Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c9e17e4a12 | ||
|
|
78908932c5 | ||
|
|
5f1a613b48 | ||
|
|
18c3dbaee0 | ||
|
|
6775988347 | ||
|
|
2580797633 | ||
|
|
28929fd61e | ||
|
|
2445e7f8b6 | ||
|
|
0af6403570 | ||
|
|
55018ca228 | ||
|
|
64bd918f32 | ||
|
|
fb6a3a7bcf | ||
|
|
4d4aa86399 | ||
|
|
1dce65cecb | ||
|
|
c1145ae111 | ||
|
|
19f029f17f | ||
|
|
916a8c0c55 |
No files matched your search
@@ -1,10 +0,0 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "monthly"
|
||||
- package-ecosystem: "maven"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "monthly"
|
||||
+22
-34
@@ -8,15 +8,25 @@ jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Checkout Code
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- uses: actions/setup-java@v3
|
||||
- name: Set Up Java
|
||||
uses: actions/setup-java@v2
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
distribution: 'adopt'
|
||||
java-version: '17'
|
||||
cache: 'maven'
|
||||
|
||||
# Install Spigot dependencies if necessary.
|
||||
# Use cache to speed up build
|
||||
- name: Cache Maven Repo
|
||||
uses: actions/cache@v2
|
||||
id: cache
|
||||
with:
|
||||
path: ~/.m2/repository
|
||||
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
|
||||
|
||||
# Install Spigot dependencies.
|
||||
# This script uses Maven to check all required installations and ensure that they are present.
|
||||
- name: Install Spigot Dependencies
|
||||
run: . scripts/install_spigot_dependencies.sh
|
||||
|
||||
@@ -26,59 +36,37 @@ jobs:
|
||||
# Upload artifacts
|
||||
- name: Upload Distributable Jar
|
||||
id: upload-final
|
||||
uses: actions/upload-artifact@v3
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: dist
|
||||
path: ./target/OpenInv.jar
|
||||
- name: Upload API Jar
|
||||
id: upload-api
|
||||
uses: actions/upload-artifact@v3
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: api
|
||||
path: ./api/target/openinvapi*.jar
|
||||
|
||||
merge-dependabot:
|
||||
name: Auto-merge Dependabot PRs
|
||||
needs: [ build ]
|
||||
if: "github.event.name == 'pull_request_target'
|
||||
&& github.actor == 'dependabot[bot]'
|
||||
&& contains( github.event.pull_request.labels.*.name, 'java')"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Approve
|
||||
uses: hmarr/auto-approve-action@v2.2.1
|
||||
with:
|
||||
github-token: "${{ secrets.GITHUB_TOKEN }}"
|
||||
- name: Merge
|
||||
uses: pascalgn/automerge-action@v0.15.3
|
||||
env:
|
||||
GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}"
|
||||
MERGE_LABELS: "dependencies"
|
||||
MERGE_METHOD: "squash"
|
||||
|
||||
release:
|
||||
name: Create Github Release
|
||||
needs: [ build ]
|
||||
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
# Fetch all history - used to assemble changelog.
|
||||
- uses: actions/checkout@v3
|
||||
- name: Checkout Code
|
||||
uses: actions/checkout@v2
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set Release Variables
|
||||
run: bash ./scripts/set_release_env.sh
|
||||
|
||||
- name: Download Artifact
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: dist
|
||||
path: dist
|
||||
- name: Download Artifacts
|
||||
uses: actions/download-artifact@v2
|
||||
|
||||
- name: Create Release
|
||||
id: create-release
|
||||
uses: softprops/action-gh-release@v0.1.14
|
||||
uses: softprops/action-gh-release@v0.1.5
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
|
||||
@@ -14,7 +14,7 @@ jobs:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Fetch Github Release Asset
|
||||
uses: dsaltares/fetch-gh-release-asset@1.0.0
|
||||
uses: dsaltares/fetch-gh-release-asset@0.0.5
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
version: ${{ github.event.release.id }}
|
||||
@@ -26,7 +26,7 @@ jobs:
|
||||
- name: Create CurseForge Release
|
||||
uses: itsmeow/curseforge-upload@v3
|
||||
with:
|
||||
token: "${{ secrets.CURSEFORGE_TOKEN }}"
|
||||
token: ${{ secrets.CURSEFORGE_TOKEN }}
|
||||
project_id: 31432
|
||||
game_endpoint: minecraft
|
||||
file_path: ./OpenInv.jar
|
||||
|
||||
@@ -124,16 +124,22 @@ The OpenInv API is available via [JitPack](https://jitpack.io/).
|
||||
```
|
||||
|
||||
### Compilation
|
||||
To compile, the relevant Spigot jars must be installed in the local repository.
|
||||
As OpenInv is compiled against Mojang's mappings, you must run BuildTools with the `--remapped` argument:
|
||||
`java -jar BuildTools.jar --remapped --rev $serverVersion`
|
||||
`$serverVersion` is the version of the server, i.e. `1.18.1`
|
||||
To compile, the relevant Spigot jars must be installed in your local repository using the `install` plugin:
|
||||
```shell
|
||||
mvn install:install-file -Dpackaging=jar -Dfile=spigot-1.8-R0.1-SNAPSHOT.jar \
|
||||
-DgroupId=org.spigotmc -DartifactId=spigot -Dversion=1.8-R0.1-SNAPSHOT
|
||||
```
|
||||
Note that BuildTools automatically installs produced files. If you use BuildTools to compile Spigot locally, you don't need to install it manually.
|
||||
If you want to use Paper as a dependency, you can install it by executing PaperClip with the property `paperclip.install` set to true:
|
||||
```shell
|
||||
wget -O paperclip.jar https://papermc.io/api/v1/paper/1.16.5/latest/download
|
||||
java -jar -Dpaperclip.install=true paperclip.jar
|
||||
```
|
||||
|
||||
To compile for a single version, specify the module you are targeting:
|
||||
`mvn -pl $moduleName -am clean install`
|
||||
`$moduleName` is the name of the module, i.e. `internal/v1_18_R1`.
|
||||
To compile for a single version, specify the NMS revision you are targeting: `mvn -pl <NMS module> -am clean install`
|
||||
|
||||
To compile for a set of versions, you'll need to use a profile. The only provided profile is `all`. Select a profile using the `-P` argument: `mvn clean package -am -P all`
|
||||
|
||||
To compile for a set of versions, use a profile. Select a profile using the `-P` argument:
|
||||
`mvn clean package -am -P all`
|
||||
The only provided profile is `all`. The final file is `target/OpenInv.jar`
|
||||
For more information, check out the [official Maven guide](http://maven.apache.org/guides/introduction/introduction-to-profiles.html).
|
||||
|
||||
The final file is `target/OpenInv.jar`
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
<!--
|
||||
~ Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
~ Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
~
|
||||
~ 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
|
||||
@@ -21,7 +21,7 @@
|
||||
<parent>
|
||||
<artifactId>openinvparent</artifactId>
|
||||
<groupId>com.lishid</groupId>
|
||||
<version>4.2.0</version>
|
||||
<version>4.1.9-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>openinvapi</artifactId>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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
|
||||
@@ -36,120 +36,53 @@ import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Interface defining behavior for the OpenInv plugin.
|
||||
*
|
||||
* @author Jikoo
|
||||
*/
|
||||
public interface IOpenInv {
|
||||
|
||||
/**
|
||||
* Check if the server version is supported by OpenInv.
|
||||
*
|
||||
* @return true if the server version is supported
|
||||
*/
|
||||
boolean isSupportedVersion();
|
||||
|
||||
/**
|
||||
* Check the configuration value for whether OpenInv saves player data when unloading players. This is exclusively
|
||||
* for users who do not allow editing of inventories, only viewing, and wish to prevent any possibility of bugs such
|
||||
* as lishid#40. If true, OpenInv will not ever save any edits made to players.
|
||||
* Check the configuration value for whether or not OpenInv saves player data when unloading
|
||||
* players. This is exclusively for users who do not allow editing of inventories, only viewing,
|
||||
* and wish to prevent any possibility of bugs such as lishid#40. If true, OpenInv will not ever
|
||||
* save any edits made to players.
|
||||
*
|
||||
* @return false unless configured otherwise
|
||||
*/
|
||||
boolean disableSaving();
|
||||
|
||||
/**
|
||||
* Check the configuration value for whether OpenInv allows offline access. If true, OpenInv will not load or allow
|
||||
* modification of players while they are not online. This does not prevent other plugins from using existing loaded
|
||||
* players who have gone offline.
|
||||
* Gets the active ISilentContainer implementation.
|
||||
*
|
||||
* @return false unless configured otherwise
|
||||
* @since 4.2.0
|
||||
*/
|
||||
boolean disableOfflineAccess();
|
||||
|
||||
/**
|
||||
* Get the active {@link IAnySilentContainer} implementation.
|
||||
*
|
||||
* @return the active implementation for the server version
|
||||
* @return the ISilentContainer
|
||||
* @throws IllegalStateException if the server version is unsupported
|
||||
*/
|
||||
@NotNull IAnySilentContainer getAnySilentContainer();
|
||||
|
||||
/**
|
||||
* @deprecated Use static {@link InventoryAccess} methods.
|
||||
* Gets the active IInventoryAccess implementation.
|
||||
*
|
||||
* @return the IInventoryAccess
|
||||
* @throws IllegalStateException if the server version is unsupported
|
||||
*/
|
||||
@Deprecated(forRemoval = true)
|
||||
@Deprecated
|
||||
default @NotNull IInventoryAccess getInventoryAccess() {
|
||||
return new InventoryAccess();
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use {@link #getAnyContainerStatus(OfflinePlayer)}. Not all containers are chests.
|
||||
*/
|
||||
@Deprecated(forRemoval = true, since = "4.2.0")
|
||||
default boolean getPlayerAnyChestStatus(@NotNull OfflinePlayer offline) {
|
||||
return getAnyContainerStatus(offline);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get whether a user has AnyContainer mode enabled.
|
||||
* Gets the provided player's AnyChest setting.
|
||||
*
|
||||
* @param offline the user to obtain the state of
|
||||
* @return true if AnyContainer mode is enabled
|
||||
* @param player the OfflinePlayer
|
||||
* @return true if AnyChest is enabled
|
||||
* @throws IllegalStateException if the server version is unsupported
|
||||
*/
|
||||
boolean getAnyContainerStatus(@NotNull OfflinePlayer offline);
|
||||
boolean getPlayerAnyChestStatus(@NotNull OfflinePlayer player);
|
||||
|
||||
/**
|
||||
* @deprecated Use {@link #setAnyContainerStatus(OfflinePlayer, boolean)}. Not all containers are chests.
|
||||
*/
|
||||
@Deprecated(forRemoval = true, since = "4.2.0")
|
||||
default void setPlayerAnyChestStatus(@NotNull OfflinePlayer offline, boolean status) {
|
||||
setAnyContainerStatus(offline, status);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set whether a user has AnyContainer mode enabled.
|
||||
* Gets a unique identifier by which the OfflinePlayer can be referenced. Using the value
|
||||
* returned to look up a Player will generally be much faster for later implementations.
|
||||
*
|
||||
* @param offline the user to set the state of
|
||||
* @param status the state of the mode
|
||||
*/
|
||||
void setAnyContainerStatus(@NotNull OfflinePlayer offline, boolean status);
|
||||
|
||||
/**
|
||||
* @deprecated Use {@link #getSilentContainerStatus(OfflinePlayer)}. Not all containers are chests.
|
||||
*/
|
||||
@Deprecated(forRemoval = true, since = "4.2.0")
|
||||
default boolean getPlayerSilentChestStatus(@NotNull OfflinePlayer offline) {
|
||||
return getSilentContainerStatus(offline);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get whether a user has SilentContainer mode enabled.
|
||||
*
|
||||
* @param offline the user to obtain the state of
|
||||
* @return true if SilentContainer mode is enabled
|
||||
*/
|
||||
boolean getSilentContainerStatus(@NotNull OfflinePlayer offline);
|
||||
|
||||
/**
|
||||
* @deprecated Use {@link #setSilentContainerStatus(OfflinePlayer, boolean)}. Not all containers are chests.
|
||||
*/
|
||||
@Deprecated(forRemoval = true, since = "4.2.0")
|
||||
default void setPlayerSilentChestStatus(@NotNull OfflinePlayer offline, boolean status) {
|
||||
setSilentContainerStatus(offline, status);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set whether a user has SilentContainer mode enabled.
|
||||
*
|
||||
* @param offline the user to set the state of
|
||||
* @param status the state of the mode
|
||||
*/
|
||||
void setSilentContainerStatus(@NotNull OfflinePlayer offline, boolean status);
|
||||
|
||||
/**
|
||||
* Get a unique identifier by which the OfflinePlayer can be referenced.
|
||||
*
|
||||
* @deprecated Use {@link OfflinePlayer#getUniqueId()} and {@link UUID#toString()}. This was necessary for non-UUID
|
||||
* versions of Minecraft, but support for them has been dropped for years.
|
||||
* @param offline the OfflinePlayer
|
||||
* @return the identifier
|
||||
* @throws IllegalStateException if the server version is unsupported
|
||||
@@ -159,65 +92,61 @@ public interface IOpenInv {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an {@link ISpecialEnderChest} for a user.
|
||||
* Gets a player's SilentChest setting.
|
||||
*
|
||||
* @param player the {@link Player} owning the inventory
|
||||
* @param online whether the owner is currently online
|
||||
* @return the created inventory
|
||||
* @param offline the OfflinePlayer
|
||||
* @return true if SilentChest is enabled
|
||||
* @throws IllegalStateException if the server version is unsupported
|
||||
* @throws InstantiationException if there was an issue creating the inventory
|
||||
*/
|
||||
boolean getPlayerSilentChestStatus(@NotNull OfflinePlayer offline);
|
||||
|
||||
/**
|
||||
* Gets an ISpecialEnderChest for the given Player.
|
||||
*
|
||||
* @param player the Player
|
||||
* @param online true if the Player is currently online
|
||||
* @return the ISpecialEnderChest
|
||||
* @throws IllegalStateException if the server version is unsupported
|
||||
* @throws InstantiationException if the ISpecialEnderChest could not be instantiated
|
||||
*/
|
||||
@NotNull ISpecialEnderChest getSpecialEnderChest(@NotNull Player player, boolean online) throws InstantiationException;
|
||||
|
||||
/**
|
||||
* Get an {@link ISpecialPlayerInventory} for a user.
|
||||
* Gets an ISpecialPlayerInventory for the given Player.
|
||||
*
|
||||
* @param player the {@link Player} owning the inventory
|
||||
* @param online whether the owner is currently online
|
||||
* @return the created inventory
|
||||
* @throws IllegalStateException if the server version is unsupported
|
||||
* @throws InstantiationException if there was an issue creating the inventory
|
||||
* @param player the Player
|
||||
* @param online true if the Player is currently online
|
||||
* @return the ISpecialPlayerInventory
|
||||
* @throws IllegalStateException if the server version is unsupported
|
||||
* @throws InstantiationException if the ISpecialPlayerInventory could not be instantiated
|
||||
*/
|
||||
@NotNull ISpecialPlayerInventory getSpecialInventory(@NotNull Player player, boolean online) throws InstantiationException;
|
||||
|
||||
/**
|
||||
* Open an {@link ISpecialInventory} for a {@link Player}.
|
||||
* Checks if the server version is supported by OpenInv.
|
||||
*
|
||||
* @param player the viewer
|
||||
* @param inventory the inventory to open
|
||||
* @return the resulting {@link InventoryView}
|
||||
* @return true if the server version is supported
|
||||
*/
|
||||
@Nullable InventoryView openInventory(@NotNull Player player, @NotNull ISpecialInventory inventory);
|
||||
boolean isSupportedVersion();
|
||||
|
||||
/**
|
||||
* Check if a {@link Player} is currently loaded by OpenInv.
|
||||
* Load a Player from an OfflinePlayer. May return null under some circumstances.
|
||||
*
|
||||
* @param playerUuid the {@link UUID} of the {@code Player}
|
||||
* @return whether the {@code Player} is loaded
|
||||
* @since 4.2.0
|
||||
*/
|
||||
boolean isPlayerLoaded(@NotNull UUID playerUuid);
|
||||
|
||||
/**
|
||||
* Load a {@link Player} from an {@link OfflinePlayer}. If the user has not played before or the default world for
|
||||
* the server is not loaded, this will return {@code null}.
|
||||
*
|
||||
* @param offline the {@code OfflinePlayer} to load a {@code Player} for
|
||||
* @return the loaded {@code Player}
|
||||
* @param offline the OfflinePlayer to load a Player for
|
||||
* @return the Player, or null
|
||||
* @throws IllegalStateException if the server version is unsupported
|
||||
*/
|
||||
@Nullable Player loadPlayer(@NotNull final OfflinePlayer offline);
|
||||
|
||||
/**
|
||||
* Match an existing {@link OfflinePlayer}. If the name is a {@link UUID#toString() UUID string}, this will only
|
||||
* return the user if they have actually played on the server before, unlike {@link Bukkit#getOfflinePlayer(UUID)}.
|
||||
*
|
||||
* <p>This method is potentially very heavily blocking. It should not ever be called on the
|
||||
* Get an OfflinePlayer by name.
|
||||
* <p>
|
||||
* Note: This method is potentially very heavily blocking. It should not ever be called on the
|
||||
* main thread, and if it is, a stack trace will be displayed alerting server owners to the
|
||||
* call.
|
||||
*
|
||||
* @param name the string to match
|
||||
* @return the user with the closest matching name
|
||||
* @param name the name of the Player
|
||||
* @return the OfflinePlayer with the closest matching name or null if no players have ever logged in
|
||||
*/
|
||||
default @Nullable OfflinePlayer matchPlayer(@NotNull String name) {
|
||||
|
||||
@@ -225,7 +154,7 @@ public interface IOpenInv {
|
||||
if (Bukkit.getServer().isPrimaryThread()) {
|
||||
this.getLogger().warning("Call to OpenInv#matchPlayer made on the main thread!");
|
||||
this.getLogger().warning("This can cause the server to hang, potentially severely.");
|
||||
this.getLogger().log(Level.WARNING, "Current stack trace", new Throwable("Current stack trace"));
|
||||
this.getLogger().log(Level.WARNING, new Throwable("Current stack trace"), () -> "Current stack trace");
|
||||
}
|
||||
|
||||
OfflinePlayer player;
|
||||
@@ -233,38 +162,32 @@ public interface IOpenInv {
|
||||
try {
|
||||
UUID uuid = UUID.fromString(name);
|
||||
player = Bukkit.getOfflinePlayer(uuid);
|
||||
// Ensure player is an existing player.
|
||||
// Ensure player is a real player, otherwise return null
|
||||
if (player.hasPlayedBefore() || player.isOnline()) {
|
||||
return player;
|
||||
}
|
||||
// Return null otherwise.
|
||||
return null;
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
// Not a UUID
|
||||
}
|
||||
|
||||
// Exact online match first.
|
||||
player = Bukkit.getServer().getPlayerExact(name);
|
||||
|
||||
if (player != null) {
|
||||
return player;
|
||||
}
|
||||
|
||||
// Exact offline match second - ensure offline access works when matchable users are online.
|
||||
player = Bukkit.getServer().getOfflinePlayer(name);
|
||||
|
||||
if (player.hasPlayedBefore()) {
|
||||
return player;
|
||||
}
|
||||
|
||||
// Inexact online match.
|
||||
player = Bukkit.getServer().getPlayer(name);
|
||||
|
||||
if (player != null) {
|
||||
return player;
|
||||
}
|
||||
|
||||
// Finally, inexact offline match.
|
||||
float bestMatch = 0;
|
||||
for (OfflinePlayer offline : Bukkit.getServer().getOfflinePlayers()) {
|
||||
if (offline.getName() == null) {
|
||||
@@ -289,58 +212,96 @@ public interface IOpenInv {
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated OpenInv uses action bar chat for notifications. Whether they show is based on language settings.
|
||||
* Open an ISpecialInventory for a Player.
|
||||
*
|
||||
* @param player the Player
|
||||
* @param inventory the ISpecialInventory
|
||||
* @return the InventoryView for the opened ISpecialInventory
|
||||
*/
|
||||
@Deprecated(forRemoval = true)
|
||||
@Nullable InventoryView openInventory(@NotNull Player player, @NotNull ISpecialInventory inventory);
|
||||
|
||||
/**
|
||||
* Check the configuration value for whether or not OpenInv displays a notification to the user
|
||||
* when a container is activated with AnyChest.
|
||||
*
|
||||
* @return true unless configured otherwise
|
||||
* @deprecated OpenInv uses action bar chat for notifications. Whether or not they show is based on language settings.
|
||||
*/
|
||||
@Deprecated
|
||||
default boolean notifyAnyChest() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated OpenInv uses action bar chat for notifications. Whether they show is based on language settings.
|
||||
* Check the configuration value for whether or not OpenInv displays a notification to the user
|
||||
* when a container is activated with SilentChest.
|
||||
*
|
||||
* @return true unless configured otherwise
|
||||
* @deprecated OpenInv uses action bar chat for notifications. Whether or not they show is based on language settings.
|
||||
*/
|
||||
@Deprecated(forRemoval = true)
|
||||
@Deprecated
|
||||
default boolean notifySilentChest() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated see {@link #retainPlayer(Player, Plugin)}
|
||||
* Mark a Player as no longer in use by a Plugin to allow OpenInv to remove it from the cache
|
||||
* when eligible.
|
||||
*
|
||||
* @param player the Player
|
||||
* @param plugin the Plugin no longer holding a reference to the Player
|
||||
* @throws IllegalStateException if the server version is unsupported
|
||||
*/
|
||||
@Deprecated(forRemoval = true, since = "4.2.0")
|
||||
default void releasePlayer(@NotNull Player player, @NotNull Plugin plugin) {}
|
||||
void releasePlayer(@NotNull Player player, @NotNull Plugin plugin);
|
||||
|
||||
/**
|
||||
* @deprecated OpenInv no longer uses an internal cache beyond maintaining copies of currently open inventories.
|
||||
* If you wish to use/modify a player, ensure either {@link IOpenInv#isPlayerLoaded(UUID)} is false or the player
|
||||
* instance is the same memory address as the one in use by OpenInv.
|
||||
* <pre>
|
||||
* public @NotNull Player savePlayerData(@NotNull Player player) {
|
||||
* IOpenInv openInv = ...
|
||||
* if (!openInv.disableSaving() && openInv.isPlayerLoaded(player.getUniqueId())) {
|
||||
* Player openInvLoadedPlayer = openInv.loadPlayer(myInUsePlayer);
|
||||
* if (openInvLoadedPlayer != player) {
|
||||
* // The copy loaded by OpenInv is not the same as our loaded copy. Push our changes.
|
||||
* copyPlayerModifications(player, openInvLoadedPlayer);
|
||||
* }
|
||||
* // OpenInv will handle saving data when the player is unloaded.
|
||||
* // Optionally, to be sure our changes will persist, save now.
|
||||
* // openInvLoadedPlayer.saveData();
|
||||
* return openInvLoadedPlayer;
|
||||
* }
|
||||
* Mark a Player as in use by a Plugin to prevent it from being removed from the cache. Used to
|
||||
* prevent issues with multiple copies of the same Player being loaded such as lishid#49.
|
||||
* Changes made to loaded copies overwrite changes to the others when saved, leading to
|
||||
* duplication bugs and more.
|
||||
* <p>
|
||||
* When finished with the Player object, be sure to call {@link #releasePlayer(Player, Plugin)}
|
||||
* to prevent the cache from keeping it stored until the plugin is disabled.
|
||||
* <p>
|
||||
* When using a Player object from OpenInv, you must handle the Player coming online, replacing
|
||||
* your Player reference with the Player from the PlayerJoinEvent. In addition, you must change
|
||||
* any values in the Player to reflect any unsaved alterations to the existing Player which do
|
||||
* not affect the inventory or ender chest contents.
|
||||
* <p>
|
||||
* OpenInv only saves player data when unloading a Player from the cache, and then only if
|
||||
* {@link #disableSaving()} returns false. If you are making changes that OpenInv does not cause
|
||||
* to persist when a Player logs in as noted above, it is suggested that you manually call
|
||||
* {@link Player#saveData()} when releasing your reference to ensure your changes persist.
|
||||
*
|
||||
* player.saveData();
|
||||
* return player;
|
||||
* }
|
||||
* </pre>
|
||||
* @param player the Player
|
||||
* @param plugin the Plugin holding the reference to the Player
|
||||
* @throws IllegalStateException if the server version is unsupported
|
||||
*/
|
||||
@Deprecated(forRemoval = true, since = "4.2.0")
|
||||
default void retainPlayer(@NotNull Player player, @NotNull Plugin plugin) {}
|
||||
void retainPlayer(@NotNull Player player, @NotNull Plugin plugin);
|
||||
|
||||
/**
|
||||
* Forcibly close inventories of and unload any cached data for a user.
|
||||
* Sets a player's AnyChest setting.
|
||||
*
|
||||
* @param offline the {@link OfflinePlayer} to unload
|
||||
* @param offline the OfflinePlayer
|
||||
* @param status the status
|
||||
* @throws IllegalStateException if the server version is unsupported
|
||||
*/
|
||||
void setPlayerAnyChestStatus(@NotNull OfflinePlayer offline, boolean status);
|
||||
|
||||
/**
|
||||
* Sets a player's SilentChest setting.
|
||||
*
|
||||
* @param offline the OfflinePlayer
|
||||
* @param status the status
|
||||
* @throws IllegalStateException if the server version is unsupported
|
||||
*/
|
||||
void setPlayerSilentChestStatus(@NotNull OfflinePlayer offline, boolean status);
|
||||
|
||||
/**
|
||||
* Forcibly unload a cached Player's data.
|
||||
*
|
||||
* @param offline the OfflinePlayer to unload
|
||||
* @throws IllegalStateException if the server version is unsupported
|
||||
*/
|
||||
void unload(@NotNull OfflinePlayer offline);
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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
|
||||
@@ -33,38 +33,39 @@ import org.jetbrains.annotations.NotNull;
|
||||
public interface IAnySilentContainer {
|
||||
|
||||
/**
|
||||
* Forcibly open the container at the given coordinates for the Player. This will open blocked containers! Be sure
|
||||
* to check {@link #isAnyContainerNeeded(Block)} first if that is not desirable.
|
||||
* Opens the container at the given coordinates for the Player. If you do not want blocked
|
||||
* containers to open, be sure to check {@link #isAnyContainerNeeded(Player, Block)}
|
||||
* first.
|
||||
*
|
||||
* @param player the {@link Player} opening the container
|
||||
* @param silent whether the container's noise is to be silenced
|
||||
* @param block the {@link Block} of the container
|
||||
* @param player the Player opening the container
|
||||
* @param silent whether the container's noise is to be silenced
|
||||
* @param block the Block
|
||||
* @return true if the container can be opened
|
||||
*/
|
||||
boolean activateContainer(@NotNull Player player, boolean silent, @NotNull Block block);
|
||||
|
||||
/**
|
||||
* Perform operations required to close the current container silently.
|
||||
* Closes the Player's currently open container silently, if necessary.
|
||||
*
|
||||
* @param player the {@link Player} closing a container
|
||||
* @param player the Player closing a container
|
||||
*/
|
||||
void deactivateContainer(@NotNull Player player);
|
||||
|
||||
/**
|
||||
* @param player the player opening the container
|
||||
* @param block the {@link Block} of the container
|
||||
* @return true if the container is blocked
|
||||
* @deprecated use {@link #isAnyContainerNeeded(Block)}
|
||||
* @param player the player opening the container
|
||||
* @param block the block
|
||||
* @return true if the container is blocked
|
||||
*/
|
||||
@Deprecated(forRemoval = true, since = "4.1.9")
|
||||
@Deprecated
|
||||
default boolean isAnyContainerNeeded(@NotNull Player player, @NotNull Block block) {
|
||||
return isAnyContainerNeeded(block);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the container at the given coordinates is blocked.
|
||||
* Checks if the container at the given coordinates is blocked.
|
||||
*
|
||||
* @param block the {@link Block} of the container
|
||||
* @param block the Block
|
||||
* @return true if the container is blocked
|
||||
*/
|
||||
default boolean isAnyContainerNeeded(@NotNull Block block) {
|
||||
@@ -81,8 +82,8 @@ public interface IAnySilentContainer {
|
||||
}
|
||||
|
||||
// Shulker boxes require 1/2 a block clear in the direction they open.
|
||||
if (blockState instanceof ShulkerBox shulker) {
|
||||
if (isShulkerBlocked(shulker)) {
|
||||
if (blockState instanceof ShulkerBox) {
|
||||
if (isShulkerBlocked((ShulkerBox) blockState)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -96,10 +97,11 @@ public interface IAnySilentContainer {
|
||||
}
|
||||
|
||||
BlockData blockData = block.getBlockData();
|
||||
if (!(blockData instanceof Chest chest) || ((Chest) blockData).getType() == Chest.Type.SINGLE) {
|
||||
if (!(blockData instanceof Chest) || ((Chest) blockData).getType() == Chest.Type.SINGLE) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Chest chest = (Chest) blockData;
|
||||
int ordinal = (chest.getFacing().ordinal() + 4 + (chest.getType() == Chest.Type.RIGHT ? -1 : 1)) % 4;
|
||||
BlockFace relativeFace = BlockFace.values()[ordinal];
|
||||
org.bukkit.block.Block relative = block.getRelative(relativeFace);
|
||||
@@ -109,10 +111,11 @@ public interface IAnySilentContainer {
|
||||
}
|
||||
|
||||
BlockData relativeData = relative.getBlockData();
|
||||
if (!(relativeData instanceof Chest relativeChest)) {
|
||||
if (!(relativeData instanceof Chest)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Chest relativeChest = (Chest) relativeData;
|
||||
if (relativeChest.getFacing() != chest.getFacing()
|
||||
|| relativeChest.getType() != (chest.getType() == Chest.Type.RIGHT ? Chest.Type.LEFT : Chest.Type.RIGHT)) {
|
||||
return false;
|
||||
@@ -121,31 +124,25 @@ public interface IAnySilentContainer {
|
||||
return isChestBlocked(relative);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a {@link ShulkerBox} cannot be opened under ordinary circumstances.
|
||||
*
|
||||
* @param shulkerBox the shulker box container
|
||||
* @return whether the container is blocked
|
||||
*/
|
||||
boolean isShulkerBlocked(@NotNull ShulkerBox shulkerBox);
|
||||
boolean isShulkerBlocked(ShulkerBox block);
|
||||
|
||||
/**
|
||||
* Check if a chest cannot be opened under ordinary circumstances.
|
||||
* Determine whether or not a chest is blocked.
|
||||
*
|
||||
* @param chest the chest block
|
||||
* @return whether the container is blocked
|
||||
* @return true if the chest block cannot be opened under ordinary circumstances
|
||||
*/
|
||||
default boolean isChestBlocked(@NotNull Block chest) {
|
||||
default boolean isChestBlocked(Block chest) {
|
||||
org.bukkit.block.Block relative = chest.getRelative(0, 1, 0);
|
||||
return relative.getType().isOccluding()
|
||||
|| chest.getWorld().getNearbyEntities(BoundingBox.of(relative), entity -> entity instanceof Cat).size() > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the given {@link Block} is a container which can be unblocked or silenced.
|
||||
* Checks if the given block is a container which can be unblocked or silenced.
|
||||
*
|
||||
* @param block the potential container
|
||||
* @return true if the type is a supported container
|
||||
* @param block the BlockState
|
||||
* @return true if the Block is a supported container
|
||||
*/
|
||||
default boolean isAnySilentContainer(@NotNull Block block) {
|
||||
if (block.getType() == Material.ENDER_CHEST) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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
|
||||
@@ -16,47 +16,49 @@
|
||||
|
||||
package com.lishid.openinv.internal;
|
||||
|
||||
import com.lishid.openinv.util.InventoryAccess;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* @deprecated Use static {@link InventoryAccess} methods.
|
||||
*/
|
||||
@Deprecated(forRemoval = true)
|
||||
@Deprecated
|
||||
public interface IInventoryAccess {
|
||||
|
||||
/**
|
||||
* @deprecated Use static {@link InventoryAccess} methods.
|
||||
* Gets an ISpecialEnderChest from an Inventory or null if the Inventory is not backed by an
|
||||
* ISpecialEnderChest.
|
||||
*
|
||||
* @param inventory the Inventory
|
||||
* @return the ISpecialEnderChest or null
|
||||
*/
|
||||
@Deprecated(forRemoval = true)
|
||||
default @Nullable ISpecialEnderChest getSpecialEnderChest(@NotNull Inventory inventory) {
|
||||
return InventoryAccess.getEnderChest(inventory);
|
||||
}
|
||||
@Deprecated
|
||||
@Nullable ISpecialEnderChest getSpecialEnderChest(@NotNull Inventory inventory);
|
||||
|
||||
/**
|
||||
* @deprecated Use static {@link InventoryAccess} methods.
|
||||
* Gets an ISpecialPlayerInventory from an Inventory or null if the Inventory is not backed by
|
||||
* an ISpecialPlayerInventory.
|
||||
*
|
||||
* @param inventory the Inventory
|
||||
* @return the ISpecialPlayerInventory or null
|
||||
*/
|
||||
@Deprecated(forRemoval = true)
|
||||
default @Nullable ISpecialPlayerInventory getSpecialPlayerInventory(@NotNull Inventory inventory) {
|
||||
return InventoryAccess.getPlayerInventory(inventory);
|
||||
}
|
||||
@Deprecated
|
||||
@Nullable ISpecialPlayerInventory getSpecialPlayerInventory(@NotNull Inventory inventory);
|
||||
|
||||
/**
|
||||
* @deprecated Use static {@link InventoryAccess} methods.
|
||||
* Check if an Inventory is an ISpecialEnderChest implementation.
|
||||
*
|
||||
* @param inventory the Inventory
|
||||
* @return true if the Inventory is backed by an ISpecialEnderChest
|
||||
*/
|
||||
@Deprecated(forRemoval = true)
|
||||
default boolean isSpecialEnderChest(@NotNull Inventory inventory) {
|
||||
return InventoryAccess.isEnderChest(inventory);
|
||||
}
|
||||
@Deprecated
|
||||
boolean isSpecialEnderChest(@NotNull Inventory inventory);
|
||||
|
||||
/**
|
||||
* @deprecated Use static {@link InventoryAccess} methods.
|
||||
* Check if an Inventory is an ISpecialPlayerInventory implementation.
|
||||
*
|
||||
* @param inventory the Inventory
|
||||
* @return true if the Inventory is backed by an ISpecialPlayerInventory
|
||||
*/
|
||||
@Deprecated(forRemoval = true)
|
||||
default boolean isSpecialPlayerInventory(@NotNull Inventory inventory) {
|
||||
return InventoryAccess.isPlayerInventory(inventory);
|
||||
}
|
||||
@Deprecated
|
||||
boolean isSpecialPlayerInventory(@NotNull Inventory inventory);
|
||||
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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
|
||||
@@ -16,9 +16,6 @@
|
||||
|
||||
package com.lishid.openinv.internal;
|
||||
|
||||
/**
|
||||
* An {@link ISpecialInventory} representing an ender chest.
|
||||
*/
|
||||
public interface ISpecialEnderChest extends ISpecialInventory {
|
||||
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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
|
||||
@@ -21,43 +21,38 @@ import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* Interface defining behavior for special inventories backed by other inventories' content listings.
|
||||
*/
|
||||
public interface ISpecialInventory {
|
||||
|
||||
/**
|
||||
* Get the {@link Inventory} associated with this {@code ISpecialInventory}.
|
||||
* Gets the Inventory associated with this ISpecialInventory.
|
||||
*
|
||||
* @return the Bukkit inventory
|
||||
* @return the Inventory
|
||||
*/
|
||||
@NotNull Inventory getBukkitInventory();
|
||||
|
||||
/**
|
||||
* Set the owning {@link Player} instance to a newly-joined user.
|
||||
* Sets the Player associated with this ISpecialInventory online.
|
||||
*
|
||||
* @param player the user coming online
|
||||
* @param player the Player coming online
|
||||
*/
|
||||
void setPlayerOnline(@NotNull Player player);
|
||||
|
||||
/**
|
||||
* Mark the owner of the inventory offline.
|
||||
* Sets the Player associated with this ISpecialInventory offline.
|
||||
*/
|
||||
void setPlayerOffline();
|
||||
|
||||
/**
|
||||
* Get whether the inventory is being viewed by any users.
|
||||
* Gets whether or not this ISpecialInventory is in use.
|
||||
*
|
||||
* @return true if the inventory is being viewed
|
||||
* @return true if the ISpecialInventory is in use
|
||||
*/
|
||||
default boolean isInUse() {
|
||||
return !getBukkitInventory().getViewers().isEmpty();
|
||||
}
|
||||
boolean isInUse();
|
||||
|
||||
/**
|
||||
* Get the {@link Player} who owns the inventory.
|
||||
* Gets the Player associated with this ISpecialInventory.
|
||||
*
|
||||
* @return the {@link HumanEntity} who owns the inventory
|
||||
* @return the HumanEntity
|
||||
*/
|
||||
@NotNull HumanEntity getPlayer();
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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
|
||||
@@ -16,35 +16,6 @@
|
||||
|
||||
package com.lishid.openinv.internal;
|
||||
|
||||
import java.util.List;
|
||||
import org.bukkit.entity.HumanEntity;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
|
||||
/**
|
||||
* An {@link ISpecialInventory} representing a player inventory.
|
||||
*/
|
||||
public interface ISpecialPlayerInventory extends ISpecialInventory {
|
||||
|
||||
/*
|
||||
* Player inventory usage varies from all other inventories - as the inventory is technically open at all times,
|
||||
* if the player is online or has been online while the inventory is open, they are in the viewer list.
|
||||
*/
|
||||
@Override
|
||||
default boolean isInUse() {
|
||||
Inventory inventory = getBukkitInventory();
|
||||
List<HumanEntity> viewers = inventory.getViewers();
|
||||
|
||||
if (viewers.size() != 1) {
|
||||
return !viewers.isEmpty();
|
||||
}
|
||||
|
||||
HumanEntity viewer = viewers.get(0);
|
||||
|
||||
if (!viewer.getUniqueId().equals(getPlayer().getUniqueId())) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return viewer.getOpenInventory().getTopInventory().equals(inventory);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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
|
||||
@@ -26,7 +26,7 @@ import org.bukkit.inventory.Inventory;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public final class InventoryAccess implements IInventoryAccess {
|
||||
public class InventoryAccess implements IInventoryAccess {
|
||||
|
||||
private static Class<?> craftInventory = null;
|
||||
private static Method getInventory = null;
|
||||
@@ -35,14 +35,16 @@ public final class InventoryAccess implements IInventoryAccess {
|
||||
String packageName = Bukkit.getServer().getClass().getPackage().getName();
|
||||
try {
|
||||
craftInventory = Class.forName(packageName + ".inventory.CraftInventory");
|
||||
} catch (ClassNotFoundException ignored) {}
|
||||
try {
|
||||
getInventory = craftInventory.getDeclaredMethod("getInventory");
|
||||
} catch (ClassNotFoundException | NoSuchMethodException ignored) {}
|
||||
} catch (NoSuchMethodException ignored) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated use {@link #isUsable()}
|
||||
*/
|
||||
@Deprecated(forRemoval = true)
|
||||
@Deprecated
|
||||
public static boolean isUseable() {
|
||||
return isUsable();
|
||||
}
|
||||
@@ -51,51 +53,25 @@ public final class InventoryAccess implements IInventoryAccess {
|
||||
return craftInventory != null && getInventory != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if an {@link Inventory} is an {@link ISpecialPlayerInventory} implementation.
|
||||
*
|
||||
* @param inventory the Bukkit inventory
|
||||
* @return true if backed by the correct implementation
|
||||
*/
|
||||
public static boolean isPlayerInventory(@NotNull Inventory inventory) {
|
||||
return getPlayerInventory(inventory) != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the {@link ISpecialPlayerInventory} backing an {@link Inventory}. Returns {@code null} if the inventory is
|
||||
* not backed by the correct class.
|
||||
*
|
||||
* @param inventory the Bukkit inventory
|
||||
* @return the backing implementation if available
|
||||
*/
|
||||
public static @Nullable ISpecialPlayerInventory getPlayerInventory(@NotNull Inventory inventory) {
|
||||
return getSpecialInventory(ISpecialPlayerInventory.class, inventory);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if an {@link Inventory} is an {@link ISpecialEnderChest} implementation.
|
||||
*
|
||||
* @param inventory the Bukkit inventory
|
||||
* @return true if backed by the correct implementation
|
||||
*/
|
||||
public static boolean isEnderChest(@NotNull Inventory inventory) {
|
||||
return getEnderChest(inventory) != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the {@link ISpecialEnderChest} backing an {@link Inventory}. Returns {@code null} if the inventory is
|
||||
* not backed by the correct class.
|
||||
*
|
||||
* @param inventory the Bukkit inventory
|
||||
* @return the backing implementation if available
|
||||
*/
|
||||
public static @Nullable ISpecialEnderChest getEnderChest(@NotNull Inventory inventory) {
|
||||
return getSpecialInventory(ISpecialEnderChest.class, inventory);
|
||||
}
|
||||
|
||||
private static <T extends ISpecialInventory> @Nullable T getSpecialInventory(@NotNull Class<T> expected, @NotNull Inventory inventory) {
|
||||
Object inv;
|
||||
if (isUsable() && craftInventory.isAssignableFrom(inventory.getClass())) {
|
||||
if (craftInventory != null && getInventory != null && craftInventory.isAssignableFrom(inventory.getClass())) {
|
||||
try {
|
||||
inv = getInventory.invoke(inventory);
|
||||
if (expected.isInstance(inv)) {
|
||||
@@ -114,10 +90,28 @@ public final class InventoryAccess implements IInventoryAccess {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Do not create a new instance to use static methods.
|
||||
*/
|
||||
@Deprecated(forRemoval = true, since = "4.2.0")
|
||||
public InventoryAccess() {}
|
||||
@Deprecated
|
||||
@Override
|
||||
public @Nullable ISpecialEnderChest getSpecialEnderChest(@NotNull Inventory inventory) {
|
||||
return getEnderChest(inventory);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
@Override
|
||||
public @Nullable ISpecialPlayerInventory getSpecialPlayerInventory(@NotNull Inventory inventory) {
|
||||
return getPlayerInventory(inventory);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
@Override
|
||||
public boolean isSpecialEnderChest(@NotNull Inventory inventory) {
|
||||
return isEnderChest(inventory);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
@Override
|
||||
public boolean isSpecialPlayerInventory(@NotNull Inventory inventory) {
|
||||
return isPlayerInventory(inventory);
|
||||
}
|
||||
|
||||
}
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
<!--
|
||||
~ Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
~ Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
~
|
||||
~ 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
|
||||
@@ -21,7 +21,7 @@
|
||||
<parent>
|
||||
<groupId>com.lishid</groupId>
|
||||
<artifactId>openinvparent</artifactId>
|
||||
<version>4.2.0</version>
|
||||
<version>4.1.9-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>openinvassembly</artifactId>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
~ Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
~
|
||||
~ 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
|
||||
@@ -23,35 +23,28 @@
|
||||
<artifactId>openinvparent</artifactId>
|
||||
<groupId>com.lishid</groupId>
|
||||
<relativePath>../../pom.xml</relativePath>
|
||||
<version>4.2.0</version>
|
||||
<version>4.1.9-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>openinvadapter1_18_R2</artifactId>
|
||||
<name>OpenInvAdapter1_18_R2</name>
|
||||
<artifactId>openinvadapter1_17_R1</artifactId>
|
||||
<name>OpenInvAdapter1_17_R1</name>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>17</maven.compiler.source>
|
||||
<maven.compiler.target>17</maven.compiler.target>
|
||||
<spigot.version>1.18.2-R0.1-SNAPSHOT</spigot.version>
|
||||
<maven.compiler.source>16</maven.compiler.source>
|
||||
<maven.compiler.target>16</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.spigotmc</groupId>
|
||||
<artifactId>spigot-api</artifactId>
|
||||
<version>${spigot.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<artifactId>spigot</artifactId>
|
||||
<groupId>org.spigotmc</groupId>
|
||||
<scope>provided</scope>
|
||||
<version>${spigot.version}</version>
|
||||
<version>1.17.1-R0.1-SNAPSHOT</version>
|
||||
<classifier>remapped-mojang</classifier>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<artifactId>openinvapi</artifactId>
|
||||
<groupId>com.lishid</groupId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<artifactId>openinvplugincore</artifactId>
|
||||
@@ -67,9 +60,8 @@
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<!-- Cannot use minimizeJar: MSHADE-366 -->
|
||||
<configuration>
|
||||
<minimizeJar>false</minimizeJar>
|
||||
<minimizeJar>true</minimizeJar>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
@@ -78,6 +70,34 @@
|
||||
<plugin>
|
||||
<groupId>net.md-5</groupId>
|
||||
<artifactId>specialsource-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>remap</goal>
|
||||
</goals>
|
||||
<id>remap-obf</id>
|
||||
<configuration>
|
||||
<srgIn>org.spigotmc:minecraft-server:1.17.1-R0.1-SNAPSHOT:txt:maps-mojang</srgIn>
|
||||
<reverse>true</reverse>
|
||||
<remappedDependencies>org.spigotmc:spigot:1.17.1-R0.1-SNAPSHOT:jar:remapped-mojang</remappedDependencies>
|
||||
<remappedArtifactAttached>true</remappedArtifactAttached>
|
||||
<remappedClassifierName>remapped-obf</remappedClassifierName>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>remap</goal>
|
||||
</goals>
|
||||
<id>remap-spigot</id>
|
||||
<configuration>
|
||||
<inputFile>${project.build.directory}/${project.artifactId}-${project.version}-remapped-obf.jar</inputFile>
|
||||
<srgIn>org.spigotmc:minecraft-server:1.17.1-R0.1-SNAPSHOT:csrg:maps-spigot</srgIn>
|
||||
<remappedDependencies>org.spigotmc:spigot:1.17.1-R0.1-SNAPSHOT:jar:remapped-obf</remappedDependencies>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
+13
-17
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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
|
||||
@@ -14,7 +14,7 @@
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.lishid.openinv.internal.v1_19_R1;
|
||||
package com.lishid.openinv.internal.v1_17_R1;
|
||||
|
||||
import com.lishid.openinv.OpenInv;
|
||||
import com.lishid.openinv.internal.IAnySilentContainer;
|
||||
@@ -24,7 +24,7 @@ import java.util.Optional;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.TextComponent;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.server.level.ServerPlayerGameMode;
|
||||
@@ -53,7 +53,7 @@ import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.Statistic;
|
||||
import org.bukkit.block.ShulkerBox;
|
||||
import org.bukkit.craftbukkit.v1_19_R1.CraftWorld;
|
||||
import org.bukkit.craftbukkit.v1_17_R1.CraftWorld;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.InventoryView;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
@@ -86,8 +86,8 @@ public class AnySilentContainer implements IAnySilentContainer {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isShulkerBlocked(@NotNull ShulkerBox shulkerBox) {
|
||||
org.bukkit.World bukkitWorld = shulkerBox.getWorld();
|
||||
public boolean isShulkerBlocked(ShulkerBox box) {
|
||||
org.bukkit.World bukkitWorld = box.getWorld();
|
||||
if (!(bukkitWorld instanceof CraftWorld)) {
|
||||
bukkitWorld = Bukkit.getWorld(bukkitWorld.getUID());
|
||||
}
|
||||
@@ -99,7 +99,7 @@ public class AnySilentContainer implements IAnySilentContainer {
|
||||
}
|
||||
|
||||
final ServerLevel world = craftWorld.getHandle();
|
||||
final BlockPos blockPosition = new BlockPos(shulkerBox.getX(), shulkerBox.getY(), shulkerBox.getZ());
|
||||
final BlockPos blockPosition = new BlockPos(box.getX(), box.getY(), box.getZ());
|
||||
final BlockEntity tile = world.getBlockEntity(blockPosition);
|
||||
|
||||
if (!(tile instanceof ShulkerBoxBlockEntity shulkerBoxBlockEntity)
|
||||
@@ -140,14 +140,14 @@ public class AnySilentContainer implements IAnySilentContainer {
|
||||
}
|
||||
|
||||
if (blockEntity instanceof EnderChestBlockEntity enderChestTile) {
|
||||
// Anychest ender chest. See net.minecraft.world.level.block.EnderChestBlock
|
||||
// Anychest ender chest. See net.minecraft.world.level.block.BlockEnderChest
|
||||
PlayerEnderChestContainer enderChest = player.getEnderChestInventory();
|
||||
enderChest.setActiveChest(enderChestTile);
|
||||
player.openMenu(new SimpleMenuProvider((containerCounter, playerInventory, ignored) -> {
|
||||
MenuType<?> containers = PlayerDataManager.getContainers(enderChest.getContainerSize());
|
||||
int rows = enderChest.getContainerSize() / 9;
|
||||
return new ChestMenu(containers, containerCounter, playerInventory, enderChest, rows);
|
||||
}, Component.translatable(("container.enderchest"))));
|
||||
}, new TextComponent("container.enderchest")));
|
||||
bukkitPlayer.incrementStatistic(Statistic.ENDERCHEST_OPENED);
|
||||
return true;
|
||||
}
|
||||
@@ -161,8 +161,8 @@ public class AnySilentContainer implements IAnySilentContainer {
|
||||
|
||||
if (block instanceof ChestBlock chestBlock) {
|
||||
|
||||
// boolean flag: do not check if chest is blocked
|
||||
Optional<MenuProvider> menuOptional = chestBlock.combine(blockState, level, blockPos, true).apply(
|
||||
// boolean flag: check if chest is blocked
|
||||
Optional<MenuProvider> menuOptional = chestBlock.combine(blockState, level, blockPos, false).apply(
|
||||
// Combiner is a copy of private ChestBlock.MENU_PROVIDER_COMBINER
|
||||
new DoubleBlockCombiner.Combiner<ChestBlockEntity, Optional<MenuProvider>>() {
|
||||
@Override
|
||||
@@ -253,13 +253,9 @@ public class AnySilentContainer implements IAnySilentContainer {
|
||||
GameType gameType = player.gameMode.getGameModeForPlayer();
|
||||
this.forceGameType(player, GameType.SPECTATOR);
|
||||
|
||||
// ServerPlayer#closeContainer cannot be called without entering an
|
||||
// infinite loop because this method is called during inventory close.
|
||||
// From ServerPlayer#closeContainer -> CraftEventFactory#handleInventoryCloseEvent
|
||||
player.containerMenu.transferTo(player.inventoryMenu, player.getBukkitEntity());
|
||||
// From ServerPlayer#closeContainer
|
||||
// Close container - note that this is very different from ServerPlayer#closeContainer!
|
||||
// Triggering event must not be re-called or we'll enter an infinite loop.
|
||||
player.doCloseContainer();
|
||||
// Regular inventory close will handle the rest - packet sending, etc.
|
||||
|
||||
// Revert forced game mode.
|
||||
this.forceGameType(player, gameType);
|
||||
+5
-5
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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
|
||||
@@ -14,7 +14,7 @@
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.lishid.openinv.internal.v1_19_R1;
|
||||
package com.lishid.openinv.internal.v1_17_R1;
|
||||
|
||||
import java.io.File;
|
||||
import net.minecraft.Util;
|
||||
@@ -23,8 +23,8 @@ import net.minecraft.nbt.NbtIo;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.level.storage.PlayerDataStorage;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.bukkit.craftbukkit.v1_19_R1.CraftServer;
|
||||
import org.bukkit.craftbukkit.v1_19_R1.entity.CraftPlayer;
|
||||
import org.bukkit.craftbukkit.v1_17_R1.CraftServer;
|
||||
import org.bukkit.craftbukkit.v1_17_R1.entity.CraftPlayer;
|
||||
|
||||
public class OpenPlayer extends CraftPlayer {
|
||||
|
||||
@@ -67,7 +67,7 @@ public class OpenPlayer extends CraftPlayer {
|
||||
File file2 = new File(worldNBTStorage.getPlayerDir(), player.getStringUUID() + ".dat_old");
|
||||
Util.safeReplaceFile(file1, file, file2);
|
||||
} catch (Exception e) {
|
||||
LogManager.getLogger().warn("Failed to save player data for {}: {}", player.getName().getString(), e.getMessage());
|
||||
LogManager.getLogger().warn("Failed to save player data for {}", player.getName().getString());
|
||||
}
|
||||
}
|
||||
|
||||
+6
-9
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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
|
||||
@@ -14,7 +14,7 @@
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.lishid.openinv.internal.v1_18_R2;
|
||||
package com.lishid.openinv.internal.v1_17_R1;
|
||||
|
||||
import com.lishid.openinv.OpenInv;
|
||||
import com.lishid.openinv.internal.IPlayerDataManager;
|
||||
@@ -35,10 +35,10 @@ import net.minecraft.world.level.Level;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.Server;
|
||||
import org.bukkit.craftbukkit.v1_18_R2.CraftServer;
|
||||
import org.bukkit.craftbukkit.v1_18_R2.entity.CraftPlayer;
|
||||
import org.bukkit.craftbukkit.v1_18_R2.event.CraftEventFactory;
|
||||
import org.bukkit.craftbukkit.v1_18_R2.inventory.CraftContainer;
|
||||
import org.bukkit.craftbukkit.v1_17_R1.CraftServer;
|
||||
import org.bukkit.craftbukkit.v1_17_R1.entity.CraftPlayer;
|
||||
import org.bukkit.craftbukkit.v1_17_R1.event.CraftEventFactory;
|
||||
import org.bukkit.craftbukkit.v1_17_R1.inventory.CraftContainer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.InventoryView;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
@@ -130,9 +130,6 @@ public class PlayerDataManager implements IPlayerDataManager {
|
||||
public Player inject(@NotNull Player player) {
|
||||
try {
|
||||
ServerPlayer nmsPlayer = getHandle(player);
|
||||
if (nmsPlayer.getBukkitEntity() instanceof OpenPlayer openPlayer) {
|
||||
return openPlayer;
|
||||
}
|
||||
injectPlayer(nmsPlayer);
|
||||
return nmsPlayer.getBukkitEntity();
|
||||
} catch (IllegalAccessException e) {
|
||||
+9
-4
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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
|
||||
@@ -14,7 +14,7 @@
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.lishid.openinv.internal.v1_18_R2;
|
||||
package com.lishid.openinv.internal.v1_17_R1;
|
||||
|
||||
import com.lishid.openinv.internal.ISpecialEnderChest;
|
||||
import java.util.List;
|
||||
@@ -33,8 +33,8 @@ import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.block.entity.EnderChestBlockEntity;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.craftbukkit.v1_18_R2.entity.CraftHumanEntity;
|
||||
import org.bukkit.craftbukkit.v1_18_R2.inventory.CraftInventory;
|
||||
import org.bukkit.craftbukkit.v1_17_R1.entity.CraftHumanEntity;
|
||||
import org.bukkit.craftbukkit.v1_17_R1.inventory.CraftInventory;
|
||||
import org.bukkit.entity.HumanEntity;
|
||||
import org.bukkit.inventory.InventoryHolder;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
@@ -60,6 +60,11 @@ public class SpecialEnderChest extends PlayerEnderChestContainer implements ISpe
|
||||
return inventory;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isInUse() {
|
||||
return !this.getViewers().isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPlayerOffline() {
|
||||
this.playerOnline = false;
|
||||
+14
-33
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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
|
||||
@@ -14,12 +14,11 @@
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.lishid.openinv.internal.v1_18_R2;
|
||||
package com.lishid.openinv.internal.v1_17_R1;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.lishid.openinv.internal.ISpecialPlayerInventory;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
@@ -33,7 +32,7 @@ import net.minecraft.nbt.ListTag;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.tags.Tag;
|
||||
import net.minecraft.world.Container;
|
||||
import net.minecraft.world.ContainerHelper;
|
||||
import net.minecraft.world.damagesource.DamageSource;
|
||||
@@ -46,8 +45,8 @@ import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.craftbukkit.v1_18_R2.entity.CraftHumanEntity;
|
||||
import org.bukkit.craftbukkit.v1_18_R2.inventory.CraftInventory;
|
||||
import org.bukkit.craftbukkit.v1_17_R1.entity.CraftHumanEntity;
|
||||
import org.bukkit.craftbukkit.v1_17_R1.inventory.CraftInventory;
|
||||
import org.bukkit.entity.HumanEntity;
|
||||
import org.bukkit.inventory.InventoryHolder;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
@@ -103,39 +102,22 @@ public class SpecialPlayerInventory extends Inventory implements ISpecialPlayerI
|
||||
this.playerOnline = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isInUse() {
|
||||
return !this.getViewers().isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull HumanEntity getPlayer() {
|
||||
return this.player.getBukkitEntity();
|
||||
}
|
||||
|
||||
private @NotNull ItemStack getRawItem(int i) {
|
||||
if (i < 0) {
|
||||
return ItemStack.EMPTY;
|
||||
}
|
||||
|
||||
NonNullList<ItemStack> list;
|
||||
for (Iterator<NonNullList<ItemStack>> iterator = this.compartments.iterator(); iterator.hasNext(); i -= list.size()) {
|
||||
list = iterator.next();
|
||||
if (i < list.size()) {
|
||||
return list.get(i);
|
||||
}
|
||||
}
|
||||
|
||||
return ItemStack.EMPTY;
|
||||
return super.getItem(i);
|
||||
}
|
||||
|
||||
private void setRawItem(int i, @NotNull ItemStack itemStack) {
|
||||
if (i < 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
NonNullList<ItemStack> list;
|
||||
for (Iterator<NonNullList<ItemStack>> iterator = this.compartments.iterator(); iterator.hasNext(); i -= list.size()) {
|
||||
list = iterator.next();
|
||||
if (i < list.size()) {
|
||||
list.set(i, itemStack);
|
||||
}
|
||||
}
|
||||
super.setItem(i, itemStack);
|
||||
}
|
||||
|
||||
private static record IndexedCompartment(@Nullable NonNullList<ItemStack> compartment, int index) {}
|
||||
@@ -743,9 +725,8 @@ public class SpecialPlayerInventory extends Inventory implements ISpecialPlayerI
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean contains(TagKey<Item> tagKey) {
|
||||
|
||||
return contains(itemStack -> !itemStack.isEmpty() && itemStack.is(tagKey));
|
||||
public boolean contains(Tag<Item> tag) {
|
||||
return contains(itemStack -> !itemStack.isEmpty() && itemStack.is(tag));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
~ Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
~
|
||||
~ 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
|
||||
@@ -23,16 +23,16 @@
|
||||
<artifactId>openinvparent</artifactId>
|
||||
<groupId>com.lishid</groupId>
|
||||
<relativePath>../../pom.xml</relativePath>
|
||||
<version>4.2.0</version>
|
||||
<version>4.1.9-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>openinvadapter1_19_R1</artifactId>
|
||||
<name>OpenInvAdapter1_19_R1</name>
|
||||
<artifactId>openinvadapter1_18_R1</artifactId>
|
||||
<name>OpenInvAdapter1_18_R1</name>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>17</maven.compiler.source>
|
||||
<maven.compiler.target>17</maven.compiler.target>
|
||||
<spigot.version>1.19-R0.1-SNAPSHOT</spigot.version>
|
||||
<spigot.version>1.18-pre5-R0.1-SNAPSHOT</spigot.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
@@ -51,7 +51,6 @@
|
||||
<dependency>
|
||||
<artifactId>openinvapi</artifactId>
|
||||
<groupId>com.lishid</groupId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<artifactId>openinvplugincore</artifactId>
|
||||
@@ -67,9 +66,8 @@
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<!-- Cannot use minimizeJar: MSHADE-366 -->
|
||||
<configuration>
|
||||
<minimizeJar>false</minimizeJar>
|
||||
<minimizeJar>true</minimizeJar>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
@@ -78,6 +76,34 @@
|
||||
<plugin>
|
||||
<groupId>net.md-5</groupId>
|
||||
<artifactId>specialsource-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>remap</goal>
|
||||
</goals>
|
||||
<id>remap-obf</id>
|
||||
<configuration>
|
||||
<srgIn>org.spigotmc:minecraft-server:${spigot.version}:txt:maps-mojang</srgIn>
|
||||
<reverse>true</reverse>
|
||||
<remappedDependencies>org.spigotmc:spigot:${spigot.version}:jar:remapped-mojang</remappedDependencies>
|
||||
<remappedArtifactAttached>true</remappedArtifactAttached>
|
||||
<remappedClassifierName>remapped-obf</remappedClassifierName>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>remap</goal>
|
||||
</goals>
|
||||
<id>remap-spigot</id>
|
||||
<configuration>
|
||||
<inputFile>${project.build.directory}/${project.artifactId}-${project.version}-remapped-obf.jar</inputFile>
|
||||
<srgIn>org.spigotmc:minecraft-server:${spigot.version}:csrg:maps-spigot</srgIn>
|
||||
<remappedDependencies>org.spigotmc:spigot:${spigot.version}:jar:remapped-obf</remappedDependencies>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
+13
-17
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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
|
||||
@@ -14,7 +14,7 @@
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.lishid.openinv.internal.v1_18_R2;
|
||||
package com.lishid.openinv.internal.v1_18_R1;
|
||||
|
||||
import com.lishid.openinv.OpenInv;
|
||||
import com.lishid.openinv.internal.IAnySilentContainer;
|
||||
@@ -24,7 +24,7 @@ import java.util.Optional;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.network.chat.TranslatableComponent;
|
||||
import net.minecraft.network.chat.TextComponent;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.server.level.ServerPlayerGameMode;
|
||||
@@ -53,7 +53,7 @@ import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.Statistic;
|
||||
import org.bukkit.block.ShulkerBox;
|
||||
import org.bukkit.craftbukkit.v1_18_R2.CraftWorld;
|
||||
import org.bukkit.craftbukkit.v1_18_R1.CraftWorld;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.InventoryView;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
@@ -86,8 +86,8 @@ public class AnySilentContainer implements IAnySilentContainer {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isShulkerBlocked(@NotNull ShulkerBox shulkerBox) {
|
||||
org.bukkit.World bukkitWorld = shulkerBox.getWorld();
|
||||
public boolean isShulkerBlocked(ShulkerBox box) {
|
||||
org.bukkit.World bukkitWorld = box.getWorld();
|
||||
if (!(bukkitWorld instanceof CraftWorld)) {
|
||||
bukkitWorld = Bukkit.getWorld(bukkitWorld.getUID());
|
||||
}
|
||||
@@ -99,7 +99,7 @@ public class AnySilentContainer implements IAnySilentContainer {
|
||||
}
|
||||
|
||||
final ServerLevel world = craftWorld.getHandle();
|
||||
final BlockPos blockPosition = new BlockPos(shulkerBox.getX(), shulkerBox.getY(), shulkerBox.getZ());
|
||||
final BlockPos blockPosition = new BlockPos(box.getX(), box.getY(), box.getZ());
|
||||
final BlockEntity tile = world.getBlockEntity(blockPosition);
|
||||
|
||||
if (!(tile instanceof ShulkerBoxBlockEntity shulkerBoxBlockEntity)
|
||||
@@ -140,14 +140,14 @@ public class AnySilentContainer implements IAnySilentContainer {
|
||||
}
|
||||
|
||||
if (blockEntity instanceof EnderChestBlockEntity enderChestTile) {
|
||||
// Anychest ender chest. See net.minecraft.world.level.block.EnderChestBlock
|
||||
// Anychest ender chest. See net.minecraft.world.level.block.BlockEnderChest
|
||||
PlayerEnderChestContainer enderChest = player.getEnderChestInventory();
|
||||
enderChest.setActiveChest(enderChestTile);
|
||||
player.openMenu(new SimpleMenuProvider((containerCounter, playerInventory, ignored) -> {
|
||||
MenuType<?> containers = PlayerDataManager.getContainers(enderChest.getContainerSize());
|
||||
int rows = enderChest.getContainerSize() / 9;
|
||||
return new ChestMenu(containers, containerCounter, playerInventory, enderChest, rows);
|
||||
}, new TranslatableComponent("container.enderchest")));
|
||||
}, new TextComponent("container.enderchest")));
|
||||
bukkitPlayer.incrementStatistic(Statistic.ENDERCHEST_OPENED);
|
||||
return true;
|
||||
}
|
||||
@@ -161,8 +161,8 @@ public class AnySilentContainer implements IAnySilentContainer {
|
||||
|
||||
if (block instanceof ChestBlock chestBlock) {
|
||||
|
||||
// boolean flag: do not check if chest is blocked
|
||||
Optional<MenuProvider> menuOptional = chestBlock.combine(blockState, level, blockPos, true).apply(
|
||||
// boolean flag: check if chest is blocked
|
||||
Optional<MenuProvider> menuOptional = chestBlock.combine(blockState, level, blockPos, false).apply(
|
||||
// Combiner is a copy of private ChestBlock.MENU_PROVIDER_COMBINER
|
||||
new DoubleBlockCombiner.Combiner<ChestBlockEntity, Optional<MenuProvider>>() {
|
||||
@Override
|
||||
@@ -253,13 +253,9 @@ public class AnySilentContainer implements IAnySilentContainer {
|
||||
GameType gameType = player.gameMode.getGameModeForPlayer();
|
||||
this.forceGameType(player, GameType.SPECTATOR);
|
||||
|
||||
// ServerPlayer#closeContainer cannot be called without entering an
|
||||
// infinite loop because this method is called during inventory close.
|
||||
// From ServerPlayer#closeContainer -> CraftEventFactory#handleInventoryCloseEvent
|
||||
player.containerMenu.transferTo(player.inventoryMenu, player.getBukkitEntity());
|
||||
// From ServerPlayer#closeContainer
|
||||
// Close container - note that this is very different from ServerPlayer#closeContainer!
|
||||
// Triggering event must not be re-called or we'll enter an infinite loop.
|
||||
player.doCloseContainer();
|
||||
// Regular inventory close will handle the rest - packet sending, etc.
|
||||
|
||||
// Revert forced game mode.
|
||||
this.forceGameType(player, gameType);
|
||||
+5
-5
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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
|
||||
@@ -14,7 +14,7 @@
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.lishid.openinv.internal.v1_18_R2;
|
||||
package com.lishid.openinv.internal.v1_18_R1;
|
||||
|
||||
import java.io.File;
|
||||
import net.minecraft.Util;
|
||||
@@ -23,8 +23,8 @@ import net.minecraft.nbt.NbtIo;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.level.storage.PlayerDataStorage;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.bukkit.craftbukkit.v1_18_R2.CraftServer;
|
||||
import org.bukkit.craftbukkit.v1_18_R2.entity.CraftPlayer;
|
||||
import org.bukkit.craftbukkit.v1_18_R1.CraftServer;
|
||||
import org.bukkit.craftbukkit.v1_18_R1.entity.CraftPlayer;
|
||||
|
||||
public class OpenPlayer extends CraftPlayer {
|
||||
|
||||
@@ -67,7 +67,7 @@ public class OpenPlayer extends CraftPlayer {
|
||||
File file2 = new File(worldNBTStorage.getPlayerDir(), player.getStringUUID() + ".dat_old");
|
||||
Util.safeReplaceFile(file1, file, file2);
|
||||
} catch (Exception e) {
|
||||
LogManager.getLogger().warn("Failed to save player data for {}: {}", player.getName().getString(), e.getMessage());
|
||||
LogManager.getLogger().warn("Failed to save player data for {}", player.getName().getString());
|
||||
}
|
||||
}
|
||||
|
||||
+11
-15
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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
|
||||
@@ -14,7 +14,7 @@
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.lishid.openinv.internal.v1_19_R1;
|
||||
package com.lishid.openinv.internal.v1_18_R1;
|
||||
|
||||
import com.lishid.openinv.OpenInv;
|
||||
import com.lishid.openinv.internal.IPlayerDataManager;
|
||||
@@ -23,7 +23,7 @@ import com.lishid.openinv.internal.OpenInventoryView;
|
||||
import com.mojang.authlib.GameProfile;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.logging.Logger;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.TextComponent;
|
||||
import net.minecraft.network.protocol.game.ClientboundOpenScreenPacket;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
@@ -35,10 +35,10 @@ import net.minecraft.world.level.Level;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.Server;
|
||||
import org.bukkit.craftbukkit.v1_19_R1.CraftServer;
|
||||
import org.bukkit.craftbukkit.v1_19_R1.entity.CraftPlayer;
|
||||
import org.bukkit.craftbukkit.v1_19_R1.event.CraftEventFactory;
|
||||
import org.bukkit.craftbukkit.v1_19_R1.inventory.CraftContainer;
|
||||
import org.bukkit.craftbukkit.v1_18_R1.CraftServer;
|
||||
import org.bukkit.craftbukkit.v1_18_R1.entity.CraftPlayer;
|
||||
import org.bukkit.craftbukkit.v1_18_R1.event.CraftEventFactory;
|
||||
import org.bukkit.craftbukkit.v1_18_R1.inventory.CraftContainer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.InventoryView;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
@@ -87,8 +87,7 @@ public class PlayerDataManager implements IPlayerDataManager {
|
||||
}
|
||||
|
||||
// Create a profile and entity to load the player data
|
||||
// See net.minecraft.server.players.PlayerList#canPlayerLogin
|
||||
// and net.minecraft.server.network.ServerLoginPacketListenerImpl#handleHello
|
||||
// See net.minecraft.server.PlayerList#attemptLogin
|
||||
GameProfile profile = new GameProfile(offline.getUniqueId(),
|
||||
offline.getName() != null ? offline.getName() : offline.getUniqueId().toString());
|
||||
MinecraftServer server = ((CraftServer) Bukkit.getServer()).getServer();
|
||||
@@ -98,7 +97,7 @@ public class PlayerDataManager implements IPlayerDataManager {
|
||||
return null;
|
||||
}
|
||||
|
||||
ServerPlayer entity = new ServerPlayer(server, worldServer, profile, null);
|
||||
ServerPlayer entity = new ServerPlayer(server, worldServer, profile);
|
||||
|
||||
try {
|
||||
injectPlayer(entity);
|
||||
@@ -131,9 +130,6 @@ public class PlayerDataManager implements IPlayerDataManager {
|
||||
public Player inject(@NotNull Player player) {
|
||||
try {
|
||||
ServerPlayer nmsPlayer = getHandle(player);
|
||||
if (nmsPlayer.getBukkitEntity() instanceof OpenPlayer openPlayer) {
|
||||
return openPlayer;
|
||||
}
|
||||
injectPlayer(nmsPlayer);
|
||||
return nmsPlayer.getBukkitEntity();
|
||||
} catch (IllegalAccessException e) {
|
||||
@@ -165,7 +161,7 @@ public class PlayerDataManager implements IPlayerDataManager {
|
||||
}
|
||||
};
|
||||
|
||||
container.setTitle(Component.literal(view.getTitle()));
|
||||
container.setTitle(new TextComponent(view.getTitle()));
|
||||
container = CraftEventFactory.callInventoryOpenEvent(nmsPlayer, container);
|
||||
|
||||
if (container == null) {
|
||||
@@ -173,7 +169,7 @@ public class PlayerDataManager implements IPlayerDataManager {
|
||||
}
|
||||
|
||||
nmsPlayer.connection.send(new ClientboundOpenScreenPacket(container.containerId, container.getType(),
|
||||
Component.literal(container.getBukkitView().getTitle())));
|
||||
new TextComponent(container.getBukkitView().getTitle())));
|
||||
nmsPlayer.containerMenu = container;
|
||||
nmsPlayer.initMenu(container);
|
||||
|
||||
+10
-5
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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
|
||||
@@ -14,7 +14,7 @@
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.lishid.openinv.internal.v1_19_R1;
|
||||
package com.lishid.openinv.internal.v1_18_R1;
|
||||
|
||||
import com.lishid.openinv.internal.ISpecialEnderChest;
|
||||
import java.util.List;
|
||||
@@ -33,8 +33,8 @@ import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.block.entity.EnderChestBlockEntity;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.craftbukkit.v1_19_R1.entity.CraftHumanEntity;
|
||||
import org.bukkit.craftbukkit.v1_19_R1.inventory.CraftInventory;
|
||||
import org.bukkit.craftbukkit.v1_18_R1.entity.CraftHumanEntity;
|
||||
import org.bukkit.craftbukkit.v1_18_R1.inventory.CraftInventory;
|
||||
import org.bukkit.entity.HumanEntity;
|
||||
import org.bukkit.inventory.InventoryHolder;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
@@ -60,6 +60,11 @@ public class SpecialEnderChest extends PlayerEnderChestContainer implements ISpe
|
||||
return inventory;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isInUse() {
|
||||
return !this.getViewers().isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPlayerOffline() {
|
||||
this.playerOnline = false;
|
||||
@@ -317,7 +322,7 @@ public class SpecialEnderChest extends PlayerEnderChestContainer implements ISpe
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.items.stream().filter((itemStack) -> !itemStack.isEmpty()).toList().toString();
|
||||
return this.items.stream().filter((itemStack) -> !itemStack.isEmpty()).collect(Collectors.toList()).toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
+15
-34
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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
|
||||
@@ -14,12 +14,11 @@
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.lishid.openinv.internal.v1_19_R1;
|
||||
package com.lishid.openinv.internal.v1_18_R1;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.lishid.openinv.internal.ISpecialPlayerInventory;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
@@ -33,7 +32,7 @@ import net.minecraft.nbt.ListTag;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.tags.Tag;
|
||||
import net.minecraft.world.Container;
|
||||
import net.minecraft.world.ContainerHelper;
|
||||
import net.minecraft.world.damagesource.DamageSource;
|
||||
@@ -46,8 +45,8 @@ import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.craftbukkit.v1_19_R1.entity.CraftHumanEntity;
|
||||
import org.bukkit.craftbukkit.v1_19_R1.inventory.CraftInventory;
|
||||
import org.bukkit.craftbukkit.v1_18_R1.entity.CraftHumanEntity;
|
||||
import org.bukkit.craftbukkit.v1_18_R1.inventory.CraftInventory;
|
||||
import org.bukkit.entity.HumanEntity;
|
||||
import org.bukkit.inventory.InventoryHolder;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
@@ -103,42 +102,25 @@ public class SpecialPlayerInventory extends Inventory implements ISpecialPlayerI
|
||||
this.playerOnline = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isInUse() {
|
||||
return !this.getViewers().isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull HumanEntity getPlayer() {
|
||||
return this.player.getBukkitEntity();
|
||||
}
|
||||
|
||||
private @NotNull ItemStack getRawItem(int i) {
|
||||
if (i < 0) {
|
||||
return ItemStack.EMPTY;
|
||||
}
|
||||
|
||||
NonNullList<ItemStack> list;
|
||||
for (Iterator<NonNullList<ItemStack>> iterator = this.compartments.iterator(); iterator.hasNext(); i -= list.size()) {
|
||||
list = iterator.next();
|
||||
if (i < list.size()) {
|
||||
return list.get(i);
|
||||
}
|
||||
}
|
||||
|
||||
return ItemStack.EMPTY;
|
||||
return super.getItem(i);
|
||||
}
|
||||
|
||||
private void setRawItem(int i, @NotNull ItemStack itemStack) {
|
||||
if (i < 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
NonNullList<ItemStack> list;
|
||||
for (Iterator<NonNullList<ItemStack>> iterator = this.compartments.iterator(); iterator.hasNext(); i -= list.size()) {
|
||||
list = iterator.next();
|
||||
if (i < list.size()) {
|
||||
list.set(i, itemStack);
|
||||
}
|
||||
}
|
||||
super.setItem(i, itemStack);
|
||||
}
|
||||
|
||||
private record IndexedCompartment(@Nullable NonNullList<ItemStack> compartment, int index) {}
|
||||
private static record IndexedCompartment(@Nullable NonNullList<ItemStack> compartment, int index) {}
|
||||
|
||||
private @NotNull SpecialPlayerInventory.IndexedCompartment getIndexedContent(int index) {
|
||||
if (index < items.size()) {
|
||||
@@ -743,9 +725,8 @@ public class SpecialPlayerInventory extends Inventory implements ISpecialPlayerI
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean contains(TagKey<Item> tagKey) {
|
||||
|
||||
return contains(itemStack -> !itemStack.isEmpty() && itemStack.is(tagKey));
|
||||
public boolean contains(Tag<Item> tag) {
|
||||
return contains(itemStack -> !itemStack.isEmpty() && itemStack.is(tag));
|
||||
}
|
||||
|
||||
@Override
|
||||
+8
-4
@@ -1,5 +1,5 @@
|
||||
<!--
|
||||
~ Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
~ Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
~
|
||||
~ 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
|
||||
@@ -21,7 +21,7 @@
|
||||
<parent>
|
||||
<artifactId>openinvparent</artifactId>
|
||||
<groupId>com.lishid</groupId>
|
||||
<version>4.2.0</version>
|
||||
<version>4.1.9-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>openinvplugincore</artifactId>
|
||||
@@ -37,8 +37,12 @@
|
||||
<groupId>org.jetbrains</groupId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<artifactId>spigot-api</artifactId>
|
||||
<groupId>org.spigotmc</groupId>
|
||||
<artifactId>paper-api</artifactId>
|
||||
<groupId>io.papermc.paper</groupId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<artifactId>planarwrappers</artifactId>
|
||||
<groupId>com.github.jikoo</groupId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv;
|
||||
|
||||
import com.lishid.openinv.internal.ISpecialInventory;
|
||||
import com.lishid.openinv.util.Permissions;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Consumer;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
record OfflineHandler(
|
||||
@NotNull BiFunction<Map<UUID, ? extends ISpecialInventory>, UUID, ISpecialInventory> fetch,
|
||||
@NotNull Consumer<@NotNull ISpecialInventory> handle) {
|
||||
|
||||
static final OfflineHandler REMOVE_AND_CLOSE = new OfflineHandler(
|
||||
Map::remove,
|
||||
inventory -> OpenInv.ejectViewers(inventory, viewer -> true)
|
||||
);
|
||||
|
||||
static final OfflineHandler REQUIRE_PERMISSIONS = new OfflineHandler(
|
||||
Map::get,
|
||||
inventory -> OpenInv.ejectViewers(inventory, viewer -> !Permissions.OPENOFFLINE.hasPermission(viewer))
|
||||
);
|
||||
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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
|
||||
@@ -16,28 +16,32 @@
|
||||
|
||||
package com.lishid.openinv;
|
||||
|
||||
import com.google.common.collect.HashMultimap;
|
||||
import com.google.common.collect.Multimap;
|
||||
import com.lishid.openinv.commands.ContainerSettingCommand;
|
||||
import com.lishid.openinv.commands.OpenInvCommand;
|
||||
import com.lishid.openinv.commands.SearchContainerCommand;
|
||||
import com.lishid.openinv.commands.SearchEnchantCommand;
|
||||
import com.lishid.openinv.commands.SearchInvCommand;
|
||||
import com.lishid.openinv.commands.SearchCommand;
|
||||
import com.lishid.openinv.internal.IAnySilentContainer;
|
||||
import com.lishid.openinv.internal.ISpecialEnderChest;
|
||||
import com.lishid.openinv.internal.ISpecialInventory;
|
||||
import com.lishid.openinv.internal.ISpecialPlayerInventory;
|
||||
import com.lishid.openinv.listeners.InventoryListener;
|
||||
import com.lishid.openinv.listeners.PlayerListener;
|
||||
import com.lishid.openinv.listeners.PluginListener;
|
||||
import com.lishid.openinv.util.Cache;
|
||||
import com.lishid.openinv.util.ConfigUpdater;
|
||||
import com.lishid.openinv.util.InternalAccessor;
|
||||
import com.lishid.openinv.util.LanguageManager;
|
||||
import com.lishid.openinv.util.Permissions;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Stream;
|
||||
import net.md_5.bungee.api.ChatMessageType;
|
||||
import net.md_5.bungee.api.chat.TextComponent;
|
||||
import org.bukkit.Bukkit;
|
||||
@@ -50,8 +54,10 @@ import org.bukkit.entity.HumanEntity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.InventoryView;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.plugin.PluginManager;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.bukkit.scheduler.BukkitRunnable;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
@@ -62,122 +68,96 @@ import org.jetbrains.annotations.Nullable;
|
||||
*/
|
||||
public class OpenInv extends JavaPlugin implements IOpenInv {
|
||||
|
||||
private final Map<UUID, ISpecialPlayerInventory> inventories = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, ISpecialEnderChest> enderChests = new ConcurrentHashMap<>();
|
||||
private final Map<String, ISpecialPlayerInventory> inventories = new HashMap<>();
|
||||
private final Map<String, ISpecialEnderChest> enderChests = new HashMap<>();
|
||||
private final Multimap<String, Class<? extends Plugin>> pluginUsage = HashMultimap.create();
|
||||
|
||||
private final Cache<String, Player> playerCache = new Cache<>(300000L,
|
||||
value -> {
|
||||
String key = OpenInv.this.getPlayerID(value);
|
||||
|
||||
return OpenInv.this.inventories.containsKey(key)
|
||||
&& OpenInv.this.inventories.get(key).isInUse()
|
||||
|| OpenInv.this.enderChests.containsKey(key)
|
||||
&& OpenInv.this.enderChests.get(key).isInUse()
|
||||
|| OpenInv.this.pluginUsage.containsKey(key);
|
||||
},
|
||||
value -> {
|
||||
String key = OpenInv.this.getPlayerID(value);
|
||||
|
||||
// Check if inventory is stored, and if it is, remove it and eject all viewers
|
||||
if (OpenInv.this.inventories.containsKey(key)) {
|
||||
Inventory inv = OpenInv.this.inventories.remove(key).getBukkitInventory();
|
||||
List<HumanEntity> viewers = new ArrayList<>(inv.getViewers());
|
||||
for (HumanEntity entity : viewers.toArray(new HumanEntity[0])) {
|
||||
entity.closeInventory();
|
||||
}
|
||||
}
|
||||
|
||||
// Check if ender chest is stored, and if it is, remove it and eject all viewers
|
||||
if (OpenInv.this.enderChests.containsKey(key)) {
|
||||
Inventory inv = OpenInv.this.enderChests.remove(key).getBukkitInventory();
|
||||
List<HumanEntity> viewers = new ArrayList<>(inv.getViewers());
|
||||
for (HumanEntity entity : viewers.toArray(new HumanEntity[0])) {
|
||||
entity.closeInventory();
|
||||
}
|
||||
}
|
||||
|
||||
if (!OpenInv.this.disableSaving() && !value.isOnline()) {
|
||||
value.saveData();
|
||||
}
|
||||
});
|
||||
|
||||
private InternalAccessor accessor;
|
||||
private LanguageManager languageManager;
|
||||
private boolean isSpigot = false;
|
||||
private OfflineHandler offlineHandler;
|
||||
|
||||
@Override
|
||||
public void reloadConfig() {
|
||||
super.reloadConfig();
|
||||
this.offlineHandler = disableOfflineAccess() ? OfflineHandler.REMOVE_AND_CLOSE : OfflineHandler.REQUIRE_PERMISSIONS;
|
||||
}
|
||||
/**
|
||||
* Evicts all viewers lacking cross-world permissions from a Player's inventory.
|
||||
*
|
||||
* @param player the Player
|
||||
*/
|
||||
public void changeWorld(final Player player) {
|
||||
|
||||
@Override
|
||||
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
|
||||
if (!isSpigot || !this.accessor.isSupported()) {
|
||||
this.sendVersionError(sender::sendMessage);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
String key = this.getPlayerID(player);
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
if (this.disableSaving()) {
|
||||
// Check if the player is cached. If not, neither of their inventories is open.
|
||||
if (!this.playerCache.containsKey(key)) {
|
||||
return;
|
||||
}
|
||||
|
||||
Stream.concat(inventories.values().stream(), enderChests.values().stream())
|
||||
.map(inventory -> {
|
||||
// Cheat a bit - rather than stream twice, evict all viewers during remapping.
|
||||
ejectViewers(inventory, viewer -> true);
|
||||
if (inventory.getPlayer() instanceof Player player) {
|
||||
return player;
|
||||
}
|
||||
return null;
|
||||
})
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.forEach(player -> {
|
||||
if (!player.isOnline()) {
|
||||
player = accessor.getPlayerDataManager().inject(player);
|
||||
}
|
||||
player.saveData();
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
// Save default configuration if not present.
|
||||
this.saveDefaultConfig();
|
||||
|
||||
// Get plugin manager
|
||||
PluginManager pm = this.getServer().getPluginManager();
|
||||
|
||||
this.accessor = new InternalAccessor(this);
|
||||
|
||||
this.languageManager = new LanguageManager(this, "en_us");
|
||||
this.offlineHandler = disableOfflineAccess() ? OfflineHandler.REMOVE_AND_CLOSE : OfflineHandler.REQUIRE_PERMISSIONS;
|
||||
|
||||
try {
|
||||
Class.forName("org.bukkit.entity.Player$Spigot");
|
||||
isSpigot = true;
|
||||
} catch (ClassNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
isSpigot = false;
|
||||
if (this.inventories.containsKey(key)) {
|
||||
kickCrossWorldViewers(player, this.inventories.get(key));
|
||||
}
|
||||
|
||||
// Version check
|
||||
if (isSpigot && this.accessor.isSupported()) {
|
||||
// Update existing configuration. May require internal access.
|
||||
new ConfigUpdater(this).checkForUpdates();
|
||||
|
||||
// Register listeners
|
||||
pm.registerEvents(new PlayerListener(this), this);
|
||||
pm.registerEvents(new InventoryListener(this), this);
|
||||
|
||||
// Register commands to their executors
|
||||
this.setCommandExecutor(new OpenInvCommand(this), "openinv", "openender");
|
||||
this.setCommandExecutor(new SearchContainerCommand(this), "searchcontainer");
|
||||
this.setCommandExecutor(new SearchInvCommand(this), "searchinv", "searchender");
|
||||
this.setCommandExecutor(new SearchEnchantCommand(this), "searchenchant");
|
||||
this.setCommandExecutor(new ContainerSettingCommand(this), "silentcontainer", "anycontainer");
|
||||
|
||||
} else {
|
||||
this.sendVersionError(this.getLogger()::warning);
|
||||
if (this.enderChests.containsKey(key)) {
|
||||
kickCrossWorldViewers(player, this.enderChests.get(key));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void setCommandExecutor(@NotNull CommandExecutor executor, String @NotNull ... commands) {
|
||||
for (String commandName : commands) {
|
||||
PluginCommand command = this.getCommand(commandName);
|
||||
if (command != null) {
|
||||
command.setExecutor(executor);
|
||||
private void kickCrossWorldViewers(Player player, ISpecialInventory inventory) {
|
||||
List<HumanEntity> viewers = new ArrayList<>(inventory.getBukkitInventory().getViewers());
|
||||
for (HumanEntity human : viewers) {
|
||||
// If player has permission or is in the same world, allow continued access
|
||||
// Just in case, also allow null worlds.
|
||||
if (Permissions.CROSSWORLD.hasPermission(human) || Objects.equals(human.getWorld(), player.getWorld())) {
|
||||
continue;
|
||||
}
|
||||
human.closeInventory();
|
||||
}
|
||||
}
|
||||
|
||||
private void sendVersionError(@NotNull Consumer<String> messageMethod) {
|
||||
if (!this.accessor.isSupported()) {
|
||||
messageMethod.accept("Your server version (" + this.accessor.getVersion() + ") is not supported.");
|
||||
messageMethod.accept("Please download the correct version of OpenInv here: " + this.accessor.getReleasesLink());
|
||||
}
|
||||
if (!isSpigot) {
|
||||
messageMethod.accept("OpenInv requires that you use Spigot or a Spigot fork. Per the 1.14 update thread");
|
||||
messageMethod.accept("(https://www.spigotmc.org/threads/369724/ \"A Note on CraftBukkit\"), if you are");
|
||||
messageMethod.accept("encountering an inconsistency with vanilla that prevents you from using Spigot,");
|
||||
messageMethod.accept("that is considered a Spigot bug and should be reported as such.");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSupportedVersion() {
|
||||
return this.accessor != null && this.accessor.isSupported();
|
||||
/**
|
||||
* Convert a raw slot number into a player inventory slot number.
|
||||
*
|
||||
* <p>Note that this method is specifically for converting an ISpecialPlayerInventory slot number into a regular
|
||||
* player inventory slot number.
|
||||
*
|
||||
* @param view the open inventory view
|
||||
* @param rawSlot the raw slot in the view
|
||||
* @return the converted slot number
|
||||
*/
|
||||
public int convertToPlayerSlot(InventoryView view, int rawSlot) {
|
||||
return this.accessor.getPlayerDataManager().convertToPlayerSlot(view, rawSlot);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -185,38 +165,28 @@ public class OpenInv extends JavaPlugin implements IOpenInv {
|
||||
return this.getConfig().getBoolean("settings.disable-saving", false);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public boolean disableOfflineAccess() {
|
||||
return this.getConfig().getBoolean("settings.disable-offline-access", false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull IAnySilentContainer getAnySilentContainer() {
|
||||
public IAnySilentContainer getAnySilentContainer() {
|
||||
return this.accessor.getAnySilentContainer();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getAnyContainerStatus(@NotNull final OfflinePlayer offline) {
|
||||
public boolean getPlayerAnyChestStatus(@NotNull final OfflinePlayer player) {
|
||||
boolean defaultState = false;
|
||||
|
||||
if (offline.isOnline()) {
|
||||
Player onlinePlayer = offline.getPlayer();
|
||||
if (player.isOnline()) {
|
||||
Player onlinePlayer = player.getPlayer();
|
||||
if (onlinePlayer != null) {
|
||||
defaultState = Permissions.ANY_DEFAULT.hasPermission(onlinePlayer);
|
||||
}
|
||||
}
|
||||
|
||||
return this.getConfig().getBoolean("toggles.any-chest." + offline.getUniqueId(), defaultState);
|
||||
return this.getConfig().getBoolean("toggles.any-chest." + this.getPlayerID(player), defaultState);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAnyContainerStatus(@NotNull final OfflinePlayer offline, final boolean status) {
|
||||
this.getConfig().set("toggles.any-chest." + offline.getUniqueId(), status);
|
||||
this.saveConfig();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getSilentContainerStatus(@NotNull final OfflinePlayer offline) {
|
||||
public boolean getPlayerSilentChestStatus(@NotNull final OfflinePlayer offline) {
|
||||
boolean defaultState = false;
|
||||
|
||||
if (offline.isOnline()) {
|
||||
@@ -226,71 +196,57 @@ public class OpenInv extends JavaPlugin implements IOpenInv {
|
||||
}
|
||||
}
|
||||
|
||||
return this.getConfig().getBoolean("toggles.silent-chest." + offline.getUniqueId(), defaultState);
|
||||
return this.getConfig().getBoolean("toggles.silent-chest." + this.getPlayerID(offline), defaultState);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public void setSilentContainerStatus(@NotNull final OfflinePlayer offline, final boolean status) {
|
||||
this.getConfig().set("toggles.silent-chest." + offline.getUniqueId(), status);
|
||||
this.saveConfig();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull ISpecialEnderChest getSpecialEnderChest(@NotNull final Player player, final boolean online)
|
||||
public ISpecialEnderChest getSpecialEnderChest(@NotNull final Player player, final boolean online)
|
||||
throws InstantiationException {
|
||||
UUID key = player.getUniqueId();
|
||||
|
||||
if (this.enderChests.containsKey(key)) {
|
||||
return this.enderChests.get(key);
|
||||
String id = this.getPlayerID(player);
|
||||
if (this.enderChests.containsKey(id)) {
|
||||
return this.enderChests.get(id);
|
||||
}
|
||||
|
||||
ISpecialEnderChest inv = this.accessor.newSpecialEnderChest(player, online);
|
||||
this.enderChests.put(key, inv);
|
||||
this.enderChests.put(id, inv);
|
||||
this.playerCache.put(id, player);
|
||||
return inv;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public @NotNull ISpecialPlayerInventory getSpecialInventory(@NotNull final Player player, final boolean online)
|
||||
public ISpecialPlayerInventory getSpecialInventory(@NotNull final Player player, final boolean online)
|
||||
throws InstantiationException {
|
||||
UUID key = player.getUniqueId();
|
||||
|
||||
if (this.inventories.containsKey(key)) {
|
||||
return this.inventories.get(key);
|
||||
String id = this.getPlayerID(player);
|
||||
if (this.inventories.containsKey(id)) {
|
||||
return this.inventories.get(id);
|
||||
}
|
||||
|
||||
ISpecialPlayerInventory inv = this.accessor.newSpecialPlayerInventory(player, online);
|
||||
this.inventories.put(key, inv);
|
||||
this.inventories.put(id, inv);
|
||||
this.playerCache.put(id, player);
|
||||
return inv;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable InventoryView openInventory(@NotNull Player player, @NotNull ISpecialInventory inventory) {
|
||||
return this.accessor.getPlayerDataManager().openInventory(player, inventory);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPlayerLoaded(@NotNull UUID playerUuid) {
|
||||
return this.inventories.containsKey(playerUuid) || this.enderChests.containsKey(playerUuid);
|
||||
public boolean isSupportedVersion() {
|
||||
return this.accessor != null && this.accessor.isSupported();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable Player loadPlayer(@NotNull final OfflinePlayer offline) {
|
||||
UUID key = offline.getUniqueId();
|
||||
|
||||
if (this.inventories.containsKey(key)) {
|
||||
return (Player) this.inventories.get(key).getPlayer();
|
||||
}
|
||||
|
||||
if (this.enderChests.containsKey(key)) {
|
||||
return (Player) this.enderChests.get(key).getPlayer();
|
||||
String key = this.getPlayerID(offline);
|
||||
if (this.playerCache.containsKey(key)) {
|
||||
return this.playerCache.get(key);
|
||||
}
|
||||
|
||||
Player player = offline.getPlayer();
|
||||
if (player != null) {
|
||||
this.playerCache.put(key, player);
|
||||
return player;
|
||||
}
|
||||
|
||||
if (disableOfflineAccess() || !this.isSupportedVersion()) {
|
||||
if (!this.isSupportedVersion()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -308,82 +264,28 @@ public class OpenInv extends JavaPlugin implements IOpenInv {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (player != null) {
|
||||
this.playerCache.put(key, player);
|
||||
}
|
||||
|
||||
return player;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unload(@NotNull final OfflinePlayer offline) {
|
||||
setPlayerOffline(offline, OfflineHandler.REMOVE_AND_CLOSE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Evict all viewers lacking cross-world permissions when a {@link Player} changes worlds.
|
||||
*
|
||||
* @param player the Player
|
||||
*/
|
||||
void changeWorld(@NotNull Player player) {
|
||||
UUID key = player.getUniqueId();
|
||||
|
||||
if (this.inventories.containsKey(key)) {
|
||||
kickCrossWorldViewers(player, this.inventories.get(key));
|
||||
}
|
||||
|
||||
if (this.enderChests.containsKey(key)) {
|
||||
kickCrossWorldViewers(player, this.enderChests.get(key));
|
||||
}
|
||||
}
|
||||
|
||||
private void kickCrossWorldViewers(@NotNull Player player, @NotNull ISpecialInventory inventory) {
|
||||
ejectViewers(
|
||||
inventory,
|
||||
viewer ->
|
||||
!Permissions.CROSSWORLD.hasPermission(viewer)
|
||||
&& !Objects.equals(viewer.getWorld(), player.getWorld()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a raw slot number into a player inventory slot number.
|
||||
*
|
||||
* <p>Note that this method is specifically for converting an ISpecialPlayerInventory slot number into a regular
|
||||
* player inventory slot number.
|
||||
*
|
||||
* @param view the open inventory view
|
||||
* @param rawSlot the raw slot in the view
|
||||
* @return the converted slot number
|
||||
*/
|
||||
int convertToPlayerSlot(InventoryView view, int rawSlot) {
|
||||
return this.accessor.getPlayerDataManager().convertToPlayerSlot(view, rawSlot);
|
||||
}
|
||||
|
||||
public @Nullable String getLocalizedMessage(@NotNull CommandSender sender, @NotNull String key) {
|
||||
return this.languageManager.getValue(key, getLocale(sender));
|
||||
}
|
||||
|
||||
public @Nullable String getLocalizedMessage(
|
||||
@NotNull CommandSender sender,
|
||||
@NotNull String key,
|
||||
String @NotNull ... replacements) {
|
||||
return this.languageManager.getValue(key, getLocale(sender), replacements);
|
||||
}
|
||||
|
||||
private @NotNull String getLocale(@NotNull CommandSender sender) {
|
||||
if (sender instanceof Player) {
|
||||
return ((Player) sender).getLocale();
|
||||
} else {
|
||||
return this.getConfig().getString("settings.locale", "en_us");
|
||||
}
|
||||
public @Nullable InventoryView openInventory(@NotNull Player player, @NotNull ISpecialInventory inventory) {
|
||||
return this.accessor.getPlayerDataManager().openInventory(player, inventory);
|
||||
}
|
||||
|
||||
public void sendMessage(@NotNull CommandSender sender, @NotNull String key) {
|
||||
String message = getLocalizedMessage(sender, key);
|
||||
String message = this.languageManager.getValue(key, getLocale(sender));
|
||||
|
||||
if (message != null && !message.isEmpty()) {
|
||||
sender.sendMessage(message);
|
||||
}
|
||||
}
|
||||
|
||||
public void sendMessage(@NotNull CommandSender sender, @NotNull String key, String @NotNull... replacements) {
|
||||
String message = getLocalizedMessage(sender, key, replacements);
|
||||
public void sendMessage(@NotNull CommandSender sender, @NotNull String key, String... replacements) {
|
||||
String message = this.languageManager.getValue(key, getLocale(sender), replacements);
|
||||
|
||||
if (message != null && !message.isEmpty()) {
|
||||
sender.sendMessage(message);
|
||||
@@ -391,7 +293,11 @@ public class OpenInv extends JavaPlugin implements IOpenInv {
|
||||
}
|
||||
|
||||
public void sendSystemMessage(@NotNull Player player, @NotNull String key) {
|
||||
String message = getLocalizedMessage(player, key);
|
||||
this.sendSystemMessage(player, key, new String[0]);
|
||||
}
|
||||
|
||||
public void sendSystemMessage(@NotNull Player player, @NotNull String key, String... replacements) {
|
||||
String message = this.languageManager.getValue(key, getLocale(player));
|
||||
|
||||
if (message == null) {
|
||||
return;
|
||||
@@ -410,76 +316,166 @@ public class OpenInv extends JavaPlugin implements IOpenInv {
|
||||
player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(message));
|
||||
}
|
||||
|
||||
public @Nullable String getLocalizedMessage(@NotNull CommandSender sender, @NotNull String key) {
|
||||
return this.languageManager.getValue(key, getLocale(sender));
|
||||
}
|
||||
|
||||
public @Nullable String getLocalizedMessage(@NotNull CommandSender sender, @NotNull String key, String... replacements) {
|
||||
return this.languageManager.getValue(key, getLocale(sender), replacements);
|
||||
}
|
||||
|
||||
private @NotNull String getLocale(@NotNull CommandSender sender) {
|
||||
if (sender instanceof Player) {
|
||||
return ((Player) sender).getLocale();
|
||||
} else {
|
||||
return this.getConfig().getString("settings.locale", "en_us");
|
||||
}
|
||||
}
|
||||
|
||||
public int getSearchPollsPerTick() {
|
||||
return this.getConfig().getInt("settings.search.polls-per-tick", 5);
|
||||
}
|
||||
|
||||
public int getSearchResultsMax() {
|
||||
return this.getConfig().getInt("settings.search.max-results", 40);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
|
||||
if (this.disableSaving()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.isSupportedVersion()) {
|
||||
this.playerCache.invalidateAll();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
|
||||
// Save default configuration if not present.
|
||||
this.saveDefaultConfig();
|
||||
|
||||
// Get plugin manager
|
||||
PluginManager pm = this.getServer().getPluginManager();
|
||||
|
||||
this.accessor = new InternalAccessor(this);
|
||||
|
||||
this.languageManager = new LanguageManager(this, "en_us");
|
||||
|
||||
// Version check
|
||||
if (this.accessor.isSupported()) {
|
||||
// Update existing configuration. May require internal access.
|
||||
new ConfigUpdater(this).checkForUpdates();
|
||||
|
||||
// Register listeners
|
||||
pm.registerEvents(new PlayerListener(this), this);
|
||||
pm.registerEvents(new PluginListener(this), this);
|
||||
pm.registerEvents(new InventoryListener(this), this);
|
||||
|
||||
// Register commands to their executors
|
||||
this.setCommandExecutor(new OpenInvCommand(this), "openinv", "openender");
|
||||
this.setCommandExecutor(new SearchCommand(this), "search");
|
||||
this.setCommandExecutor(new ContainerSettingCommand(this), "silentcontainer", "anycontainer");
|
||||
|
||||
} else {
|
||||
this.sendVersionError(this.getLogger()::warning);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void sendVersionError(Consumer<String> messageMethod) {
|
||||
messageMethod.accept("Your server version (" + this.accessor.getVersion() + ") is not supported.");
|
||||
messageMethod.accept("Please obtain an appropriate version here: " + accessor.getReleasesLink());
|
||||
}
|
||||
|
||||
private void setCommandExecutor(CommandExecutor executor, String... commands) {
|
||||
for (String commandName : commands) {
|
||||
PluginCommand command = this.getCommand(commandName);
|
||||
if (command != null) {
|
||||
command.setExecutor(executor);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
|
||||
if (!this.accessor.isSupported()) {
|
||||
this.sendVersionError(sender::sendMessage);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public void releaseAllPlayers(final Plugin plugin) {
|
||||
Iterator<Map.Entry<String, Class<? extends Plugin>>> iterator = this.pluginUsage.entries().iterator();
|
||||
|
||||
if (!iterator.hasNext()) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (Map.Entry<String, Class<? extends Plugin>> entry = iterator.next(); iterator.hasNext(); entry = iterator.next()) {
|
||||
if (entry.getValue().equals(plugin.getClass())) {
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void releasePlayer(@NotNull final Player player, @NotNull final Plugin plugin) {
|
||||
String key = this.getPlayerID(player);
|
||||
|
||||
if (!this.pluginUsage.containsEntry(key, plugin.getClass())) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.pluginUsage.remove(key, plugin.getClass());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void retainPlayer(@NotNull final Player player, @NotNull final Plugin plugin) {
|
||||
String key = this.getPlayerID(player);
|
||||
|
||||
if (this.pluginUsage.containsEntry(key, plugin.getClass())) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.pluginUsage.put(key, plugin.getClass());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPlayerAnyChestStatus(@NotNull final OfflinePlayer offline, final boolean status) {
|
||||
this.getConfig().set("toggles.any-chest." + this.getPlayerID(offline), status);
|
||||
this.saveConfig();
|
||||
}
|
||||
|
||||
/**
|
||||
* Method for handling a Player going offline.
|
||||
*
|
||||
* @param player the Player
|
||||
* @throws IllegalStateException if the server version is unsupported
|
||||
*/
|
||||
void setPlayerOffline(@NotNull Player player) {
|
||||
setPlayerOffline(player, offlineHandler);
|
||||
}
|
||||
public void setPlayerOffline(final Player player) {
|
||||
|
||||
private void setPlayerOffline(@NotNull OfflinePlayer player, @NotNull OfflineHandler handler) {
|
||||
UUID key = player.getUniqueId();
|
||||
String key = this.getPlayerID(player);
|
||||
|
||||
setPlayerOffline(inventories, key, handler);
|
||||
setPlayerOffline(enderChests, key, handler);
|
||||
}
|
||||
|
||||
private void setPlayerOffline(
|
||||
@NotNull Map<UUID, ? extends ISpecialInventory> map,
|
||||
@NotNull UUID key,
|
||||
@NotNull OfflineHandler handler) {
|
||||
ISpecialInventory inventory = handler.fetch().apply(map, key);
|
||||
if (inventory == null) {
|
||||
return;
|
||||
}
|
||||
inventory.setPlayerOffline();
|
||||
if (!inventory.isInUse()) {
|
||||
map.remove(key);
|
||||
} else {
|
||||
handler.handle().accept(inventory);
|
||||
}
|
||||
}
|
||||
|
||||
void handleCloseInventory(@NotNull HumanEntity exViewer, @NotNull ISpecialInventory inventory) {
|
||||
Map<UUID, ? extends ISpecialInventory> map = inventory instanceof ISpecialPlayerInventory ? inventories : enderChests;
|
||||
UUID key = inventory.getPlayer().getUniqueId();
|
||||
@Nullable ISpecialInventory loaded = map.get(key);
|
||||
|
||||
if (loaded == null) {
|
||||
// Loaded inventory has already been removed. Removal will handle saving if necessary.
|
||||
// Check if the player is cached. If not, neither of their inventories is open.
|
||||
if (!this.playerCache.containsKey(key)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// This should only be possible if a plugin is doing funky things with our inventories.
|
||||
if (loaded != inventory) {
|
||||
Inventory bukkitInventory = inventory.getBukkitInventory();
|
||||
// Just in case, respect contents of the inventory that was just used.
|
||||
loaded.getBukkitInventory().setContents(bukkitInventory.getContents());
|
||||
// We need to close this inventory to reduce risk of duplication bugs if the user is offline.
|
||||
// We don't want to risk recursively closing the same inventory repeatedly, so we schedule dumping viewers.
|
||||
// Worst case we schedule a couple redundant tasks if several people had the inventory open.
|
||||
if (inventory.isInUse()) {
|
||||
getServer().getScheduler().runTask(this, () -> ejectViewers(inventory, viewer -> true));
|
||||
}
|
||||
// Replace stored player with our own version
|
||||
this.playerCache.put(key, this.accessor.getPlayerDataManager().inject(player));
|
||||
|
||||
if (this.inventories.containsKey(key)) {
|
||||
this.inventories.get(key).setPlayerOffline();
|
||||
}
|
||||
|
||||
// Schedule task to check in use status later this tick. Closing user is still in viewer list.
|
||||
getServer().getScheduler().runTask(this, () -> {
|
||||
if (loaded.isInUse()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Re-fetch from map - prevents duplicate saves on multi-close.
|
||||
ISpecialInventory current = map.remove(key);
|
||||
|
||||
if (!disableSaving()
|
||||
&& current != null
|
||||
&& current.getPlayer() instanceof Player player && !player.isOnline()) {
|
||||
this.accessor.getPlayerDataManager().inject(player).saveData();
|
||||
}
|
||||
});
|
||||
if (this.enderChests.containsKey(key)) {
|
||||
this.enderChests.get(key).setPlayerOffline();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -488,49 +484,78 @@ public class OpenInv extends JavaPlugin implements IOpenInv {
|
||||
* @param player the Player
|
||||
* @throws IllegalStateException if the server version is unsupported
|
||||
*/
|
||||
void setPlayerOnline(@NotNull Player player) {
|
||||
setPlayerOnline(inventories, player, player::updateInventory);
|
||||
setPlayerOnline(enderChests, player, null);
|
||||
}
|
||||
public void setPlayerOnline(final Player player) {
|
||||
|
||||
private void setPlayerOnline(
|
||||
@NotNull Map<UUID, ? extends ISpecialInventory> map,
|
||||
@NotNull Player player,
|
||||
@Nullable Runnable task) {
|
||||
ISpecialInventory inventory = map.get(player.getUniqueId());
|
||||
String key = this.getPlayerID(player);
|
||||
|
||||
if (inventory == null) {
|
||||
// Inventory not open.
|
||||
// Check if the player is cached. If not, neither of their inventories is open.
|
||||
if (!this.playerCache.containsKey(key)) {
|
||||
return;
|
||||
}
|
||||
|
||||
inventory.setPlayerOnline(player);
|
||||
this.playerCache.put(key, player);
|
||||
|
||||
// Eject viewers lacking permission.
|
||||
ejectViewers(
|
||||
inventory,
|
||||
viewer ->
|
||||
!Permissions.OPENONLINE.hasPermission(viewer)
|
||||
|| !Permissions.CROSSWORLD.hasPermission(viewer)
|
||||
&& !Objects.equals(viewer.getWorld(), inventory.getPlayer().getWorld()));
|
||||
if (this.inventories.containsKey(key)) {
|
||||
this.inventories.get(key).setPlayerOnline(player);
|
||||
new BukkitRunnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (player.isOnline()) {
|
||||
player.updateInventory();
|
||||
}
|
||||
}
|
||||
}.runTask(this);
|
||||
}
|
||||
|
||||
if (task != null) {
|
||||
getServer().getScheduler().runTask(this, task);
|
||||
if (this.enderChests.containsKey(key)) {
|
||||
this.enderChests.get(key).setPlayerOnline(player);
|
||||
}
|
||||
}
|
||||
|
||||
static void ejectViewers(@NotNull ISpecialInventory inventory, @NotNull Predicate<@NotNull HumanEntity> predicate) {
|
||||
Inventory bukkitInventory = inventory.getBukkitInventory();
|
||||
for (HumanEntity viewer : new ArrayList<>(bukkitInventory.getViewers())) {
|
||||
if (viewer.getUniqueId().equals(inventory.getPlayer().getUniqueId())
|
||||
&& !viewer.getOpenInventory().getTopInventory().equals(bukkitInventory)) {
|
||||
// Skip owner with other inventory open. They aren't actually a viewer.
|
||||
@Override
|
||||
public void setPlayerSilentChestStatus(@NotNull final OfflinePlayer offline, final boolean status) {
|
||||
this.getConfig().set("toggles.silent-chest." + this.getPlayerID(offline), status);
|
||||
this.saveConfig();
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays all applicable help for OpenInv commands.
|
||||
*
|
||||
* @param player the Player to help
|
||||
*/
|
||||
public void showHelp(final Player player) {
|
||||
// Get registered commands
|
||||
for (String commandName : this.getDescription().getCommands().keySet()) {
|
||||
PluginCommand command = this.getCommand(commandName);
|
||||
|
||||
// Ensure command is successfully registered and player can use it
|
||||
if (command == null || !command.testPermissionSilent(player)) {
|
||||
continue;
|
||||
}
|
||||
if (predicate.test(viewer)) {
|
||||
viewer.closeInventory();
|
||||
|
||||
// Send usage
|
||||
player.sendMessage(command.getUsage().replace("<command>", commandName));
|
||||
|
||||
List<String> aliases = command.getAliases();
|
||||
if (aliases.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Assemble alias list
|
||||
StringBuilder aliasBuilder = new StringBuilder(" (aliases: ");
|
||||
for (String alias : aliases) {
|
||||
aliasBuilder.append(alias).append(", ");
|
||||
}
|
||||
aliasBuilder.delete(aliasBuilder.length() - 2, aliasBuilder.length()).append(')');
|
||||
|
||||
// Send all aliases
|
||||
player.sendMessage(aliasBuilder.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unload(@NotNull final OfflinePlayer offline) {
|
||||
this.playerCache.invalidate(this.getPlayerID(offline));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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
|
||||
@@ -39,14 +39,15 @@ public class ContainerSettingCommand implements TabExecutor {
|
||||
|
||||
@Override
|
||||
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
|
||||
if (!(sender instanceof Player player)) {
|
||||
if (!(sender instanceof Player)) {
|
||||
plugin.sendMessage(sender, "messages.error.consoleUnsupported");
|
||||
return true;
|
||||
}
|
||||
|
||||
Player player = (Player) sender;
|
||||
boolean any = command.getName().startsWith("any");
|
||||
Predicate<Player> getSetting = any ? plugin::getAnyContainerStatus : plugin::getSilentContainerStatus;
|
||||
BiConsumer<OfflinePlayer, Boolean> setSetting = any ? plugin::setAnyContainerStatus : plugin::setSilentContainerStatus;
|
||||
Predicate<Player> getSetting = any ? plugin::getPlayerAnyChestStatus : plugin::getPlayerSilentChestStatus;
|
||||
BiConsumer<OfflinePlayer, Boolean> setSetting = any ? plugin::setPlayerAnyChestStatus : plugin::setPlayerSilentChestStatus;
|
||||
|
||||
if (args.length > 0) {
|
||||
args[0] = args[0].toLowerCase();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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
|
||||
@@ -23,11 +23,9 @@ import com.lishid.openinv.util.TabCompleter;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.StringJoiner;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.command.PluginCommand;
|
||||
import org.bukkit.command.TabExecutor;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.scheduler.BukkitRunnable;
|
||||
@@ -45,24 +43,25 @@ public class OpenInvCommand implements TabExecutor {
|
||||
|
||||
@Override
|
||||
public boolean onCommand(@NotNull final CommandSender sender, @NotNull final Command command, @NotNull final String label, @NotNull final String[] args) {
|
||||
boolean openInv = command.getName().equals("openinv");
|
||||
|
||||
if (openInv && args.length > 0 && (args[0].equalsIgnoreCase("help") || args[0].equals("?"))) {
|
||||
this.showHelp(sender);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!(sender instanceof Player player)) {
|
||||
if (!(sender instanceof Player)) {
|
||||
plugin.sendMessage(sender, "messages.error.consoleUnsupported");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (args.length > 0 && (args[0].equalsIgnoreCase("help") || args[0].equals("?"))) {
|
||||
this.plugin.showHelp((Player) sender);
|
||||
return true;
|
||||
}
|
||||
|
||||
final Player player = (Player) sender;
|
||||
final boolean openinv = command.getName().equals("openinv");
|
||||
|
||||
// History management
|
||||
String history = (openInv ? this.openInvHistory : this.openEnderHistory).get(player);
|
||||
String history = (openinv ? this.openInvHistory : this.openEnderHistory).get(player);
|
||||
|
||||
if (history == null || history.isEmpty()) {
|
||||
history = player.getName();
|
||||
(openInv ? this.openInvHistory : this.openEnderHistory).put(player, history);
|
||||
(openinv ? this.openInvHistory : this.openEnderHistory).put(player, history);
|
||||
}
|
||||
|
||||
final String name;
|
||||
@@ -90,7 +89,7 @@ public class OpenInvCommand implements TabExecutor {
|
||||
if (!player.isOnline()) {
|
||||
return;
|
||||
}
|
||||
OpenInvCommand.this.openInventory(player, offlinePlayer, openInv);
|
||||
OpenInvCommand.this.openInventory(player, offlinePlayer, openinv);
|
||||
}
|
||||
}.runTask(OpenInvCommand.this.plugin);
|
||||
|
||||
@@ -100,40 +99,12 @@ public class OpenInvCommand implements TabExecutor {
|
||||
return true;
|
||||
}
|
||||
|
||||
private void showHelp(final CommandSender sender) {
|
||||
// Get registered commands
|
||||
for (String commandName : plugin.getDescription().getCommands().keySet()) {
|
||||
PluginCommand command = plugin.getCommand(commandName);
|
||||
|
||||
// Ensure command is successfully registered and sender can use it
|
||||
if (command == null || !command.testPermissionSilent(sender)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Send usage
|
||||
sender.sendMessage(command.getUsage().replace("<command>", commandName));
|
||||
|
||||
List<String> aliases = command.getAliases();
|
||||
if (!aliases.isEmpty()) {
|
||||
// Assemble alias list
|
||||
StringJoiner aliasJoiner = new StringJoiner(", ", " (aliases: ", ")");
|
||||
for (String alias : aliases) {
|
||||
aliasJoiner.add(alias);
|
||||
}
|
||||
|
||||
// Send all aliases
|
||||
sender.sendMessage(aliasJoiner.toString());
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private void openInventory(final Player player, final OfflinePlayer target, boolean openinv) {
|
||||
Player onlineTarget;
|
||||
boolean online = target.isOnline();
|
||||
|
||||
if (!online) {
|
||||
if (!plugin.disableOfflineAccess() && Permissions.OPENOFFLINE.hasPermission(player)) {
|
||||
if (Permissions.OPENOFFLINE.hasPermission(player)) {
|
||||
// Try loading the player's data
|
||||
onlineTarget = this.plugin.loadPlayer(target);
|
||||
} else {
|
||||
@@ -186,7 +157,7 @@ public class OpenInvCommand implements TabExecutor {
|
||||
}
|
||||
|
||||
// Record the target
|
||||
(openinv ? this.openInvHistory : this.openEnderHistory).put(player, target.getUniqueId().toString());
|
||||
(openinv ? this.openInvHistory : this.openEnderHistory).put(player, this.plugin.getPlayerID(target));
|
||||
|
||||
// Create the inventory
|
||||
final ISpecialInventory inv;
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv.commands;
|
||||
|
||||
import com.lishid.openinv.OpenInv;
|
||||
import com.lishid.openinv.commands.search.ChunkSearchOption;
|
||||
import com.lishid.openinv.commands.search.CompletableOption;
|
||||
import com.lishid.openinv.commands.search.ItemAmountOption;
|
||||
import com.lishid.openinv.commands.search.ItemEnchantOption;
|
||||
import com.lishid.openinv.commands.search.ItemTypeOption;
|
||||
import com.lishid.openinv.commands.search.PlayerSearchOption;
|
||||
import com.lishid.openinv.commands.search.PseudoOption;
|
||||
import com.lishid.openinv.search.Search;
|
||||
import com.lishid.openinv.search.bucket.SearchBucket;
|
||||
import com.lishid.openinv.search.match.ItemMatcher;
|
||||
import com.lishid.openinv.search.match.MatchableItem;
|
||||
import com.lishid.openinv.search.match.MatchableMeta;
|
||||
import com.lishid.openinv.util.PseudoJson;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.command.TabExecutor;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class SearchCommand implements TabExecutor {
|
||||
|
||||
private final OpenInv plugin;
|
||||
private final Collection<String> activeSearches = Collections.newSetFromMap(new ConcurrentHashMap<>());
|
||||
|
||||
private final Collection<CompletableOption<SearchBucket>> completableSearchBuckets = new HashSet<>();
|
||||
private final Collection<CompletableOption<MatchableItem>> completableMatchOptions = new HashSet<>();
|
||||
private final Collection<CompletableOption<MatchableMeta>> completableMatchMetaOptions = new HashSet<>();
|
||||
|
||||
public SearchCommand(OpenInv plugin) {
|
||||
this.plugin = plugin;
|
||||
|
||||
this.completableSearchBuckets.add(new ChunkSearchOption());
|
||||
this.completableSearchBuckets.add(new PlayerSearchOption(plugin));
|
||||
this.completableMatchOptions.add(new ItemAmountOption());
|
||||
this.completableMatchOptions.add(new ItemTypeOption());
|
||||
this.completableMatchMetaOptions.add(new ItemEnchantOption());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(
|
||||
@NotNull CommandSender sender,
|
||||
@NotNull Command command,
|
||||
@NotNull String label,
|
||||
@NotNull String[] args) {
|
||||
|
||||
if (args.length < 2) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String id = sender instanceof Player ? plugin.getPlayerID((Player) sender) : "CONSOLE";
|
||||
|
||||
if (activeSearches.contains(id)) {
|
||||
plugin.sendMessage(sender, "messages.error.search.activeSearch");
|
||||
return true;
|
||||
}
|
||||
|
||||
Collection<PseudoJson> arguments = new HashSet<>();
|
||||
for (String arg : args) {
|
||||
arg = arg.toLowerCase(Locale.ROOT);
|
||||
try {
|
||||
arguments.add(PseudoJson.fromString(arg));
|
||||
} catch (IllegalArgumentException e) {
|
||||
plugin.sendMessage(sender, "messages.error.search.invalidSchema", "%value%", arg);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
Collection<SearchBucket> searchBuckets = getSearchBuckets(sender, arguments);
|
||||
|
||||
if (searchBuckets.isEmpty()) {
|
||||
plugin.sendMessage(sender, "messages.error.search.invalidInventory");
|
||||
return true;
|
||||
}
|
||||
|
||||
ItemMatcher matcher = getMatcher(sender, arguments);
|
||||
|
||||
if (matcher == null) {
|
||||
plugin.sendMessage(sender, "messages.error.search.invalidMatcher");
|
||||
return true;
|
||||
}
|
||||
|
||||
activeSearches.add(id);
|
||||
|
||||
new Search(matcher, searchBuckets, () -> activeSearches.remove(id)).schedule(sender, plugin);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private @Nullable ItemMatcher getMatcher(@NotNull CommandSender sender, @NotNull Collection<PseudoJson> args) {
|
||||
List<PseudoOption<MatchableItem>> matchItemOptions = new ArrayList<>();
|
||||
List<PseudoOption<MatchableMeta>> matchMetaOptions = new ArrayList<>();
|
||||
|
||||
|
||||
for (PseudoJson arg : args) {
|
||||
addMatchOptions(completableMatchOptions, matchItemOptions, sender, arg);
|
||||
addMatchOptions(completableMatchMetaOptions, matchMetaOptions, sender, arg);
|
||||
}
|
||||
|
||||
// Must have a match option. Null entries indicate a parsing error.
|
||||
if (matchItemOptions.isEmpty()
|
||||
|| matchItemOptions.stream().anyMatch(Objects::isNull)
|
||||
|| matchMetaOptions.stream().anyMatch(Objects::isNull)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new ItemMatcher(
|
||||
matchItemOptions.stream().map(PseudoOption::option).toList(),
|
||||
matchMetaOptions.stream().map(PseudoOption::option).toList());
|
||||
}
|
||||
|
||||
private <T> void addMatchOptions(
|
||||
@NotNull Collection<CompletableOption<T>> completableOptions,
|
||||
@NotNull Collection<PseudoOption<T>> options,
|
||||
@NotNull CommandSender sender,
|
||||
@NotNull PseudoJson arg) {
|
||||
for (CompletableOption<T> option : completableOptions) {
|
||||
if (option.matches(sender, arg)) {
|
||||
PseudoOption<T> parsed = option.parse(sender, arg);
|
||||
if (parsed == null) {
|
||||
options.add(null);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (option.isUnique()) {
|
||||
String uniqueId = option.getName();
|
||||
|
||||
// Match existing options.
|
||||
List<PseudoOption<T>> matches = options.stream()
|
||||
.filter(Objects::nonNull)
|
||||
.filter(bucket -> bucket.pseudoJson().getIdentifier().equals(uniqueId))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// Remove all existing options.
|
||||
options.removeAll(matches);
|
||||
|
||||
// Merge with existing options.
|
||||
for (PseudoOption<T> match : matches) {
|
||||
PseudoOption<T> newParsed = option.merge(sender, match, parsed);
|
||||
if (newParsed != null) {
|
||||
parsed = newParsed;
|
||||
}
|
||||
}
|
||||
}
|
||||
options.add(parsed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Collection<SearchBucket> getSearchBuckets(
|
||||
@NotNull CommandSender sender,
|
||||
@NotNull Collection<PseudoJson> args) {
|
||||
List<PseudoOption<SearchBucket>> buckets = new ArrayList<>();
|
||||
|
||||
for (PseudoJson arg : args) {
|
||||
addMatchOptions(completableSearchBuckets, buckets, sender, arg);
|
||||
}
|
||||
|
||||
return buckets.stream().map(PseudoOption::option).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable List<String> onTabComplete(
|
||||
@NotNull CommandSender sender,
|
||||
@NotNull Command command,
|
||||
@NotNull String label,
|
||||
@NotNull String[] args) {
|
||||
|
||||
List<PseudoJson> arguments = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < args.length; i++) {
|
||||
String arg = args[i].toLowerCase(Locale.ROOT);
|
||||
try {
|
||||
arguments.add(PseudoJson.fromString(arg));
|
||||
} catch (IllegalArgumentException e) {
|
||||
if (i == args.length - 1) {
|
||||
// If last argument cannot be parsed, do not complete.
|
||||
return List.of();
|
||||
}
|
||||
// Otherwise, ignore formatting issues during tab completion.
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Ensure an argument exists.
|
||||
if (arguments.isEmpty()) {
|
||||
arguments.add(new PseudoJson(""));
|
||||
}
|
||||
|
||||
// Remove last indexed argument, it is being completed.
|
||||
PseudoJson last = arguments.remove(arguments.size() - 1);
|
||||
|
||||
// Due to generics, can't just use generic list of options to start with.
|
||||
Collection<PseudoOption<SearchBucket>> buckets = new HashSet<>();
|
||||
Collection<PseudoOption<MatchableItem>> items = new HashSet<>();
|
||||
Collection<PseudoOption<MatchableMeta>> metas = new HashSet<>();
|
||||
for (PseudoJson arg : arguments) {
|
||||
addMatchOptions(completableSearchBuckets, buckets, sender, arg);
|
||||
addMatchOptions(completableMatchOptions, items, sender, arg);
|
||||
addMatchOptions(completableMatchMetaOptions, metas, sender, arg);
|
||||
}
|
||||
Collection<PseudoOption<?>> options = new HashSet<>();
|
||||
options.addAll(buckets);
|
||||
options.addAll(items);
|
||||
options.addAll(metas);
|
||||
|
||||
// Suggest all completable options' completions.
|
||||
return Stream.concat(completableSearchBuckets.stream(),
|
||||
Stream.concat(completableMatchOptions.stream(),
|
||||
completableMatchMetaOptions.stream()))
|
||||
// Don't suggest unique options that are already present.
|
||||
.filter(option ->
|
||||
option.isUnique() && options.stream().anyMatch(pseudoOption ->
|
||||
pseudoOption.pseudoJson().getIdentifier().equals(option.getName())))
|
||||
.flatMap(option -> option.suggestOptions(sender, last).stream())
|
||||
.distinct()
|
||||
.toList();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv.commands;
|
||||
|
||||
import com.lishid.openinv.OpenInv;
|
||||
import com.lishid.openinv.util.TabCompleter;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import org.bukkit.Chunk;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.block.BlockState;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.command.TabExecutor;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.InventoryHolder;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* Command for searching containers in a radius of chunks.
|
||||
*/
|
||||
public class SearchContainerCommand implements TabExecutor {
|
||||
|
||||
private final OpenInv plugin;
|
||||
|
||||
public SearchContainerCommand(OpenInv plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
|
||||
if (!(sender instanceof Player senderPlayer)) {
|
||||
plugin.sendMessage(sender, "messages.error.consoleUnsupported");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (args.length < 1) {
|
||||
// Must supply material
|
||||
return false;
|
||||
}
|
||||
|
||||
Material material = Material.getMaterial(args[0].toUpperCase());
|
||||
|
||||
if (material == null) {
|
||||
plugin.sendMessage(sender, "messages.error.invalidMaterial", "%target%", args[0]);
|
||||
return false;
|
||||
}
|
||||
|
||||
int radius = 5;
|
||||
|
||||
if (args.length > 1) {
|
||||
try {
|
||||
radius = Integer.parseInt(args[1]);
|
||||
} catch (NumberFormatException e) {
|
||||
// Invalid radius supplied
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
World world = senderPlayer.getWorld();
|
||||
Chunk centerChunk = senderPlayer.getLocation().getChunk();
|
||||
StringBuilder locations = new StringBuilder();
|
||||
|
||||
for (int dX = -radius; dX <= radius; ++dX) {
|
||||
for (int dZ = -radius; dZ <= radius; ++dZ) {
|
||||
if (!world.loadChunk(centerChunk.getX() + dX, centerChunk.getZ() + dZ, false)) {
|
||||
continue;
|
||||
}
|
||||
Chunk chunk = world.getChunkAt(centerChunk.getX() + dX, centerChunk.getZ() + dZ);
|
||||
for (BlockState tileEntity : chunk.getTileEntities()) {
|
||||
if (!(tileEntity instanceof InventoryHolder holder)) {
|
||||
continue;
|
||||
}
|
||||
if (!holder.getInventory().contains(material)) {
|
||||
continue;
|
||||
}
|
||||
locations.append(holder.getInventory().getType().name().toLowerCase()).append(" (")
|
||||
.append(tileEntity.getX()).append(',').append(tileEntity.getY()).append(',')
|
||||
.append(tileEntity.getZ()).append("), ");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Matches found, delete trailing comma and space
|
||||
if (locations.length() > 0) {
|
||||
locations.delete(locations.length() - 2, locations.length());
|
||||
} else {
|
||||
plugin.sendMessage(sender, "messages.info.container.noMatches",
|
||||
"%target%", material.name());
|
||||
return true;
|
||||
}
|
||||
|
||||
plugin.sendMessage(sender, "messages.info.container.matches",
|
||||
"%target%", material.name(), "%detail%", locations.toString());
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
|
||||
if (args.length < 1 || args.length > 2 || !command.testPermissionSilent(sender)) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
String argument = args[args.length - 1];
|
||||
if (args.length == 1) {
|
||||
return TabCompleter.completeEnum(argument, Material.class);
|
||||
} else {
|
||||
return TabCompleter.completeInteger(argument);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,168 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv.commands;
|
||||
|
||||
import com.lishid.openinv.OpenInv;
|
||||
import com.lishid.openinv.util.TabCompleter;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.command.TabExecutor;
|
||||
import org.bukkit.enchantments.Enchantment;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Command adding the ability to search online players' inventories for enchantments of a specific
|
||||
* type at or above the level specified.
|
||||
*
|
||||
* @author Jikoo
|
||||
*/
|
||||
public class SearchEnchantCommand implements TabExecutor {
|
||||
|
||||
private final OpenInv plugin;
|
||||
|
||||
public SearchEnchantCommand(OpenInv plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
|
||||
if (args.length == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Enchantment enchant = null;
|
||||
int level = 0;
|
||||
|
||||
for (String argument : args) {
|
||||
try {
|
||||
level = Integer.parseInt(argument);
|
||||
continue;
|
||||
} catch (NumberFormatException ignored) {}
|
||||
|
||||
argument = argument.toLowerCase();
|
||||
int colon = argument.indexOf(':');
|
||||
NamespacedKey key;
|
||||
try {
|
||||
if (colon > -1 && colon < argument.length() - 1) {
|
||||
key = new NamespacedKey(argument.substring(0, colon), argument.substring(colon + 1));
|
||||
} else {
|
||||
key = NamespacedKey.minecraft(argument);
|
||||
}
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Enchantment localEnchant = Enchantment.getByKey(key);
|
||||
if (localEnchant != null) {
|
||||
enchant = localEnchant;
|
||||
}
|
||||
}
|
||||
|
||||
// Arguments not set correctly
|
||||
if (level == 0 && enchant == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
StringBuilder players = new StringBuilder();
|
||||
for (Player player : plugin.getServer().getOnlinePlayers()) {
|
||||
boolean flagInventory = containsEnchantment(player.getInventory(), enchant, level);
|
||||
boolean flagEnder = containsEnchantment(player.getEnderChest(), enchant, level);
|
||||
|
||||
// No matches, continue
|
||||
if (!flagInventory && !flagEnder) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Matches, append details
|
||||
players.append(player.getName()).append(" (");
|
||||
if (flagInventory) {
|
||||
players.append("inv");
|
||||
}
|
||||
if (flagEnder) {
|
||||
if (flagInventory) {
|
||||
players.append(',');
|
||||
}
|
||||
players.append("ender");
|
||||
}
|
||||
players.append("), ");
|
||||
}
|
||||
|
||||
if (players.length() > 0) {
|
||||
// Matches found, delete trailing comma and space
|
||||
players.delete(players.length() - 2, players.length());
|
||||
} else {
|
||||
plugin.sendMessage(sender, "messages.info.player.noMatches",
|
||||
"%target%", (enchant != null ? enchant.getKey().toString() : "") + " >= " + level);
|
||||
return true;
|
||||
}
|
||||
|
||||
plugin.sendMessage(sender, "messages.info.player.matches",
|
||||
"%target%", (enchant != null ? enchant.getKey().toString() : "") + " >= " + level,
|
||||
"%detail%", players.toString());
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean containsEnchantment(Inventory inventory, @Nullable Enchantment enchant, int minLevel) {
|
||||
for (ItemStack item : inventory.getContents()) {
|
||||
if (item == null || item.getType() == Material.AIR) {
|
||||
continue;
|
||||
}
|
||||
if (enchant != null) {
|
||||
if (item.containsEnchantment(enchant) && item.getEnchantmentLevel(enchant) >= minLevel) {
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
if (!item.hasItemMeta()) {
|
||||
continue;
|
||||
}
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
if (meta == null || !meta.hasEnchants()) {
|
||||
continue;
|
||||
}
|
||||
for (int enchLevel : meta.getEnchants().values()) {
|
||||
if (enchLevel >= minLevel) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
|
||||
if (!command.testPermissionSilent(sender) || args.length < 1 || args.length > 2) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
if (args.length == 1) {
|
||||
return TabCompleter.completeObject(args[0], enchantment -> enchantment.getKey().toString(), Enchantment.values());
|
||||
} else {
|
||||
return TabCompleter.completeInteger(args[1]);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv.commands;
|
||||
|
||||
import com.lishid.openinv.OpenInv;
|
||||
import com.lishid.openinv.util.TabCompleter;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.command.TabExecutor;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class SearchInvCommand implements TabExecutor {
|
||||
|
||||
private final OpenInv plugin;
|
||||
|
||||
public SearchInvCommand(OpenInv plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
|
||||
|
||||
Material material = null;
|
||||
|
||||
if (args.length >= 1) {
|
||||
material = Material.getMaterial(args[0].toUpperCase());
|
||||
}
|
||||
|
||||
if (material == null) {
|
||||
plugin.sendMessage(sender, "messages.error.invalidMaterial", "%target%", args.length > 0 ? args[0] : "null");
|
||||
return false;
|
||||
}
|
||||
|
||||
int count = 1;
|
||||
|
||||
if (args.length >= 2) {
|
||||
try {
|
||||
count = Integer.parseInt(args[1]);
|
||||
} catch (NumberFormatException ex) {
|
||||
plugin.sendMessage(sender, "messages.error.invalidNumber", "%target%", args[1]);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
StringBuilder players = new StringBuilder();
|
||||
boolean searchInv = command.getName().equals("searchinv");
|
||||
for (Player player : plugin.getServer().getOnlinePlayers()) {
|
||||
Inventory inventory = searchInv ? player.getInventory() : player.getEnderChest();
|
||||
if (inventory.contains(material, count)) {
|
||||
players.append(player.getName()).append(", ");
|
||||
}
|
||||
}
|
||||
|
||||
// Matches found, delete trailing comma and space
|
||||
if (players.length() > 0) {
|
||||
players.delete(players.length() - 2, players.length());
|
||||
} else {
|
||||
plugin.sendMessage(sender, "messages.info.player.noMatches",
|
||||
"%target%", material.name());
|
||||
return true;
|
||||
}
|
||||
|
||||
plugin.sendMessage(sender, "messages.info.player.matches",
|
||||
"%target%", material.name(), "%detail%", players.toString());
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
|
||||
if (args.length < 1 || args.length > 2 || !command.testPermissionSilent(sender)) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
String argument = args[args.length - 1];
|
||||
if (args.length == 1) {
|
||||
return TabCompleter.completeEnum(argument, Material.class);
|
||||
} else {
|
||||
return TabCompleter.completeInteger(argument);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv.commands.search;
|
||||
|
||||
import com.lishid.openinv.search.bucket.ChunkBucket;
|
||||
import com.lishid.openinv.search.bucket.SearchBucket;
|
||||
import com.lishid.openinv.util.Permissions;
|
||||
import com.lishid.openinv.util.PseudoJson;
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Chunk;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class ChunkSearchOption implements CompletableOption<SearchBucket> {
|
||||
|
||||
@Override
|
||||
public @NotNull String getName() {
|
||||
return "chunk";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean matches(@NotNull CommandSender sender, @NotNull PseudoJson pseudoJson) {
|
||||
return CompletableOption.super.matches(sender, pseudoJson)
|
||||
&& Permissions.SEARCH_CHUNKS_LOADED.hasPermission(sender);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable PseudoOption<SearchBucket> parse(@NotNull CommandSender sender, @NotNull PseudoJson pseudoJson) {
|
||||
World world = null;
|
||||
Integer chunkX = null;
|
||||
Integer chunkZ = null;
|
||||
int chunkRadius = 5;
|
||||
boolean chunkLoad = false;
|
||||
Map<String, String> mappings = pseudoJson.getMappings();
|
||||
|
||||
if (!(sender instanceof Player senderPlayer)) {
|
||||
if (mappings.size() < 3) {
|
||||
// Console must specify world, x center, z center.
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
world = senderPlayer.getWorld();
|
||||
Chunk senderChunk = senderPlayer.getLocation().getChunk();
|
||||
chunkX = senderChunk.getX();
|
||||
chunkZ = senderChunk.getZ();
|
||||
}
|
||||
|
||||
for (Map.Entry<String, String> entry : mappings.entrySet()) {
|
||||
String key = entry.getKey();
|
||||
String value = entry.getValue();
|
||||
|
||||
if (key.indexOf('w') >= 0) {
|
||||
world = null;
|
||||
// Name should always be lower case by this point. Ignore case when selecting world.
|
||||
for (World loaded : Bukkit.getWorlds()) {
|
||||
if (loaded.getName().equalsIgnoreCase(value)) {
|
||||
world = loaded;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else if (key.indexOf('x') >= 0) {
|
||||
try {
|
||||
chunkX = Integer.parseInt(value);
|
||||
} catch (NumberFormatException e) {
|
||||
chunkX = null;
|
||||
}
|
||||
} else if (key.indexOf('z') >= 0) {
|
||||
try {
|
||||
chunkZ = Integer.parseInt(value);
|
||||
} catch (NumberFormatException e) {
|
||||
chunkZ = null;
|
||||
}
|
||||
} else if (key.indexOf('r') >= 0) {
|
||||
// R is for radius. Needs to be checked later so that "world" doesn't result in a false positive.
|
||||
try {
|
||||
chunkRadius = Integer.parseInt(value);
|
||||
} catch (NumberFormatException e) {
|
||||
// Fall through to default radius.
|
||||
}
|
||||
} else if (key.indexOf('l') >= 0) {
|
||||
// L is for loaded. Needs to be checked later so that "world" doesn't result in a false positive.
|
||||
chunkLoad = Permissions.SEARCH_CHUNKS_UNLOADED.hasPermission(sender) && Boolean.parseBoolean(value);
|
||||
}
|
||||
}
|
||||
|
||||
if (world == null || chunkX == null || chunkZ == null || chunkRadius < 0) {
|
||||
// Invalid data provided.
|
||||
return null;
|
||||
}
|
||||
|
||||
return new PseudoOption<>(pseudoJson, new ChunkBucket(world, chunkX, chunkZ, chunkRadius, chunkLoad));
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Collection<String> suggestOptions(@NotNull CommandSender sender, @NotNull PseudoJson pseudoJson) {
|
||||
// TODO
|
||||
return Set.of();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUnique() {
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv.commands.search;
|
||||
|
||||
import com.lishid.openinv.util.PseudoJson;
|
||||
import java.util.Collection;
|
||||
import java.util.Locale;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Interface defining behavior for an option.
|
||||
*
|
||||
* @param <T> the type of option represented
|
||||
*/
|
||||
public interface CompletableOption<T> {
|
||||
|
||||
/**
|
||||
* Get unique identifier representing the option.
|
||||
*
|
||||
* @return the unique identifier
|
||||
*/
|
||||
@NotNull String getName();
|
||||
|
||||
/**
|
||||
* Check if the <code>CompletableOption</code> matches the given <code>PseudoJson</code>.
|
||||
*
|
||||
* @param sender the individual using the option
|
||||
* @param pseudoJson the pseudo-JSON element
|
||||
* @return true if the CompletableOption matches
|
||||
*/
|
||||
default boolean matches(@NotNull CommandSender sender, @NotNull PseudoJson pseudoJson) {
|
||||
return pseudoJson.getIdentifier().toLowerCase(Locale.ROOT).startsWith(getName());
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the option represented from the given <code>PseudoJson</code>.
|
||||
*
|
||||
* @param sender the individual using the option
|
||||
* @param pseudoJson the pseudo-JSON element
|
||||
* @return the parsed options
|
||||
*/
|
||||
@Nullable PseudoOption<T> parse(@NotNull CommandSender sender, @NotNull PseudoJson pseudoJson);
|
||||
|
||||
/**
|
||||
* Form a collection of viable permutations to suggest for the given <code>PseudoJson</code>.
|
||||
*
|
||||
* @param sender the individual to suggest options for
|
||||
* @param pseudoJson the parsed pseudo-JSON
|
||||
* @return the suggested permutations
|
||||
*/
|
||||
@NotNull Collection<String> suggestOptions(
|
||||
@NotNull CommandSender sender,
|
||||
@NotNull PseudoJson pseudoJson);
|
||||
|
||||
/**
|
||||
* Get whether or not multiple different copies of this <code>CompletableOption</code> are allowed.
|
||||
*
|
||||
* @return true if only a single instance is allowed
|
||||
*/
|
||||
boolean isUnique();
|
||||
|
||||
/**
|
||||
* Merge similar elements. Used to enforce {@link #isUnique()} despite multiples being provided.
|
||||
*
|
||||
* @param sender the individual using the options
|
||||
* @param first the first parsed option
|
||||
* @param second the second parsed option
|
||||
* @return a single element containing a best-effort merge of both
|
||||
*/
|
||||
default @Nullable PseudoOption<T> merge(
|
||||
@NotNull CommandSender sender,
|
||||
@NotNull PseudoOption<?> first,
|
||||
@NotNull PseudoOption<?> second) {
|
||||
PseudoJson merge = new PseudoJson(first.pseudoJson().getIdentifier());
|
||||
|
||||
// Use mappings of first for our base.
|
||||
first.pseudoJson().getMappings().forEach(merge::put);
|
||||
// Overwrite with second.
|
||||
second.pseudoJson().getMappings().forEach(merge::put);
|
||||
|
||||
// Parse merged options.
|
||||
PseudoOption<T> parsed = parse(sender, merge);
|
||||
|
||||
if (parsed != null) {
|
||||
return parsed;
|
||||
}
|
||||
|
||||
// On parsing failure, try second instead.
|
||||
merge = new PseudoJson(second.pseudoJson().getIdentifier(), merge.getMappings());
|
||||
|
||||
return parse(sender, merge);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv.commands.search;
|
||||
|
||||
import com.lishid.openinv.search.match.ItemMatchables;
|
||||
import com.lishid.openinv.search.match.MatchableItem;
|
||||
import com.lishid.openinv.util.PseudoJson;
|
||||
import com.lishid.openinv.util.TabCompleter;
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.util.StringUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class ItemAmountOption implements CompletableOption<MatchableItem> {
|
||||
|
||||
@Override
|
||||
public @NotNull String getName() {
|
||||
return "amount";
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable PseudoOption<MatchableItem> parse(@NotNull CommandSender sender, @NotNull PseudoJson pseudoJson) {
|
||||
String minAmountString = pseudoJson.getMappings().entrySet().stream().findFirst().map(Map.Entry::getValue).orElse(null);
|
||||
if (minAmountString == null) {
|
||||
// Amount not correctly specified. Warn about spec.
|
||||
return null;
|
||||
}
|
||||
int minAmount;
|
||||
try {
|
||||
minAmount = Integer.parseInt(minAmountString);
|
||||
} catch (NumberFormatException e) {
|
||||
// Amount can't be parsed. Warn about spec.
|
||||
return null;
|
||||
}
|
||||
|
||||
return new PseudoOption<>(pseudoJson, ItemMatchables.hasAmount(minAmount));
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Collection<String> suggestOptions(@NotNull CommandSender sender, @NotNull PseudoJson pseudoJson) {
|
||||
// TODO combine with type
|
||||
if (!pseudoJson.getIdentifier().equals(getName())) {
|
||||
// Suggest name while unformed.
|
||||
if (StringUtil.startsWithIgnoreCase(getName(), pseudoJson.getIdentifier())) {
|
||||
return Set.of(getName() + ":");
|
||||
}
|
||||
// If name is not a valid suggestion, suggest nothing.
|
||||
return Set.of();
|
||||
}
|
||||
|
||||
String minAmountString = pseudoJson.getMappings().entrySet().stream().findFirst().map(Map.Entry::getValue).orElse("");
|
||||
|
||||
// Find and suggest name in full pseudojson.
|
||||
return TabCompleter.completeInteger(minAmountString).stream().map(match -> {
|
||||
PseudoJson amount = new PseudoJson(getName());
|
||||
amount.put(getName(), match);
|
||||
return amount;
|
||||
}).map(PseudoJson::asString).collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUnique() {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv.commands.search;
|
||||
|
||||
import com.github.jikoo.planarwrappers.util.StringConverters;
|
||||
import com.lishid.openinv.search.match.ItemMatchables;
|
||||
import com.lishid.openinv.search.match.MatchableMeta;
|
||||
import com.lishid.openinv.util.PseudoJson;
|
||||
import com.lishid.openinv.util.TabCompleter;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.enchantments.Enchantment;
|
||||
import org.bukkit.util.StringUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class ItemEnchantOption implements CompletableOption<MatchableMeta> {
|
||||
|
||||
@Override
|
||||
public @NotNull String getName() {
|
||||
return "enchant";
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable PseudoOption<MatchableMeta> parse(@NotNull CommandSender sender, @NotNull PseudoJson pseudoJson) {
|
||||
Enchantment enchantment = null;
|
||||
Integer enchantLevel = null;
|
||||
for (Map.Entry<String, String> entry : pseudoJson.getMappings().entrySet()) {
|
||||
if (entry.getValue().isBlank()) {
|
||||
continue;
|
||||
}
|
||||
if (entry.getKey().indexOf('l') >= 0) {
|
||||
try {
|
||||
enchantLevel = Integer.parseInt(entry.getValue());
|
||||
} catch (NumberFormatException e) {
|
||||
// Level can't be parsed. Warn about spec.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (entry.getKey().indexOf('t') >= 0) {
|
||||
enchantment = StringConverters.toEnchant(entry.getValue());
|
||||
if (enchantment == null) {
|
||||
// Enchantment is specified but can't be parsed. Warn about spec.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new PseudoOption<>(pseudoJson, ItemMatchables.hasEnchant(enchantment, enchantLevel));
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Collection<String> suggestOptions(@NotNull CommandSender sender, @NotNull PseudoJson pseudoJson) {
|
||||
if (!pseudoJson.getIdentifier().equals(getName())) {
|
||||
if (!StringUtil.startsWithIgnoreCase(getName(), pseudoJson.getIdentifier())) {
|
||||
// If enchant is not a valid suggestion, suggest nothing.
|
||||
return Set.of();
|
||||
}
|
||||
|
||||
// Suggest all options while unformed.
|
||||
Set<String> set = new HashSet<>();
|
||||
PseudoJson enchant = new PseudoJson(getName());
|
||||
set.add(enchant.asString());
|
||||
enchant.put("type", "");
|
||||
set.add(enchant.asString());
|
||||
enchant.put("level", "");
|
||||
set.add(enchant.asString());
|
||||
enchant.remove("type");
|
||||
set.add(enchant.asString());
|
||||
return set;
|
||||
}
|
||||
|
||||
Collection<String> enchantments = null;
|
||||
Integer enchantLevel = null;
|
||||
for (Map.Entry<String, String> entry : pseudoJson.getMappings().entrySet()) {
|
||||
if (entry.getValue().isBlank()) {
|
||||
continue;
|
||||
}
|
||||
if (entry.getKey().indexOf('l') >= 0) {
|
||||
try {
|
||||
enchantLevel = Integer.parseInt(entry.getValue());
|
||||
} catch (NumberFormatException e) {
|
||||
// Level is present but cannot be parsed. Default 0.
|
||||
enchantLevel = 0;
|
||||
}
|
||||
}
|
||||
if (entry.getKey().indexOf('t') >= 0) {
|
||||
Enchantment enchant = StringConverters.toEnchant(entry.getValue());
|
||||
if (enchant == null) {
|
||||
// Enchantment is specified but can't be parsed, tab complete.
|
||||
enchantments = TabCompleter.completeKeyed(entry.getValue(), Enchantment.values());
|
||||
} else {
|
||||
enchantments = Set.of(entry.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
PseudoJson enchant = new PseudoJson(getName());
|
||||
if (enchantLevel != null) {
|
||||
enchant.put("level", String.valueOf(enchantLevel));
|
||||
}
|
||||
|
||||
if (enchantments == null) {
|
||||
return Set.of(enchant.asString());
|
||||
}
|
||||
|
||||
return enchantments.stream().map(enchantment -> {
|
||||
// Reuse is fine, single-threaded.
|
||||
enchant.put("type", enchantment);
|
||||
return enchant;
|
||||
}).map(PseudoJson::asString).collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUnique() {
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv.commands.search;
|
||||
|
||||
import com.github.jikoo.planarwrappers.util.StringConverters;
|
||||
import com.lishid.openinv.search.match.ItemMatchables;
|
||||
import com.lishid.openinv.search.match.MatchableItem;
|
||||
import com.lishid.openinv.util.PseudoJson;
|
||||
import com.lishid.openinv.util.TabCompleter;
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.util.StringUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class ItemTypeOption implements CompletableOption<MatchableItem> {
|
||||
|
||||
@Override
|
||||
public @NotNull String getName() {
|
||||
return "type";
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable PseudoOption<MatchableItem> parse(@NotNull CommandSender sender, @NotNull PseudoJson pseudoJson) {
|
||||
String typeName = pseudoJson.getMappings().entrySet().stream().findFirst().map(Map.Entry::getValue).orElse(null);
|
||||
Material material = StringConverters.toMaterial(typeName);
|
||||
if (material == null) {
|
||||
// Invalid material, warn about matcher spec.
|
||||
return null;
|
||||
}
|
||||
return new PseudoOption<>(pseudoJson, ItemMatchables.isType(material));
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Collection<String> suggestOptions(@NotNull CommandSender sender, @NotNull PseudoJson pseudoJson) {
|
||||
if (!pseudoJson.getIdentifier().equals(getName())) {
|
||||
// Suggest name while unformed.
|
||||
if (StringUtil.startsWithIgnoreCase(getName(), pseudoJson.getIdentifier())) {
|
||||
return Set.of(getName() + ":");
|
||||
}
|
||||
// If name is not a valid suggestion, suggest nothing.
|
||||
return Set.of();
|
||||
}
|
||||
|
||||
String typeName = pseudoJson.getMappings().entrySet().stream().findFirst().map(Map.Entry::getValue).orElse("");
|
||||
|
||||
// Find and suggest matching types in full pseudojson.
|
||||
return TabCompleter.completeMaterial(typeName).stream().map(match -> {
|
||||
PseudoJson type = new PseudoJson(getName());
|
||||
type.put(getName(), match);
|
||||
return type;
|
||||
}).map(PseudoJson::asString).collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUnique() {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv.commands.search;
|
||||
|
||||
import com.lishid.openinv.OpenInv;
|
||||
import com.lishid.openinv.search.bucket.PlayerBucket;
|
||||
import com.lishid.openinv.search.bucket.SearchBucket;
|
||||
import com.lishid.openinv.util.Permissions;
|
||||
import com.lishid.openinv.util.PseudoJson;
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class PlayerSearchOption implements CompletableOption<SearchBucket> {
|
||||
|
||||
private final OpenInv plugin;
|
||||
|
||||
public PlayerSearchOption(OpenInv plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull String getName() {
|
||||
return "player";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean matches(@NotNull CommandSender sender, @NotNull PseudoJson pseudoJson) {
|
||||
return CompletableOption.super.matches(sender, pseudoJson)
|
||||
&& Permissions.SEARCH_PLAYERS_ONLINE.hasPermission(sender);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable PseudoOption<SearchBucket> parse(@NotNull CommandSender sender, @NotNull PseudoJson pseudoJson) {
|
||||
Optional<Boolean> optional = pseudoJson.getMappings().entrySet().stream()
|
||||
.filter(entry -> entry.getKey().contains("offline"))
|
||||
.findFirst()
|
||||
.map(Map.Entry::getValue)
|
||||
.map(Boolean::parseBoolean);
|
||||
|
||||
return new PseudoOption<>(
|
||||
pseudoJson, new PlayerBucket(plugin,
|
||||
!(optional.orElse(false) && Permissions.SEARCH_PLAYERS_OFFLINE.hasPermission(sender))));
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Collection<String> suggestOptions(@NotNull CommandSender sender, @NotNull PseudoJson pseudoJson) {
|
||||
// TODO
|
||||
return Set.of();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUnique() {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv.commands.search;
|
||||
|
||||
import com.lishid.openinv.util.PseudoJson;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* Data holder for completable options.
|
||||
*
|
||||
* @param <T> the type of data
|
||||
*/
|
||||
public record PseudoOption<T>(@NotNull PseudoJson pseudoJson, @NotNull T option) {}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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 com.lishid.openinv.internal;
|
||||
|
||||
import com.lishid.openinv.OpenInv;
|
||||
import java.util.Objects;
|
||||
import org.bukkit.entity.HumanEntity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.inventory.InventoryType;
|
||||
@@ -71,7 +70,11 @@ public class OpenInventoryView extends InventoryView {
|
||||
titleKey,
|
||||
"%player%",
|
||||
owner.getName());
|
||||
title = Objects.requireNonNullElseGet(localTitle, () -> owner.getName() + titleDefaultSuffix);
|
||||
if (localTitle != null) {
|
||||
title = localTitle;
|
||||
} else {
|
||||
title = owner.getName() + titleDefaultSuffix;
|
||||
}
|
||||
}
|
||||
|
||||
return title;
|
||||
|
||||
+17
-19
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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
|
||||
@@ -14,9 +14,9 @@
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.lishid.openinv;
|
||||
package com.lishid.openinv.listeners;
|
||||
|
||||
import com.lishid.openinv.internal.ISpecialInventory;
|
||||
import com.lishid.openinv.OpenInv;
|
||||
import com.lishid.openinv.internal.ISpecialPlayerInventory;
|
||||
import com.lishid.openinv.util.InventoryAccess;
|
||||
import com.lishid.openinv.util.Permissions;
|
||||
@@ -45,31 +45,29 @@ import org.jetbrains.annotations.Nullable;
|
||||
*
|
||||
* @author Jikoo
|
||||
*/
|
||||
record InventoryListener(OpenInv plugin) implements Listener {
|
||||
public class InventoryListener implements Listener {
|
||||
|
||||
private final OpenInv plugin;
|
||||
|
||||
public InventoryListener(final OpenInv plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
private void onInventoryClose(@NotNull final InventoryCloseEvent event) {
|
||||
if (!(event.getPlayer() instanceof Player player)) {
|
||||
public void onInventoryClose(@NotNull final InventoryCloseEvent event) {
|
||||
if (!(event.getPlayer() instanceof Player)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.plugin.getSilentContainerStatus(player)) {
|
||||
this.plugin.getAnySilentContainer().deactivateContainer(player);
|
||||
}
|
||||
Player player = (Player) event.getPlayer();
|
||||
|
||||
ISpecialInventory specialInventory = InventoryAccess.getEnderChest(event.getInventory());
|
||||
if (specialInventory != null) {
|
||||
this.plugin.handleCloseInventory(event.getPlayer(), specialInventory);
|
||||
} else {
|
||||
specialInventory = InventoryAccess.getPlayerInventory(event.getInventory());
|
||||
if (specialInventory != null) {
|
||||
this.plugin.handleCloseInventory(event.getPlayer(), specialInventory);
|
||||
}
|
||||
if (this.plugin.getPlayerSilentChestStatus(player)) {
|
||||
this.plugin.getAnySilentContainer().deactivateContainer(player);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST)
|
||||
private void onInventoryClick(@NotNull final InventoryClickEvent event) {
|
||||
public void onInventoryClick(@NotNull final InventoryClickEvent event) {
|
||||
if (handleInventoryInteract(event)) {
|
||||
return;
|
||||
}
|
||||
@@ -103,7 +101,7 @@ record InventoryListener(OpenInv plugin) implements Listener {
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST)
|
||||
private void onInventoryDrag(@NotNull final InventoryDragEvent event) {
|
||||
public void onInventoryDrag(@NotNull final InventoryDragEvent event) {
|
||||
if (handleInventoryInteract(event)) {
|
||||
return;
|
||||
}
|
||||
+20
-14
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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
|
||||
@@ -14,8 +14,9 @@
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.lishid.openinv;
|
||||
package com.lishid.openinv.listeners;
|
||||
|
||||
import com.lishid.openinv.OpenInv;
|
||||
import com.lishid.openinv.util.Permissions;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Event.Result;
|
||||
@@ -27,27 +28,32 @@ import org.bukkit.event.player.PlayerChangedWorldEvent;
|
||||
import org.bukkit.event.player.PlayerInteractEvent;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
record PlayerListener(OpenInv plugin) implements Listener {
|
||||
public class PlayerListener implements Listener {
|
||||
|
||||
private final OpenInv plugin;
|
||||
|
||||
public PlayerListener(OpenInv plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST)
|
||||
private void onPlayerJoin(@NotNull PlayerJoinEvent event) {
|
||||
public void onPlayerJoin(final PlayerJoinEvent event) {
|
||||
plugin.setPlayerOnline(event.getPlayer());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
private void onPlayerQuit(@NotNull PlayerQuitEvent event) {
|
||||
public void onPlayerQuit(PlayerQuitEvent event) {
|
||||
plugin.setPlayerOffline(event.getPlayer());
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
private void onWorldChange(@NotNull PlayerChangedWorldEvent event) {
|
||||
public void onWorldChange(PlayerChangedWorldEvent event) {
|
||||
plugin.changeWorld(event.getPlayer());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
private void onPlayerInteract(@NotNull PlayerInteractEvent event) {
|
||||
public void onPlayerInteract(PlayerInteractEvent event) {
|
||||
|
||||
// Do not cancel 3rd party plugins' custom events
|
||||
if (!PlayerInteractEvent.class.equals(event.getClass())) {
|
||||
@@ -61,23 +67,23 @@ record PlayerListener(OpenInv plugin) implements Listener {
|
||||
}
|
||||
|
||||
Player player = event.getPlayer();
|
||||
boolean any = Permissions.ANYCHEST.hasPermission(player) && plugin.getAnyContainerStatus(player);
|
||||
boolean needsAny = plugin.getAnySilentContainer().isAnyContainerNeeded(event.getClickedBlock());
|
||||
boolean any = Permissions.ANYCHEST.hasPermission(player) && plugin.getPlayerAnyChestStatus(player);
|
||||
boolean needsAny = plugin.getAnySilentContainer().isAnyContainerNeeded(player, event.getClickedBlock());
|
||||
|
||||
if (!any && needsAny) {
|
||||
return;
|
||||
}
|
||||
|
||||
boolean silent = Permissions.SILENT.hasPermission(player) && plugin.getSilentContainerStatus(player);
|
||||
boolean silent = Permissions.SILENT.hasPermission(player) && plugin.getPlayerSilentChestStatus(player);
|
||||
|
||||
// If anycontainer or silentcontainer is active
|
||||
if (any || silent) {
|
||||
if (plugin.getAnySilentContainer().activateContainer(player, silent, event.getClickedBlock())) {
|
||||
if (silent && needsAny) {
|
||||
if (silent && plugin.notifySilentChest() && needsAny && plugin.notifyAnyChest()) {
|
||||
plugin.sendSystemMessage(player, "messages.info.containerBlockedSilent");
|
||||
} else if (needsAny) {
|
||||
} else if (needsAny && plugin.notifyAnyChest()) {
|
||||
plugin.sendSystemMessage(player, "messages.info.containerBlocked");
|
||||
} else if (silent) {
|
||||
} else if (silent && plugin.notifySilentChest()) {
|
||||
plugin.sendSystemMessage(player, "messages.info.containerSilent");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv.listeners;
|
||||
|
||||
import com.lishid.openinv.OpenInv;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.server.PluginDisableEvent;
|
||||
|
||||
/**
|
||||
* Listener for plugin-related events.
|
||||
*
|
||||
* @author Jikoo
|
||||
*/
|
||||
public class PluginListener implements Listener {
|
||||
|
||||
private final OpenInv plugin;
|
||||
|
||||
public PluginListener(OpenInv plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPluginDisable(PluginDisableEvent event) {
|
||||
plugin.releaseAllPlayers(event.getPlugin());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv.search;
|
||||
|
||||
import com.lishid.openinv.OpenInv;
|
||||
import com.lishid.openinv.search.bucket.SearchBucket;
|
||||
import com.lishid.openinv.search.match.ItemMatcher;
|
||||
import com.lishid.openinv.search.match.MatchResult;
|
||||
import com.lishid.openinv.search.match.Matchable;
|
||||
import com.lishid.openinv.util.MessagePart;
|
||||
import java.text.DecimalFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.stream.Collectors;
|
||||
import net.md_5.bungee.api.chat.BaseComponent;
|
||||
import net.md_5.bungee.api.chat.TextComponent;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.scheduler.BukkitRunnable;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* A search function.
|
||||
*/
|
||||
public class Search {
|
||||
|
||||
public static final BaseComponent SEPARATOR = new TextComponent(", ");
|
||||
|
||||
private final Set<MessagePart> matches = new HashSet<>();
|
||||
private final ItemMatcher matcher;
|
||||
private final double totalMatchables;
|
||||
private final Iterator<SearchBucket> bucketIterator;
|
||||
private final Runnable callback;
|
||||
private SearchBucket current = null;
|
||||
private int polls = 0;
|
||||
|
||||
public Search(
|
||||
@NotNull ItemMatcher matcher,
|
||||
@NotNull Collection<@NotNull SearchBucket> buckets,
|
||||
@Nullable Runnable callback) {
|
||||
// Just in case, copy contents to new set.
|
||||
Set<SearchBucket> bucketSet = new HashSet<>(buckets);
|
||||
this.matcher = matcher;
|
||||
this.totalMatchables = bucketSet.stream().mapToInt(SearchBucket::size).sum();
|
||||
this.bucketIterator = bucketSet.iterator();
|
||||
this.callback = callback;
|
||||
}
|
||||
|
||||
private boolean isComplete(OpenInv plugin) {
|
||||
if (matches.size() >= plugin.getSearchResultsMax()) {
|
||||
return true;
|
||||
}
|
||||
if (current != null && current.hasNext()) {
|
||||
return false;
|
||||
}
|
||||
while (bucketIterator.hasNext()) {
|
||||
current = bucketIterator.next();
|
||||
if (current.hasNext()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Search the configured amount of Matchables.
|
||||
*
|
||||
* <p>Matchables are assembled asynchronously, then
|
||||
*
|
||||
* @param plugin the OpenInv instance
|
||||
*/
|
||||
private void poll(OpenInv plugin) {
|
||||
Collection<Matchable> syncMatchables = new ArrayList<>();
|
||||
// Assemble matchables async, then search synchronously.
|
||||
for (int i = 0; !isComplete(plugin) && i < plugin.getSearchPollsPerTick(); ++i) {
|
||||
++polls;
|
||||
// Calling #isComplete will advance to next InventoryProvider as necessary.
|
||||
// Bucket matchables for searching synchronously.
|
||||
syncMatchables.add(current.next());
|
||||
}
|
||||
|
||||
Future<Boolean> future = plugin.getServer().getScheduler().callSyncMethod(plugin, () -> {
|
||||
for (Matchable matchable : syncMatchables) {
|
||||
MatchResult match = matchable.match(matcher);
|
||||
if (match.isMatch()) {
|
||||
matches.addAll(Arrays.asList(match.getMatch()));
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
try {
|
||||
future.get();
|
||||
} catch (InterruptedException | ExecutionException e) {
|
||||
// Eat exception to prevent spam.
|
||||
}
|
||||
}
|
||||
|
||||
private void sendProgress(CommandSender sender, OpenInv plugin) {
|
||||
if (!(sender instanceof Player) || polls % (10 * plugin.getSearchPollsPerTick()) != 1) {
|
||||
return;
|
||||
}
|
||||
double progress = 100 * Math.min(polls, totalMatchables) / totalMatchables;
|
||||
DecimalFormat percent = new DecimalFormat("00.0");
|
||||
plugin.sendSystemMessage((Player) sender, "messages.info.search.progress",
|
||||
"%progress%", percent.format(progress),
|
||||
"%matches%", String.valueOf(matches.size()));
|
||||
}
|
||||
|
||||
private void sendResults(CommandSender sender, OpenInv plugin) {
|
||||
if (matches.isEmpty()) {
|
||||
String localizedMessage = plugin.getLocalizedMessage(sender, "messages.info.search.noMatches");
|
||||
if (localizedMessage == null) {
|
||||
localizedMessage = "No items found with search parameters.";
|
||||
}
|
||||
sender.sendMessage(localizedMessage);
|
||||
return;
|
||||
}
|
||||
|
||||
String prefix = plugin.getLocalizedMessage(sender, "messages.info.search.matches");
|
||||
if (prefix == null) {
|
||||
prefix = "Locations of items matching parameters:";
|
||||
}
|
||||
|
||||
if (sender instanceof Player) {
|
||||
TextComponent textComponent = new TextComponent(prefix);
|
||||
Iterator<MessagePart> iterator = matches.iterator();
|
||||
|
||||
int total = 0;
|
||||
int searchResultsMax = plugin.getSearchResultsMax();
|
||||
while (iterator.hasNext()) {
|
||||
textComponent.addExtra(iterator.next().forPlayer());
|
||||
|
||||
++total;
|
||||
if (total >= searchResultsMax) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (iterator.hasNext()) {
|
||||
textComponent.addExtra(SEPARATOR);
|
||||
}
|
||||
}
|
||||
|
||||
// Paper deprecated Spigot's message API.
|
||||
// This is a risky deprecation ignore - Spigot may eventually do the sane thing
|
||||
// and just add a method accepting components to the player directly.
|
||||
//noinspection deprecation
|
||||
sender.spigot().sendMessage(textComponent);
|
||||
return;
|
||||
}
|
||||
|
||||
String message = matches.stream()
|
||||
.limit(plugin.getSearchResultsMax())
|
||||
.map(MessagePart::forConsole)
|
||||
.collect(Collectors.joining(", ", prefix, ""));
|
||||
sender.sendMessage(message);
|
||||
}
|
||||
|
||||
public void schedule(CommandSender sender, OpenInv plugin) {
|
||||
new BukkitRunnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
// Scheduler struggles to cancel async tasks with high frequency.
|
||||
if (isCancelled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
poll(plugin);
|
||||
|
||||
if (isComplete(plugin)) {
|
||||
if (isCancelled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
sendResults(sender, plugin);
|
||||
cancel();
|
||||
|
||||
if (callback != null) {
|
||||
callback.run();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
sendProgress(sender, plugin);
|
||||
}
|
||||
}.runTaskTimerAsynchronously(plugin, 0L, 1L);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv.search.bucket;
|
||||
|
||||
import com.lishid.openinv.search.match.MatchResult;
|
||||
import com.lishid.openinv.search.match.Matchable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.function.BiConsumer;
|
||||
import org.bukkit.Chunk;
|
||||
import org.bukkit.World;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class ChunkBucket implements SearchBucket {
|
||||
|
||||
private final World world;
|
||||
private final boolean load;
|
||||
private final List<ChunkCoord> chunks;
|
||||
protected int index = -1;
|
||||
private Boolean paper = null;
|
||||
|
||||
public ChunkBucket(@NotNull World world, int chunkX, int chunkZ, int radius, boolean load) {
|
||||
this.world = world;
|
||||
this.load = load;
|
||||
this.chunks = new ArrayList<>();
|
||||
// Order chunks based (loosely) on proximity.
|
||||
spiralRectangle(radius, (deltaX, deltaZ) -> chunks.add(new ChunkCoord(chunkX + deltaX, chunkZ + deltaZ)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Matchable next() throws IndexOutOfBoundsException {
|
||||
ChunkCoord chunkCoord = chunks.get(++index);
|
||||
|
||||
if (!world.isChunkGenerated(chunkCoord.x(), chunkCoord.z())) {
|
||||
return Matchable.EMPTY;
|
||||
}
|
||||
|
||||
if (!load && !world.isChunkLoaded(chunkCoord.x(), chunkCoord.z())) {
|
||||
return Matchable.EMPTY;
|
||||
}
|
||||
|
||||
// If async chunk loading is not available, load chunk when checking.
|
||||
if (!isPaper()) {
|
||||
return new MatchableChunk(world, chunkCoord.x(), chunkCoord.z());
|
||||
}
|
||||
|
||||
CompletableFuture<Chunk> chunkAt = world.getChunkAtAsync(chunkCoord.x(), chunkCoord.z());
|
||||
|
||||
Chunk chunk;
|
||||
try {
|
||||
chunk = chunkAt.get();
|
||||
} catch (InterruptedException | ExecutionException e) {
|
||||
return matcher -> MatchResult.NO_MATCH;
|
||||
}
|
||||
|
||||
return new MatchableChunk(chunk);
|
||||
}
|
||||
|
||||
private boolean isPaper() {
|
||||
if (paper == null) {
|
||||
try {
|
||||
// Check for Paper.
|
||||
Class.forName("com.destroystokyo.paper.PaperConfig");
|
||||
paper = true;
|
||||
} catch (ClassNotFoundException e) {
|
||||
paper = false;
|
||||
}
|
||||
}
|
||||
|
||||
return paper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return index < chunks.size() - 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return chunks.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* Produce a series of integer coordinates starting at 0, 0 that extend outward to form a centered square,
|
||||
* producing closer proximity results sooner than a traditional double for loop from min to max.
|
||||
*
|
||||
* @param radius the radius of the square
|
||||
* @param coordConsumer the method consuming the values produced
|
||||
*/
|
||||
private static void spiralRectangle(int radius, BiConsumer<Integer, Integer> coordConsumer) {
|
||||
for (int x = 0; x <= radius; ++x) {
|
||||
for (int z = 0; z <= radius; ++z) {
|
||||
coordConsumer.accept(x, z);
|
||||
if (x != 0) {
|
||||
coordConsumer.accept(-x, z);
|
||||
if (z != 0) {
|
||||
coordConsumer.accept(-x, -z);
|
||||
}
|
||||
}
|
||||
if (z != 0) {
|
||||
coordConsumer.accept(x, -z);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv.search.bucket;
|
||||
|
||||
/**
|
||||
* A data holder for chunk coordinates.
|
||||
*/
|
||||
public record ChunkCoord(int x, int z) {}
|
||||
@@ -0,0 +1,128 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv.search.bucket;
|
||||
|
||||
import com.lishid.openinv.search.match.ItemMatcher;
|
||||
import com.lishid.openinv.search.match.MatchResult;
|
||||
import com.lishid.openinv.search.match.Matchable;
|
||||
import com.lishid.openinv.util.MessagePart;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import net.md_5.bungee.api.chat.BaseComponent;
|
||||
import net.md_5.bungee.api.chat.ClickEvent;
|
||||
import net.md_5.bungee.api.chat.HoverEvent;
|
||||
import net.md_5.bungee.api.chat.TextComponent;
|
||||
import net.md_5.bungee.api.chat.hover.content.Text;
|
||||
import org.bukkit.Chunk;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.block.BlockState;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.InventoryHolder;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
class MatchableChunk implements Matchable {
|
||||
|
||||
private Chunk chunk;
|
||||
private World world;
|
||||
private int chunkX;
|
||||
private int chunkZ;
|
||||
|
||||
MatchableChunk(@NotNull Chunk chunk) {
|
||||
this.chunk = chunk;
|
||||
}
|
||||
|
||||
MatchableChunk(@NotNull World world, int chunkX, int chunkZ) {
|
||||
this.world = world;
|
||||
this.chunkX = chunkX;
|
||||
this.chunkZ = chunkZ;
|
||||
}
|
||||
|
||||
private Chunk getChunk() {
|
||||
if (chunk == null) {
|
||||
chunk = world.getChunkAt(chunkX, chunkZ);
|
||||
}
|
||||
return chunk;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull MatchResult match(@NotNull ItemMatcher matcher) {
|
||||
List<BlockState> blocks = new ArrayList<>();
|
||||
|
||||
for (BlockState tileEntity : getChunk().getTileEntities()) {
|
||||
if (!(tileEntity instanceof InventoryHolder)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Inventory inventory = ((InventoryHolder) tileEntity).getInventory();
|
||||
|
||||
for (ItemStack content : inventory.getContents()) {
|
||||
if (matcher.matches(content)) {
|
||||
blocks.add(tileEntity);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (blocks.isEmpty()) {
|
||||
return MatchResult.NO_MATCH;
|
||||
}
|
||||
|
||||
MessagePart[] matches = new MessagePart[blocks.size()];
|
||||
for (int i = 0; i < matches.length; ++i) {
|
||||
BlockState state = blocks.get(i);
|
||||
matches[i] = new MessagePart(() -> getComponent(state), () -> getString(state));
|
||||
}
|
||||
|
||||
return new MatchResult(matches);
|
||||
}
|
||||
|
||||
private static BaseComponent getComponent(BlockState state) {
|
||||
TextComponent component = new TextComponent(state.getType().name());
|
||||
|
||||
String command = String.format(
|
||||
"/execute in %s minecraft:tp %s %s %s",
|
||||
state.getWorld().getName(),
|
||||
state.getX(),
|
||||
state.getY() + 1,
|
||||
state.getZ());
|
||||
component.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, command));
|
||||
|
||||
String hover = String.format(
|
||||
"%s{world:%s,x:%s,y:%s,z:%s}\n\nClick to teleport.",
|
||||
state.getType().getKey(),
|
||||
state.getWorld().getName(),
|
||||
state.getX(),
|
||||
state.getY(),
|
||||
state.getZ());
|
||||
Text hoverText = new Text(new BaseComponent[] { new TextComponent(hover)});
|
||||
component.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, hoverText));
|
||||
|
||||
return component;
|
||||
}
|
||||
|
||||
private static String getString(BlockState state) {
|
||||
return String.format(
|
||||
"%s{world:%s,x:%s,y:%s,z:%s}",
|
||||
state.getType().getKey(),
|
||||
state.getWorld().getName(),
|
||||
state.getX(),
|
||||
state.getY(),
|
||||
state.getZ());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv.search.bucket;
|
||||
|
||||
import com.lishid.openinv.OpenInv;
|
||||
import com.lishid.openinv.search.match.ItemMatcher;
|
||||
import com.lishid.openinv.search.match.MatchResult;
|
||||
import com.lishid.openinv.search.match.Matchable;
|
||||
import com.lishid.openinv.util.MessagePart;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Supplier;
|
||||
import net.md_5.bungee.api.chat.BaseComponent;
|
||||
import net.md_5.bungee.api.chat.ClickEvent;
|
||||
import net.md_5.bungee.api.chat.HoverEvent;
|
||||
import net.md_5.bungee.api.chat.TextComponent;
|
||||
import net.md_5.bungee.api.chat.hover.content.Text;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.inventory.InventoryType;
|
||||
import org.bukkit.inventory.InventoryView;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.PlayerInventory;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class MatchablePlayer implements Matchable {
|
||||
|
||||
private final OpenInv plugin;
|
||||
private final OfflinePlayer offlinePlayer;
|
||||
|
||||
public MatchablePlayer(OpenInv plugin, OfflinePlayer offlinePlayer) {
|
||||
this.plugin = plugin;
|
||||
this.offlinePlayer = offlinePlayer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull MatchResult match(@NotNull ItemMatcher matcher) {
|
||||
|
||||
Player player;
|
||||
if (offlinePlayer instanceof Player) {
|
||||
player = (Player) offlinePlayer;
|
||||
} else {
|
||||
player = plugin.loadPlayer(offlinePlayer);
|
||||
}
|
||||
|
||||
if (player == null) {
|
||||
return MatchResult.NO_MATCH;
|
||||
}
|
||||
|
||||
boolean matchInv = false;
|
||||
boolean matchEnder = false;
|
||||
|
||||
PlayerInventory playerInventory = player.getInventory();
|
||||
|
||||
// Check inventory. Modern implementations include armor and off hand in contents.
|
||||
for (ItemStack content : playerInventory.getContents()) {
|
||||
if (matcher.matches(content)) {
|
||||
matchInv = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
InventoryView openInventory = player.getOpenInventory();
|
||||
|
||||
// If no matches are found yet, check cursor.
|
||||
if (!matchInv && matcher.matches(openInventory.getCursor())) {
|
||||
matchInv = true;
|
||||
}
|
||||
|
||||
// Check player crafting inventory.
|
||||
if (!matchInv && openInventory.getType() == InventoryType.CRAFTING) {
|
||||
for (ItemStack content : openInventory.getTopInventory().getContents()) {
|
||||
if (matcher.matches(content)) {
|
||||
matchInv = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check ender chest.
|
||||
for (ItemStack content : player.getEnderChest().getContents()) {
|
||||
if (matcher.matches(content)) {
|
||||
matchEnder = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!matchInv && !matchEnder) {
|
||||
return MatchResult.NO_MATCH;
|
||||
}
|
||||
|
||||
String name = player.getName();
|
||||
UUID uuid = player.getUniqueId();
|
||||
|
||||
if (matchInv && matchEnder) {
|
||||
return new MatchResult(new MessagePart[] {
|
||||
new MessagePart(() -> getBoth(name, uuid), () -> name + " (inv, ender)")
|
||||
});
|
||||
}
|
||||
|
||||
Supplier<BaseComponent> componentSupplier;
|
||||
Supplier<String> stringSupplier;
|
||||
|
||||
if (matchInv) {
|
||||
componentSupplier = () -> getSingle(name, () -> getInvClick(uuid), () -> getInvHover(name));
|
||||
stringSupplier = () -> name + " (inv)";
|
||||
} else {
|
||||
componentSupplier = () -> getSingle(name, () -> getEnderClick(uuid), () -> getEnderHover(name));
|
||||
stringSupplier = () -> name + " (ender)";
|
||||
}
|
||||
|
||||
return new MatchResult(new MessagePart[] { new MessagePart(componentSupplier, stringSupplier) });
|
||||
}
|
||||
|
||||
private static BaseComponent getBoth(String name, UUID uuid) {
|
||||
BaseComponent component = new TextComponent(name + " (inv,");
|
||||
component.setClickEvent(getInvClick(uuid));
|
||||
component.setHoverEvent(getInvHover(name));
|
||||
|
||||
BaseComponent enderComponent = new TextComponent(" ender)");
|
||||
enderComponent.setClickEvent(getEnderClick(uuid));
|
||||
enderComponent.setHoverEvent(getEnderHover(name));
|
||||
|
||||
component.addExtra(enderComponent);
|
||||
return component;
|
||||
}
|
||||
|
||||
private static BaseComponent getSingle(String name, Supplier<ClickEvent> click, Supplier<HoverEvent> hover) {
|
||||
BaseComponent component = new TextComponent(name);
|
||||
component.setClickEvent(click.get());
|
||||
component.setHoverEvent(hover.get());
|
||||
return component;
|
||||
}
|
||||
|
||||
private static ClickEvent getInvClick(UUID uuid) {
|
||||
return getClick("/openinv:openinv ", uuid);
|
||||
}
|
||||
|
||||
private static HoverEvent getInvHover(String name) {
|
||||
return getHover("/openinv ", name);
|
||||
}
|
||||
|
||||
private static ClickEvent getEnderClick(UUID uuid) {
|
||||
return getClick("/openinv:openender ", uuid);
|
||||
}
|
||||
|
||||
private static HoverEvent getEnderHover(String name) {
|
||||
return getHover("/openender ", name);
|
||||
}
|
||||
|
||||
private static ClickEvent getClick(String command, UUID uuid) {
|
||||
// Actual command run is not exposed to user, so there's no reason not to use UUID and be precise.
|
||||
return new ClickEvent(ClickEvent.Action.RUN_COMMAND, command + uuid);
|
||||
}
|
||||
|
||||
private static HoverEvent getHover(String command, String name) {
|
||||
BaseComponent[] text = new BaseComponent[] { new TextComponent(command + name) };
|
||||
return new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(text));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv.search.bucket;
|
||||
|
||||
import com.lishid.openinv.OpenInv;
|
||||
import com.lishid.openinv.search.match.Matchable;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class PlayerBucket implements SearchBucket {
|
||||
|
||||
private final OpenInv plugin;
|
||||
private final OfflinePlayer[] players;
|
||||
private int index = -1;
|
||||
|
||||
public PlayerBucket(OpenInv plugin, boolean online) {
|
||||
this.plugin = plugin;
|
||||
if (online) {
|
||||
this.players = Bukkit.getOnlinePlayers().toArray(new Player[0]);
|
||||
} else {
|
||||
this.players = Bukkit.getOfflinePlayers();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return index < players.length - 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Matchable next() {
|
||||
return new MatchablePlayer(plugin, players[++index]);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv.search.bucket;
|
||||
|
||||
import com.lishid.openinv.search.match.Matchable;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public interface SearchBucket {
|
||||
|
||||
boolean hasNext();
|
||||
|
||||
@NotNull Matchable next() throws IndexOutOfBoundsException;
|
||||
|
||||
int size();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv.search.match;
|
||||
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.enchantments.Enchantment;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class ItemMatchables {
|
||||
|
||||
public static MatchableItem isType(@NotNull Material material) {
|
||||
return itemStack -> itemStack.getType() == material;
|
||||
}
|
||||
|
||||
public static MatchableItem hasAmount(int minAmount) {
|
||||
return itemStack -> itemStack.getAmount() >= minAmount;
|
||||
}
|
||||
|
||||
public static MatchableMeta hasEnchant(@Nullable Enchantment enchantment, @Nullable Integer minLevel) {
|
||||
return itemMeta -> {
|
||||
if (minLevel == null) {
|
||||
if (enchantment == null) {
|
||||
// Level and enchantment not specified, any enchantment of any level matches.
|
||||
return !itemMeta.getEnchants().isEmpty();
|
||||
}
|
||||
|
||||
// Level not specified, any level of enchantment matches.
|
||||
return itemMeta.hasEnchant(enchantment);
|
||||
}
|
||||
|
||||
if (enchantment != null) {
|
||||
// Level and enchantment are specified, enchantment must meet or exceed level.
|
||||
return itemMeta.getEnchantLevel(enchantment) >= minLevel;
|
||||
}
|
||||
|
||||
// Enchantment not specified, any enchantment that meets or exceeds level matches.
|
||||
for (int enchantLevel : itemMeta.getEnchants().values()) {
|
||||
if (enchantLevel >= minLevel) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
}
|
||||
|
||||
private ItemMatchables() {}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv.search.match;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* A collection of multiple filters used to match items.
|
||||
*/
|
||||
public class ItemMatcher {
|
||||
|
||||
private final Collection<MatchableItem> baseOptions;
|
||||
private final Collection<MatchableMeta> metaOptions;
|
||||
|
||||
public ItemMatcher(
|
||||
Collection<MatchableItem> baseOptions,
|
||||
Collection<MatchableMeta> metaOptions) {
|
||||
this.baseOptions = new HashSet<>(baseOptions);
|
||||
this.metaOptions = new HashSet<>(metaOptions);
|
||||
}
|
||||
|
||||
public boolean matches(@Nullable ItemStack other) {
|
||||
// Ensure item exists.
|
||||
if (other == null || other.getType() == Material.AIR) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Match options against base item.
|
||||
for (MatchableItem baseOption : baseOptions) {
|
||||
if (!baseOption.matches(other)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// If no meta options exist, item matches.
|
||||
if (metaOptions.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Require item meta for meta options.
|
||||
ItemMeta meta;
|
||||
if (!other.hasItemMeta() || (meta = other.getItemMeta()) == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Match meta-based options.
|
||||
for (MatchableMeta metaOption : metaOptions) {
|
||||
if (!metaOption.matches(meta)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return baseOptions.isEmpty() && metaOptions.isEmpty();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv.search.match;
|
||||
|
||||
import com.lishid.openinv.util.MessagePart;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class MatchResult {
|
||||
|
||||
public static final MatchResult NO_MATCH = new MatchResult();
|
||||
|
||||
private final MessagePart[] result;
|
||||
|
||||
private MatchResult() {
|
||||
result = null;
|
||||
}
|
||||
|
||||
public MatchResult(MessagePart @NotNull [] result) {
|
||||
this.result = result;
|
||||
}
|
||||
|
||||
public boolean isMatch() {
|
||||
return result != null;
|
||||
}
|
||||
|
||||
public MessagePart @Nullable [] getMatch() {
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv.search.match;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public interface Matchable {
|
||||
|
||||
Matchable EMPTY = matcher -> MatchResult.NO_MATCH;
|
||||
|
||||
@NotNull MatchResult match(@NotNull ItemMatcher matcher);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv.search.match;
|
||||
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public interface MatchableItem {
|
||||
|
||||
boolean matches(@NotNull ItemStack itemStack);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv.search.match;
|
||||
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public interface MatchableMeta {
|
||||
|
||||
boolean matches(@NotNull ItemMeta itemMeta);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv.util;
|
||||
|
||||
import com.google.common.collect.Multimap;
|
||||
import com.google.common.collect.TreeMultimap;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/**
|
||||
* A minimal thread-safe time-based cache implementation backed by a HashMap and TreeMultimap.
|
||||
*
|
||||
* @author Jikoo
|
||||
*/
|
||||
public class Cache<K, V> {
|
||||
|
||||
private final Map<K, V> internal;
|
||||
private final Multimap<Long, K> expiry;
|
||||
private final long retention;
|
||||
private final Predicate<V> inUseCheck;
|
||||
private final Consumer<V> postRemoval;
|
||||
|
||||
/**
|
||||
* Constructs a Cache with the specified retention duration, in use function, and post-removal function.
|
||||
*
|
||||
* @param retention duration after which keys are automatically invalidated if not in use
|
||||
* @param inUseCheck Predicate used to check if a key is considered in use
|
||||
* @param postRemoval Consumer used to perform any operations required when a key is invalidated
|
||||
*/
|
||||
public Cache(final long retention, final Predicate<V> inUseCheck, final Consumer<V> postRemoval) {
|
||||
this.internal = new HashMap<>();
|
||||
|
||||
this.expiry = TreeMultimap.create(Long::compareTo, (k1, k2) -> Objects.equals(k1, k2) ? 0 : 1);
|
||||
|
||||
this.retention = retention;
|
||||
this.inUseCheck = inUseCheck;
|
||||
this.postRemoval = postRemoval;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a key and value pair. Keys are unique. Using an existing key will cause the old value to
|
||||
* be overwritten and the expiration timer to be reset.
|
||||
*
|
||||
* @param key key with which the specified value is to be associated
|
||||
* @param value value to be associated with the specified key
|
||||
*/
|
||||
public void put(final K key, final V value) {
|
||||
// Invalidate key - runs lazy check and ensures value won't be cleaned up early
|
||||
this.invalidate(key);
|
||||
|
||||
synchronized (this.internal) {
|
||||
this.internal.put(key, value);
|
||||
this.expiry.put(System.currentTimeMillis() + this.retention, key);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value to which the specified key is mapped, or null if no value is mapped for the key.
|
||||
*
|
||||
* @param key the key whose associated value is to be returned
|
||||
* @return the value to which the specified key is mapped, or null if no value is mapped for the key
|
||||
*/
|
||||
public V get(final K key) {
|
||||
// Run lazy check to clean cache
|
||||
this.lazyCheck();
|
||||
|
||||
synchronized (this.internal) {
|
||||
return this.internal.get(key);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the specified key is mapped to a value.
|
||||
*
|
||||
* @param key key to check if a mapping exists for
|
||||
* @return true if a mapping exists for the specified key
|
||||
*/
|
||||
public boolean containsKey(final K key) {
|
||||
// Run lazy check to clean cache
|
||||
this.lazyCheck();
|
||||
|
||||
synchronized (this.internal) {
|
||||
return this.internal.containsKey(key);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Forcibly invalidates a key, even if it is considered to be in use.
|
||||
*
|
||||
* @param key key to invalidate
|
||||
*/
|
||||
public void invalidate(final K key) {
|
||||
// Run lazy check to clean cache
|
||||
this.lazyCheck();
|
||||
|
||||
synchronized (this.internal) {
|
||||
if (!this.internal.containsKey(key)) {
|
||||
// Value either not present or cleaned by lazy check. Either way, we're good
|
||||
return;
|
||||
}
|
||||
|
||||
// Remove stored object
|
||||
this.internal.remove(key);
|
||||
|
||||
// Remove expiration entry - prevents more work later, plus prevents issues with values invalidating early
|
||||
for (Iterator<Map.Entry<Long, K>> iterator = this.expiry.entries().iterator(); iterator.hasNext();) {
|
||||
if (key.equals(iterator.next().getValue())) {
|
||||
iterator.remove();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Forcibly invalidates all keys, even if they are considered to be in use.
|
||||
*/
|
||||
public void invalidateAll() {
|
||||
synchronized (this.internal) {
|
||||
for (V value : this.internal.values()) {
|
||||
this.postRemoval.accept(value);
|
||||
}
|
||||
this.expiry.clear();
|
||||
this.internal.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalidate all expired keys that are not considered in use. If a key is expired but is
|
||||
* considered in use by the provided Function, its expiration time is reset.
|
||||
*/
|
||||
private void lazyCheck() {
|
||||
long now = System.currentTimeMillis();
|
||||
synchronized (this.internal) {
|
||||
List<K> inUse = new ArrayList<>();
|
||||
for (Iterator<Map.Entry<Long, K>> iterator = this.expiry.entries().iterator(); iterator
|
||||
.hasNext();) {
|
||||
Map.Entry<Long, K> entry = iterator.next();
|
||||
|
||||
if (entry.getKey() > now) {
|
||||
break;
|
||||
}
|
||||
|
||||
iterator.remove();
|
||||
|
||||
if (this.inUseCheck.test(this.internal.get(entry.getValue()))) {
|
||||
inUse.add(entry.getValue());
|
||||
continue;
|
||||
}
|
||||
|
||||
V value = this.internal.remove(entry.getValue());
|
||||
|
||||
if (value == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
this.postRemoval.accept(value);
|
||||
}
|
||||
|
||||
long nextExpiry = now + this.retention;
|
||||
for (K value : inUse) {
|
||||
this.expiry.put(nextExpiry, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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
|
||||
@@ -25,7 +25,13 @@ import java.util.Set;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
|
||||
public record ConfigUpdater(OpenInv plugin) {
|
||||
public class ConfigUpdater {
|
||||
|
||||
private final OpenInv plugin;
|
||||
|
||||
public ConfigUpdater(OpenInv plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
public void checkForUpdates() {
|
||||
final int version = plugin.getConfig().getInt("config-version", 1);
|
||||
@@ -67,7 +73,8 @@ public record ConfigUpdater(OpenInv plugin) {
|
||||
|
||||
private void updateConfig4To5() {
|
||||
plugin.getServer().getScheduler().runTask(plugin, () -> {
|
||||
plugin.getConfig().set("settings.disable-offline-access", false);
|
||||
plugin.getConfig().set("settings.search.polls-per-tick", 5);
|
||||
plugin.getConfig().set("settings.search.max-results", 40);
|
||||
plugin.getConfig().set("config-version", 5);
|
||||
});
|
||||
}
|
||||
@@ -128,7 +135,7 @@ public record ConfigUpdater(OpenInv plugin) {
|
||||
for (String playerName : keys) {
|
||||
OfflinePlayer player = plugin.matchPlayer(playerName);
|
||||
if (player != null) {
|
||||
toggles.put(player.getUniqueId().toString(), section.getBoolean(playerName + ".toggle", false));
|
||||
toggles.put(plugin.getPlayerID(player), section.getBoolean(playerName + ".toggle", false));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+78
-54
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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
|
||||
@@ -14,28 +14,26 @@
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package com.lishid.openinv;
|
||||
package com.lishid.openinv.util;
|
||||
|
||||
import com.lishid.openinv.internal.IAnySilentContainer;
|
||||
import com.lishid.openinv.internal.IPlayerDataManager;
|
||||
import com.lishid.openinv.internal.ISpecialEnderChest;
|
||||
import com.lishid.openinv.internal.ISpecialInventory;
|
||||
import com.lishid.openinv.internal.ISpecialPlayerInventory;
|
||||
import com.lishid.openinv.util.InventoryAccess;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
class InternalAccessor {
|
||||
public class InternalAccessor {
|
||||
|
||||
private final @NotNull Plugin plugin;
|
||||
private final Plugin plugin;
|
||||
private final String version;
|
||||
private boolean supported = false;
|
||||
private IPlayerDataManager playerDataManager;
|
||||
private IAnySilentContainer anySilentContainer;
|
||||
|
||||
InternalAccessor(@NotNull Plugin plugin) {
|
||||
public InternalAccessor(final Plugin plugin) {
|
||||
this.plugin = plugin;
|
||||
|
||||
String packageName = plugin.getServer().getClass().getPackage().getName();
|
||||
@@ -51,30 +49,58 @@ class InternalAccessor {
|
||||
}
|
||||
|
||||
public String getReleasesLink() {
|
||||
|
||||
return switch (version) {
|
||||
case "1_4_5", "1_4_6", "v1_4_R1", "v1_5_R2", "v1_5_R3", "v1_6_R1", "v1_6_R2", "v1_6_R3",
|
||||
"v1_7_R1", "v1_7_R2", "v1_7_R3", "v1_7_R4", "v1_8_R1", "v1_8_R2",
|
||||
"v1_9_R1", "v1_9_R2", "v1_10_R1", "v1_11_R1", "v1_12_R1"
|
||||
-> "https://github.com/lishid/OpenInv/releases/tag/4.0.0 (OpenInv-legacy)";
|
||||
case "v1_13_R1" -> "https://github.com/lishid/OpenInv/releases/tag/4.0.0";
|
||||
case "v1_13_R2" -> "https://github.com/lishid/OpenInv/releases/tag/4.0.7";
|
||||
case "v1_14_R1" -> "https://github.com/lishid/OpenInv/releases/tag/4.1.1";
|
||||
case "v1_16_R1" -> "https://github.com/lishid/OpenInv/releases/tag/4.1.4";
|
||||
case "v1_8_R3", "v1_15_R1", "v1_16_R2" -> "https://github.com/lishid/OpenInv/releases/tag/4.1.5";
|
||||
case "v1_16_R3" -> "https://github.com/Jikoo/OpenInv/releases/tag/4.1.8";
|
||||
case "v1_17_R1", "v1_18_R1" -> "https://github.com/Jikoo/OpenInv/releases/tag/4.1.10";
|
||||
default -> "https://github.com/Jikoo/OpenInv/releases";
|
||||
};
|
||||
switch (version) {
|
||||
case "1_4_5":
|
||||
case "1_4_6":
|
||||
case "v1_4_R1":
|
||||
case "v1_5_R2":
|
||||
case "v1_5_R3":
|
||||
case "v1_6_R1":
|
||||
case "v1_6_R2":
|
||||
case "v1_6_R3":
|
||||
case "v1_7_R1":
|
||||
case "v1_7_R2":
|
||||
case "v1_7_R3":
|
||||
case "v1_7_R4":
|
||||
case "v1_8_R1":
|
||||
case "v1_8_R2":
|
||||
case "v1_9_R1":
|
||||
case "v1_9_R2":
|
||||
case "v1_10_R1":
|
||||
case "v1_11_R1":
|
||||
case "v1_12_R1":
|
||||
return "https://github.com/lishid/OpenInv/releases/tag/4.0.0 (OpenInv-legacy)";
|
||||
case "v1_13_R1":
|
||||
return "https://github.com/lishid/OpenInv/releases/tag/4.0.0";
|
||||
case "v1_13_R2":
|
||||
return "https://github.com/lishid/OpenInv/releases/tag/4.0.7";
|
||||
case "v1_14_R1":
|
||||
return "https://github.com/lishid/OpenInv/releases/tag/4.1.1";
|
||||
case "v1_16_R1":
|
||||
return "https://github.com/lishid/OpenInv/releases/tag/4.1.4";
|
||||
case "v1_8_R3":
|
||||
case "v1_15_R1":
|
||||
case "v1_16_R2":
|
||||
return "https://github.com/lishid/OpenInv/releases/tag/4.1.5";
|
||||
case "v1_16_R3":
|
||||
return "https://github.com/Jikoo/OpenInv/releases/tag/4.1.8";
|
||||
case "v1_17_R1":
|
||||
default:
|
||||
return "https://github.com/Jikoo/OpenInv/releases";
|
||||
}
|
||||
}
|
||||
|
||||
private @NotNull <T> T createObject(
|
||||
@NotNull Class<? extends T> assignableClass,
|
||||
@NotNull String className,
|
||||
@NotNull Object @NotNull ... params)
|
||||
throws ClassCastException, ReflectiveOperationException {
|
||||
private <T> T createObject(final Class<? extends T> assignableClass, final String className,
|
||||
final Object... params) throws ClassCastException, ClassNotFoundException,
|
||||
InstantiationException, IllegalAccessException, IllegalArgumentException,
|
||||
InvocationTargetException, NoSuchMethodException, SecurityException {
|
||||
// Fetch internal class if it exists.
|
||||
Class<?> internalClass = Class.forName("com.lishid.openinv.internal." + this.version + "." + className);
|
||||
if (!assignableClass.isAssignableFrom(internalClass)) {
|
||||
String message = String.format("Found class %s but cannot cast to %s!", internalClass.getName(), assignableClass.getName());
|
||||
this.plugin.getLogger().warning(message);
|
||||
throw new IllegalStateException(message);
|
||||
}
|
||||
|
||||
// Quick return: no parameters, no need to fiddle about finding the correct constructor.
|
||||
if (params.length == 0) {
|
||||
@@ -105,24 +131,7 @@ class InternalAccessor {
|
||||
String message = builder.append(']').toString();
|
||||
this.plugin.getLogger().warning(message);
|
||||
|
||||
throw new NoSuchMethodException(message);
|
||||
}
|
||||
|
||||
private @NotNull <T extends ISpecialInventory> T createSpecialInventory(
|
||||
@NotNull Class<? extends T> assignableClass,
|
||||
@NotNull String className,
|
||||
@NotNull Player player,
|
||||
boolean online) throws InstantiationException {
|
||||
if (!this.supported) {
|
||||
throw new IllegalStateException(String.format("Unsupported server version %s!", this.version));
|
||||
}
|
||||
try {
|
||||
return this.createObject(assignableClass, className, player, online);
|
||||
} catch (Exception original) {
|
||||
InstantiationException exception = new InstantiationException(String.format("Unable to create a new %s", className));
|
||||
exception.initCause(original.fillInStackTrace());
|
||||
throw exception;
|
||||
}
|
||||
throw new IllegalArgumentException(message);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -131,7 +140,7 @@ class InternalAccessor {
|
||||
* @return the IAnySilentContainer
|
||||
* @throws IllegalStateException if server version is unsupported
|
||||
*/
|
||||
public @NotNull IAnySilentContainer getAnySilentContainer() {
|
||||
public IAnySilentContainer getAnySilentContainer() {
|
||||
if (!this.supported) {
|
||||
throw new IllegalStateException(String.format("Unsupported server version %s!", this.version));
|
||||
}
|
||||
@@ -144,7 +153,7 @@ class InternalAccessor {
|
||||
* @return the IPlayerDataManager
|
||||
* @throws IllegalStateException if server version is unsupported
|
||||
*/
|
||||
public @NotNull IPlayerDataManager getPlayerDataManager() {
|
||||
public IPlayerDataManager getPlayerDataManager() {
|
||||
if (!this.supported) {
|
||||
throw new IllegalStateException(String.format("Unsupported server version %s!", this.version));
|
||||
}
|
||||
@@ -152,12 +161,13 @@ class InternalAccessor {
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the server implementation version.
|
||||
* Gets the server implementation version. If not initialized, returns the string "null"
|
||||
* instead.
|
||||
*
|
||||
* @return the version
|
||||
* @return the version, or "null"
|
||||
*/
|
||||
public @NotNull String getVersion() {
|
||||
return this.version;
|
||||
public String getVersion() {
|
||||
return this.version != null ? this.version : "null";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -179,7 +189,14 @@ class InternalAccessor {
|
||||
* @throws InstantiationException if the ISpecialEnderChest could not be instantiated
|
||||
*/
|
||||
public ISpecialEnderChest newSpecialEnderChest(final Player player, final boolean online) throws InstantiationException {
|
||||
return this.createSpecialInventory(ISpecialEnderChest.class, "SpecialEnderChest", player, online);
|
||||
if (!this.supported) {
|
||||
throw new IllegalStateException(String.format("Unsupported server version %s!", this.version));
|
||||
}
|
||||
try {
|
||||
return this.createObject(ISpecialEnderChest.class, "SpecialEnderChest", player, online);
|
||||
} catch (Exception e) {
|
||||
throw new InstantiationException(String.format("Unable to create a new ISpecialEnderChest: %s", e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -191,7 +208,14 @@ class InternalAccessor {
|
||||
* @throws InstantiationException if the ISpecialPlayerInventory could not be instantiated
|
||||
*/
|
||||
public ISpecialPlayerInventory newSpecialPlayerInventory(final Player player, final boolean online) throws InstantiationException {
|
||||
return this.createSpecialInventory(ISpecialPlayerInventory.class, "SpecialPlayerInventory", player, online);
|
||||
if (!this.supported) {
|
||||
throw new IllegalStateException(String.format("Unsupported server version %s!", this.version));
|
||||
}
|
||||
try {
|
||||
return this.createObject(ISpecialPlayerInventory.class, "SpecialPlayerInventory", player, online);
|
||||
} catch (Exception e) {
|
||||
throw new InstantiationException(String.format("Unable to create a new ISpecialPlayerInventory: %s", e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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
|
||||
@@ -39,130 +39,132 @@ import org.jetbrains.annotations.Nullable;
|
||||
*/
|
||||
public class LanguageManager {
|
||||
|
||||
private final OpenInv plugin;
|
||||
private final String defaultLocale;
|
||||
private final Map<String, YamlConfiguration> locales;
|
||||
private final OpenInv plugin;
|
||||
private final String defaultLocale;
|
||||
private final Map<String, YamlConfiguration> locales;
|
||||
|
||||
public LanguageManager(@NotNull OpenInv plugin, @NotNull String defaultLocale) {
|
||||
this.plugin = plugin;
|
||||
this.defaultLocale = defaultLocale;
|
||||
this.locales = new HashMap<>();
|
||||
getOrLoadLocale(defaultLocale);
|
||||
}
|
||||
public LanguageManager(@NotNull OpenInv plugin, @NotNull String defaultLocale) {
|
||||
this.plugin = plugin;
|
||||
this.defaultLocale = defaultLocale;
|
||||
this.locales = new HashMap<>();
|
||||
getOrLoadLocale(defaultLocale);
|
||||
}
|
||||
|
||||
private @NotNull YamlConfiguration getOrLoadLocale(@NotNull String locale) {
|
||||
YamlConfiguration loaded = locales.get(locale);
|
||||
if (loaded != null) {
|
||||
return loaded;
|
||||
}
|
||||
private YamlConfiguration getOrLoadLocale(@NotNull String locale) {
|
||||
YamlConfiguration loaded = locales.get(locale);
|
||||
if (loaded != null) {
|
||||
return loaded;
|
||||
}
|
||||
|
||||
InputStream resourceStream = plugin.getResource("locale/" + locale + ".yml");
|
||||
YamlConfiguration localeConfigDefaults;
|
||||
if (resourceStream == null) {
|
||||
localeConfigDefaults = new YamlConfiguration();
|
||||
} else {
|
||||
try (BufferedReader reader = new BufferedReader(new InputStreamReader(resourceStream))) {
|
||||
localeConfigDefaults = YamlConfiguration.loadConfiguration(reader);
|
||||
} catch (IOException e) {
|
||||
plugin.getLogger().log(Level.WARNING, "[LanguageManager] Unable to load resource " + locale + ".yml", e);
|
||||
localeConfigDefaults = new YamlConfiguration();
|
||||
}
|
||||
}
|
||||
InputStream resourceStream = plugin.getResource(locale + ".yml");
|
||||
YamlConfiguration localeConfigDefaults;
|
||||
if (resourceStream == null) {
|
||||
localeConfigDefaults = new YamlConfiguration();
|
||||
} else {
|
||||
try (BufferedReader reader = new BufferedReader(new InputStreamReader(resourceStream))) {
|
||||
localeConfigDefaults = YamlConfiguration.loadConfiguration(reader);
|
||||
} catch (IOException e) {
|
||||
plugin.getLogger().log(Level.WARNING, "[LanguageManager] Unable to load resource " + locale + ".yml", e);
|
||||
localeConfigDefaults = new YamlConfiguration();
|
||||
}
|
||||
}
|
||||
|
||||
File file = new File(plugin.getDataFolder(), locale + ".yml");
|
||||
YamlConfiguration localeConfig;
|
||||
File file = new File(plugin.getDataFolder(), locale + ".yml");
|
||||
YamlConfiguration localeConfig;
|
||||
|
||||
if (!file.exists()) {
|
||||
localeConfig = localeConfigDefaults;
|
||||
try {
|
||||
localeConfigDefaults.save(file);
|
||||
} catch (IOException e) {
|
||||
plugin.getLogger().log(Level.WARNING, "[LanguageManager] Unable to save resource " + locale + ".yml", e);
|
||||
}
|
||||
} else {
|
||||
localeConfig = YamlConfiguration.loadConfiguration(file);
|
||||
if (!file.exists()) {
|
||||
localeConfig = localeConfigDefaults;
|
||||
try {
|
||||
localeConfigDefaults.save(file);
|
||||
} catch (IOException e) {
|
||||
plugin.getLogger().log(Level.WARNING, "[LanguageManager] Unable to save resource " + locale + ".yml", e);
|
||||
}
|
||||
} else {
|
||||
localeConfig = YamlConfiguration.loadConfiguration(file);
|
||||
|
||||
// Add new language keys
|
||||
List<String> newKeys = new ArrayList<>();
|
||||
for (String key : localeConfigDefaults.getKeys(true)) {
|
||||
if (localeConfigDefaults.isConfigurationSection(key)) {
|
||||
continue;
|
||||
}
|
||||
// Add new language keys
|
||||
List<String> newKeys = new ArrayList<>();
|
||||
for (String key : localeConfigDefaults.getKeys(true)) {
|
||||
if (localeConfigDefaults.isConfigurationSection(key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (localeConfig.isSet(key)) {
|
||||
continue;
|
||||
}
|
||||
if (localeConfig.isSet(key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
localeConfig.set(key, localeConfigDefaults.get(key));
|
||||
newKeys.add(key);
|
||||
}
|
||||
localeConfig.set(key, localeConfigDefaults.get(key));
|
||||
newKeys.add(key);
|
||||
}
|
||||
|
||||
if (!newKeys.isEmpty()) {
|
||||
plugin.getLogger().info("[LanguageManager] Added new language keys: " + String.join(", ", newKeys));
|
||||
try {
|
||||
localeConfig.save(file);
|
||||
} catch (IOException e) {
|
||||
plugin.getLogger().log(Level.WARNING, "[LanguageManager] Unable to save resource " + locale + ".yml", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!newKeys.isEmpty()) {
|
||||
plugin.getLogger().info("[LanguageManager] Added new language keys: " + String.join(", ", newKeys));
|
||||
try {
|
||||
localeConfig.save(file);
|
||||
} catch (IOException e) {
|
||||
plugin.getLogger().log(Level.WARNING, "[LanguageManager] Unable to save resource " + locale + ".yml", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!locale.equals(defaultLocale)) {
|
||||
localeConfigDefaults = locales.get(defaultLocale);
|
||||
if (!locale.equals(defaultLocale)) {
|
||||
localeConfigDefaults = locales.get(defaultLocale);
|
||||
|
||||
// Check for missing keys
|
||||
List<String> newKeys = new ArrayList<>();
|
||||
for (String key : localeConfigDefaults.getKeys(true)) {
|
||||
if (localeConfigDefaults.isConfigurationSection(key)) {
|
||||
continue;
|
||||
}
|
||||
// Check for missing keys
|
||||
List<String> newKeys = new ArrayList<>();
|
||||
for (String key : localeConfigDefaults.getKeys(true)) {
|
||||
if (localeConfigDefaults.isConfigurationSection(key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (localeConfig.isSet(key)) {
|
||||
continue;
|
||||
}
|
||||
if (localeConfig.isSet(key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
newKeys.add(key);
|
||||
}
|
||||
newKeys.add(key);
|
||||
}
|
||||
|
||||
if (!newKeys.isEmpty()) {
|
||||
plugin.getLogger().info("[LanguageManager] Missing translations from " + locale + ".yml: " + String.join(", ", newKeys));
|
||||
}
|
||||
if (!newKeys.isEmpty()) {
|
||||
plugin.getLogger().info("[LanguageManager] Missing translations from " + locale + ".yml: " + String.join(", ", newKeys));
|
||||
}
|
||||
|
||||
// Fall through to default locale
|
||||
localeConfig.setDefaults(localeConfigDefaults);
|
||||
}
|
||||
// Fall through to default locale
|
||||
localeConfig.setDefaults(localeConfigDefaults);
|
||||
}
|
||||
|
||||
locales.put(locale, localeConfig);
|
||||
return localeConfig;
|
||||
}
|
||||
locales.put(locale, localeConfig);
|
||||
return localeConfig;
|
||||
}
|
||||
|
||||
public @Nullable String getValue(@NotNull String key, @Nullable String locale) {
|
||||
String value = getOrLoadLocale(locale == null ? defaultLocale : locale.toLowerCase()).getString(key);
|
||||
if (value == null || value.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
@Nullable
|
||||
public String getValue(@NotNull String key, @Nullable String locale) {
|
||||
String value = getOrLoadLocale(locale == null ? defaultLocale : locale.toLowerCase()).getString(key);
|
||||
if (value == null || value.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
value = ChatColor.translateAlternateColorCodes('&', value);
|
||||
value = ChatColor.translateAlternateColorCodes('&', value);
|
||||
|
||||
return value;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
public @Nullable String getValue(@NotNull String key, @Nullable String locale, String @NotNull ... replacements) {
|
||||
if (replacements.length % 2 != 0) {
|
||||
plugin.getLogger().log(Level.WARNING, "[LanguageManager] Replacement data is uneven", new Exception());
|
||||
}
|
||||
@Nullable
|
||||
public String getValue(@NotNull String key, @Nullable String locale, @NotNull String... replacements) {
|
||||
if (replacements.length % 2 != 0) {
|
||||
plugin.getLogger().log(Level.WARNING, "[LanguageManager] Replacement data is uneven", new Exception());
|
||||
}
|
||||
|
||||
String value = getValue(key, locale);
|
||||
String value = getValue(key, locale);
|
||||
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (int i = 0; i < replacements.length; i += 2) {
|
||||
value = value.replace(replacements[i], replacements[i + 1]);
|
||||
}
|
||||
for (int i = 0; i < replacements.length; i += 2) {
|
||||
value = value.replace(replacements[i], replacements[i + 1]);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv.util;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Supplier;
|
||||
import net.md_5.bungee.api.chat.BaseComponent;
|
||||
import net.md_5.bungee.api.chat.ClickEvent;
|
||||
import net.md_5.bungee.api.chat.TextComponent;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class MessagePart {
|
||||
|
||||
private final Supplier<BaseComponent> playerProvider;
|
||||
private final Supplier<String> consoleProvider;
|
||||
private @Nullable BaseComponent playerComponent;
|
||||
private @Nullable String consoleComponent;
|
||||
|
||||
public MessagePart(@NotNull Supplier<@NotNull BaseComponent> playerProvider) {
|
||||
this(playerProvider, () -> unwrapComponent(playerProvider.get()));
|
||||
}
|
||||
|
||||
public MessagePart(
|
||||
@NotNull Supplier<@NotNull BaseComponent> playerProvider,
|
||||
@NotNull Supplier<@NotNull String> consoleProvider) {
|
||||
this.playerProvider = playerProvider;
|
||||
this.consoleProvider = consoleProvider;
|
||||
}
|
||||
|
||||
public BaseComponent forPlayer() {
|
||||
if (this.playerComponent == null) {
|
||||
this.playerComponent = playerProvider.get();
|
||||
}
|
||||
return this.playerComponent;
|
||||
}
|
||||
|
||||
public String forConsole() {
|
||||
if (consoleComponent == null) {
|
||||
consoleComponent = consoleProvider.get();
|
||||
}
|
||||
return consoleComponent;
|
||||
}
|
||||
|
||||
private static String unwrapComponent(BaseComponent component) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
ClickEvent clickEvent = component.getClickEvent();
|
||||
|
||||
if (clickEvent != null) {
|
||||
// Prefer click events, i.e. "Check out our GitHub" with a link -> raw link
|
||||
builder.append(clickEvent.getValue());
|
||||
} else if (component instanceof TextComponent) {
|
||||
builder.append(((TextComponent) component).getText());
|
||||
}
|
||||
|
||||
List<BaseComponent> extra = component.getExtra();
|
||||
if (extra != null) {
|
||||
for (BaseComponent extraComponent : extra) {
|
||||
builder.append(unwrapComponent(extraComponent));
|
||||
}
|
||||
}
|
||||
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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 com.lishid.openinv.util;
|
||||
|
||||
import org.bukkit.permissions.Permissible;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public enum Permissions {
|
||||
|
||||
@@ -32,6 +31,10 @@ public enum Permissions {
|
||||
ENDERCHEST("openender"),
|
||||
ENDERCHEST_ALL("openenderall"),
|
||||
SEARCH("search"),
|
||||
SEARCH_PLAYERS_ONLINE("search.players.online"),
|
||||
SEARCH_PLAYERS_OFFLINE("search.players.offline"),
|
||||
SEARCH_CHUNKS_LOADED("search.chunks.loaded"),
|
||||
SEARCH_CHUNKS_UNLOADED("search.chunks.unloaded"),
|
||||
EDITINV("editinv"),
|
||||
EDITENDER("editender"),
|
||||
OPENSELF("openself"),
|
||||
@@ -51,7 +54,7 @@ public enum Permissions {
|
||||
this.uninheritable = uninheritable;
|
||||
}
|
||||
|
||||
public boolean hasPermission(@NotNull Permissible permissible) {
|
||||
public boolean hasPermission(Permissible permissible) {
|
||||
|
||||
boolean hasPermission = permissible.hasPermission(permission);
|
||||
if (uninheritable || hasPermission || permissible.isPermissionSet(permission)) {
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
/*
|
||||
* Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
*
|
||||
* 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, version 3.
|
||||
*
|
||||
* 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 com.lishid.openinv.util;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* A data container for JSON-esque expressions.
|
||||
*
|
||||
* <p>Ex: A ChunkBucket can be expressed <code>chunks{world:world_name,x:0,z:0,radius:10,load:true}</code>. The
|
||||
* starting "chunks" identifies it as a ChunkBucket and the content in braces contains the construction detail.
|
||||
* However, a simpler detail, such as a MatchableItem, may be specified <code>type:IRON_SWORD</code> where "type"
|
||||
* is both the identifier of the MatchableItem and the key of the sole value.
|
||||
*
|
||||
* <p>A best-effort will be made to match other start and finish demarcation techniques.
|
||||
*/
|
||||
public class PseudoJson {
|
||||
|
||||
private static final char[] BRACE_OPEN = new char[] { '{', '[', '(' };
|
||||
private static final char[] BRACE_CLOSE = new char[] { '}', ']', ')' };
|
||||
private static final Set<Character> RESERVED_CHARACTERS = new HashSet<>();
|
||||
|
||||
static {
|
||||
for (char brace : BRACE_OPEN) {
|
||||
RESERVED_CHARACTERS.add(brace);
|
||||
}
|
||||
for (char brace : BRACE_CLOSE) {
|
||||
RESERVED_CHARACTERS.add(brace);
|
||||
}
|
||||
RESERVED_CHARACTERS.add(',');
|
||||
RESERVED_CHARACTERS.add(':');
|
||||
}
|
||||
|
||||
private final String identifier;
|
||||
private final Map<String, String> mappings;
|
||||
|
||||
public PseudoJson(@NotNull String identifier) {
|
||||
this(identifier, new HashMap<>());
|
||||
}
|
||||
|
||||
public PseudoJson(@NotNull String identifier, @NotNull Map<String, String> mappings) {
|
||||
this.identifier = identifier;
|
||||
mappings.forEach(PseudoJson::validate);
|
||||
this.mappings = mappings;
|
||||
}
|
||||
|
||||
public @NotNull String getIdentifier() {
|
||||
return identifier;
|
||||
}
|
||||
|
||||
public @NotNull Optional<String> put(@NotNull String key, @NotNull String value) {
|
||||
validate(key, value);
|
||||
|
||||
return Optional.ofNullable(this.mappings.put(key, value));
|
||||
}
|
||||
|
||||
public @NotNull Optional<String> get(@NotNull String key) {
|
||||
return Optional.ofNullable(this.mappings.get(key));
|
||||
}
|
||||
|
||||
public @NotNull Map<String, String> getMappings() {
|
||||
return Collections.unmodifiableMap(mappings);
|
||||
}
|
||||
|
||||
public Optional<String> remove(@NotNull String key) {
|
||||
return Optional.ofNullable(this.mappings.get(key));
|
||||
}
|
||||
|
||||
public String asString() {
|
||||
StringBuilder builder = new StringBuilder(identifier);
|
||||
|
||||
builder.append('{');
|
||||
|
||||
for (Iterator<Map.Entry<String, String>> iterator = mappings.entrySet().iterator(); iterator.hasNext();) {
|
||||
Map.Entry<String, String> entry = iterator.next();
|
||||
builder.append(entry.getKey()).append(':').append(entry.getValue());
|
||||
if (iterator.hasNext()) {
|
||||
builder.append(',');
|
||||
}
|
||||
}
|
||||
|
||||
builder.append('}');
|
||||
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return asString();
|
||||
}
|
||||
|
||||
private static void validate(String key, String value) {
|
||||
if (RESERVED_CHARACTERS.stream().anyMatch(character -> key.indexOf(character) >= 0 || value.indexOf(character) >= 0)) {
|
||||
throw new IllegalArgumentException(String.format("Primitive pseudo-JSON reserves characters %s", RESERVED_CHARACTERS));
|
||||
}
|
||||
}
|
||||
|
||||
public static PseudoJson fromString(String pseudoJson) {
|
||||
int open = -1;
|
||||
for (char brace : BRACE_OPEN) {
|
||||
open = pseudoJson.indexOf(brace);
|
||||
if (open >= 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
String identifier = getIdentifier(pseudoJson, open);
|
||||
|
||||
int close = -1;
|
||||
for (char brace : BRACE_CLOSE) {
|
||||
close = pseudoJson.lastIndexOf(brace);
|
||||
if (close >= 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (open >= 0) {
|
||||
if (close <= open) {
|
||||
// Ignore bad ending brace.
|
||||
pseudoJson = pseudoJson.substring(open + 1);
|
||||
} else {
|
||||
// Use only bracketed content
|
||||
pseudoJson = pseudoJson.substring(open + 1, close);
|
||||
}
|
||||
}
|
||||
|
||||
return new PseudoJson(identifier, getMappings(pseudoJson));
|
||||
}
|
||||
|
||||
private static String getIdentifier(String pseudoJson, int braceOpen) {
|
||||
int identifierEnd;
|
||||
if (braceOpen >= 0) {
|
||||
identifierEnd = braceOpen;
|
||||
} else {
|
||||
// No quote, use first mapping.
|
||||
identifierEnd = pseudoJson.indexOf(':');
|
||||
if (identifierEnd == -1) {
|
||||
// No mappings, use whole string.
|
||||
return pseudoJson;
|
||||
}
|
||||
}
|
||||
|
||||
return pseudoJson.substring(0, identifierEnd);
|
||||
}
|
||||
|
||||
private static Map<String, String> getMappings(String pseudoJson) {
|
||||
String[] mappings = pseudoJson.split(",");
|
||||
|
||||
Map<String, String> data = new HashMap<>();
|
||||
for (String mapping : mappings) {
|
||||
String[] datum = mapping.split(":");
|
||||
if (datum.length >= 2) {
|
||||
data.put(datum[0], datum[1]);
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -22,9 +22,12 @@ import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.function.Function;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Keyed;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.util.StringUtil;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* Utility class for common tab completions.
|
||||
@@ -37,7 +40,7 @@ public class TabCompleter {
|
||||
* @param argument the argument to complete
|
||||
* @return integer options
|
||||
*/
|
||||
public static List<String> completeInteger(String argument) {
|
||||
public static List<String> completeInteger(@NotNull String argument) {
|
||||
// Ensure existing argument is actually a number
|
||||
if (!argument.isEmpty()) {
|
||||
try {
|
||||
@@ -62,14 +65,46 @@ public class TabCompleter {
|
||||
* @param enumClazz the Enum to complete for
|
||||
* @return the matching Enum values
|
||||
*/
|
||||
public static List<String> completeEnum(String argument, Class<? extends Enum<?>> enumClazz) {
|
||||
public static List<String> completeEnum(@NotNull String argument, @NotNull Class<? extends Enum<?>> enumClazz) {
|
||||
return completeObject(argument, Enum::name, enumClazz.getEnumConstants());
|
||||
}
|
||||
|
||||
/**
|
||||
* Offer tab completions for {@link Material Materials}.
|
||||
*
|
||||
* @param argument the argument to complete
|
||||
* @return the matching {@code Material} keys
|
||||
*/
|
||||
public static List<String> completeMaterial(@NotNull String argument) {
|
||||
argument = argument.toLowerCase(Locale.ENGLISH);
|
||||
List<String> completions = new ArrayList<>();
|
||||
|
||||
for (Enum<?> enumConstant : enumClazz.getEnumConstants()) {
|
||||
String name = enumConstant.name().toLowerCase();
|
||||
if (name.startsWith(argument)) {
|
||||
completions.add(name);
|
||||
for (Material material : Material.values()) {
|
||||
if (material.name().toLowerCase(Locale.ENGLISH).startsWith(argument)
|
||||
|| material.getKey().toString().startsWith(argument)
|
||||
|| material.getKey().getKey().startsWith(argument)) {
|
||||
completions.add(material.getKey().toString());
|
||||
}
|
||||
}
|
||||
|
||||
return completions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Offer tab completions for {@link Keyed} values.
|
||||
*
|
||||
* @param argument the argument to complete
|
||||
* @param options the {@code Keyed} values
|
||||
* @return the matching keys
|
||||
*/
|
||||
public static List<String> completeKeyed(@NotNull String argument, @NotNull Keyed @NotNull [] options) {
|
||||
argument = argument.toLowerCase(Locale.ENGLISH);
|
||||
List<String> completions = new ArrayList<>();
|
||||
|
||||
for (Keyed keyed : options) {
|
||||
if (keyed.getKey().toString().startsWith(argument)
|
||||
|| keyed.getKey().getKey().startsWith(argument)) {
|
||||
completions.add(keyed.getKey().toString());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,7 +118,7 @@ public class TabCompleter {
|
||||
* @param options the Strings which may be completed
|
||||
* @return the matching Strings
|
||||
*/
|
||||
public static List<String> completeString(String argument, String[] options) {
|
||||
public static List<String> completeString(@NotNull String argument, @NotNull String @NotNull [] options) {
|
||||
argument = argument.toLowerCase(Locale.ENGLISH);
|
||||
List<String> completions = new ArrayList<>();
|
||||
|
||||
@@ -103,7 +138,7 @@ public class TabCompleter {
|
||||
* @param argument the argument to complete
|
||||
* @return the matching Players' names
|
||||
*/
|
||||
public static List<String> completeOnlinePlayer(CommandSender sender, String argument) {
|
||||
public static List<String> completeOnlinePlayer(@NotNull CommandSender sender, String argument) {
|
||||
List<String> completions = new ArrayList<>();
|
||||
Player senderPlayer = sender instanceof Player ? (Player) sender : null;
|
||||
|
||||
@@ -128,12 +163,12 @@ public class TabCompleter {
|
||||
* @param options the Objects which may be completed
|
||||
* @return the matching Strings
|
||||
*/
|
||||
public static <T> List<String> completeObject(String argument, Function<T, String> converter, T[] options) {
|
||||
public static <T> List<String> completeObject(@NotNull String argument, @NotNull Function<T, String> converter, @NotNull T @NotNull [] options) {
|
||||
argument = argument.toLowerCase(Locale.ENGLISH);
|
||||
List<String> completions = new ArrayList<>();
|
||||
|
||||
for (T option : options) {
|
||||
String optionString = converter.apply(option).toLowerCase();
|
||||
String optionString = converter.apply(option).toLowerCase(Locale.ENGLISH);
|
||||
if (optionString.startsWith(argument)) {
|
||||
completions.add(optionString);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
config-version: 5
|
||||
settings:
|
||||
disable-offline-access: false
|
||||
search:
|
||||
polls-per-tick: 5
|
||||
max-results: 40
|
||||
disable-saving: false
|
||||
locale: 'en_us'
|
||||
File renamed without changes.
@@ -2,6 +2,11 @@ messages:
|
||||
error:
|
||||
consoleUnsupported: 'You cannot use this command from console.'
|
||||
lootNotGenerated: '&cLoot not generated! Please disable &b/silentcontainer&c.'
|
||||
search:
|
||||
invalidSchema: '&cUnable to parse "%value%" to determine target. Try using tab completion!'
|
||||
invalidInventory: '&cUnable to determine target inventories. Try using tab completion!'
|
||||
invalidMatcher: '&cUnable to determine target item parameters. Try using tab completion!'
|
||||
activeSearch: '&cPlease wait for your search to complete before starting another.'
|
||||
invalidMaterial: '&cInvalid material: "%target%"'
|
||||
invalidNumber: '&cInvalid number: "%target%"'
|
||||
invalidPlayer: '&cPlayer not found!'
|
||||
@@ -17,12 +22,10 @@ messages:
|
||||
containerBlockedSilent: 'You are opening a blocked container silently.'
|
||||
containerSilent: 'You are opening a container silently.'
|
||||
settingState: '%setting%: %state%'
|
||||
player:
|
||||
noMatches: 'No players found with %target%.'
|
||||
matches: 'Players holding %target%: %detail%'
|
||||
container:
|
||||
noMatches: 'No containers found with %target%.'
|
||||
matches: 'Containers holding %target%: %detail%'
|
||||
search:
|
||||
progress: 'Searching... %progress%% | Results: %matches%'
|
||||
noMatches: 'No items found with search parameters.'
|
||||
matches: 'Locations of items matching parameters: '
|
||||
on: 'on'
|
||||
off: 'off'
|
||||
container:
|
||||
File renamed without changes.
@@ -52,12 +52,12 @@ commands:
|
||||
permission: OpenInv.openender
|
||||
usage: |-
|
||||
/<command> [Player] - Open a player's enderchest
|
||||
searchinv:
|
||||
aliases: [si]
|
||||
description: Search and list players having a specific item
|
||||
search:
|
||||
aliases: [ searchinv, si, searchender, se, searchenchant, searchenchants, searchcontainer, searchchest ]
|
||||
description: Search inventories for a matching item
|
||||
permission: OpenInv.search
|
||||
usage: |-
|
||||
/<command> <Material> [MinAmount] - MinAmount is optional, the minimum amount required
|
||||
/<command> <inventories> <item details>
|
||||
searchender:
|
||||
aliases: [se]
|
||||
permission: OpenInv.search
|
||||
@@ -76,14 +76,3 @@ commands:
|
||||
permission: OpenInv.anychest
|
||||
usage: |-
|
||||
/<command> [check|on|off] - Check, toggle, or set AnyContainer
|
||||
searchenchant:
|
||||
aliases: [searchenchants]
|
||||
description: Search and list players with a specific enchantment.
|
||||
permission: OpenInv.searchenchant
|
||||
usage: |-
|
||||
/<command> <[Enchantment] [MinLevel]> - Enchantment is the enchantment type, MinLevel is the minimum level. One is optional
|
||||
searchcontainer:
|
||||
aliases: [searchchest]
|
||||
description: Search and list containers with a specific material.
|
||||
permission: OpenInv.searchcontainer
|
||||
usage: /<command> <Material> [ChunkRadius] - ChunkRadius is optional, the length that will be searched for matching items. Default 5
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -1,5 +1,5 @@
|
||||
<!--
|
||||
~ Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
~ Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
~
|
||||
~ 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
|
||||
@@ -21,16 +21,14 @@
|
||||
<artifactId>openinvparent</artifactId>
|
||||
<name>OpenInv</name>
|
||||
<url>http://dev.bukkit.org/bukkit-plugins/openinv/</url>
|
||||
<version>4.2.0</version>
|
||||
<version>4.1.9-SNAPSHOT</version>
|
||||
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.source>17</maven.compiler.source>
|
||||
<maven.compiler.target>17</maven.compiler.target>
|
||||
<!-- Silence IDE warning - property is declared in individual internal modules. -->
|
||||
<spigot.version>unknown</spigot.version>
|
||||
<maven.compiler.source>16</maven.compiler.source>
|
||||
<maven.compiler.target>16</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
<profiles>
|
||||
@@ -39,8 +37,8 @@
|
||||
<modules>
|
||||
<module>api</module>
|
||||
<module>plugin</module>
|
||||
<module>internal/v1_18_R2</module>
|
||||
<module>internal/v1_19_R1</module>
|
||||
<module>internal/v1_17_R1</module>
|
||||
<module>internal/v1_18_R1</module>
|
||||
<module>assembly</module>
|
||||
</modules>
|
||||
</profile>
|
||||
@@ -63,6 +61,14 @@
|
||||
<id>spigot-repo</id>
|
||||
<url>https://hub.spigotmc.org/nexus/content/groups/public/</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>papermc</id>
|
||||
<url>https://papermc.io/repo/repository/maven-public/</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>jitpack</id>
|
||||
<url>https://jitpack.io</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<dependencyManagement>
|
||||
@@ -73,33 +79,46 @@
|
||||
<scope>provided</scope>
|
||||
<version>23.0.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<artifactId>paper-api</artifactId>
|
||||
<groupId>io.papermc.paper</groupId>
|
||||
<scope>provided</scope>
|
||||
<version>1.17.1-R0.1-SNAPSHOT</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<artifactId>spigot-api</artifactId>
|
||||
<groupId>org.spigotmc</groupId>
|
||||
<scope>provided</scope>
|
||||
<version>1.17.1-R0.1-SNAPSHOT</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<artifactId>planarwrappers</artifactId>
|
||||
<groupId>com.github.jikoo</groupId>
|
||||
<scope>compile</scope>
|
||||
<version>2.2.4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<artifactId>openinvapi</artifactId>
|
||||
<groupId>com.lishid</groupId>
|
||||
<scope>compile</scope>
|
||||
<version>4.2.0</version>
|
||||
<version>4.1.9-SNAPSHOT</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<artifactId>openinvplugincore</artifactId>
|
||||
<groupId>com.lishid</groupId>
|
||||
<scope>compile</scope>
|
||||
<version>4.2.0</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>com.lishid</groupId>
|
||||
<artifactId>openinvapi</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
<version>4.1.9-SNAPSHOT</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<pluginRepositories>
|
||||
<pluginRepository>
|
||||
<id>apache-snapshot-repo</id>
|
||||
<url>https://repository.apache.org/content/repositories/snapshots/</url>
|
||||
</pluginRepository>
|
||||
</pluginRepositories>
|
||||
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
@@ -133,7 +152,7 @@
|
||||
</execution>
|
||||
</executions>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<version>3.3.0</version>
|
||||
<version>3.3.1-SNAPSHOT</version>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
@@ -151,35 +170,7 @@
|
||||
<plugin>
|
||||
<groupId>net.md-5</groupId>
|
||||
<artifactId>specialsource-maven-plugin</artifactId>
|
||||
<version>1.2.4</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>remap</goal>
|
||||
</goals>
|
||||
<id>remap-obf</id>
|
||||
<configuration>
|
||||
<srgIn>org.spigotmc:minecraft-server:${spigot.version}:txt:maps-mojang</srgIn>
|
||||
<reverse>true</reverse>
|
||||
<remappedDependencies>org.spigotmc:spigot:${spigot.version}:jar:remapped-mojang</remappedDependencies>
|
||||
<remappedArtifactAttached>true</remappedArtifactAttached>
|
||||
<remappedClassifierName>remapped-obf</remappedClassifierName>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>remap</goal>
|
||||
</goals>
|
||||
<id>remap-spigot</id>
|
||||
<configuration>
|
||||
<inputFile>${project.build.directory}/${project.artifactId}-${project.version}-remapped-obf.jar</inputFile>
|
||||
<srgIn>org.spigotmc:minecraft-server:${spigot.version}:csrg:maps-spigot</srgIn>
|
||||
<remappedDependencies>org.spigotmc:spigot:${spigot.version}:jar:remapped-obf</remappedDependencies>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
<version>1.2.2</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Copyright (C) 2011-2022 lishid. All rights reserved.
|
||||
# Copyright (C) 2011-2021 lishid. All rights reserved.
|
||||
#
|
||||
# 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
|
||||
@@ -42,10 +42,22 @@ readarray -t modules <<< "$(mvn help:evaluate -Dexpression=project.modules -q -D
|
||||
declare -n versions="spigot_versions"
|
||||
|
||||
for module in "${modules[@]}"; do
|
||||
# Get Spigot version.
|
||||
spigot_version=$(mvn help:evaluate -Dexpression=spigot.version -q -DforceStdout -P all -pl "$module")
|
||||
versions+=("$spigot_version")
|
||||
echo "$spigot_version"
|
||||
# Get number of dependencies declared in pom of specified internal module.
|
||||
max_index=$(mvn help:evaluate -Dexpression=project.dependencies -q -DforceStdout -P all -pl "$module" | grep -c "<dependency>")
|
||||
|
||||
for ((i=0; i < max_index; i++)); do
|
||||
# Get artifactId of dependency.
|
||||
artifact_id=$(mvn help:evaluate -Dexpression=project.dependencies["$i"].artifactId -q -DforceStdout -P all -pl "$module")
|
||||
|
||||
# Ensure dependency is Spigot.
|
||||
if [[ "$artifact_id" == spigot ]]; then
|
||||
# Get Spigot version.
|
||||
spigot_version=$(mvn help:evaluate -Dexpression=project.dependencies["$i"].version -q -DforceStdout -P all -pl "$module")
|
||||
versions+=("$spigot_version")
|
||||
echo "$spigot_version"
|
||||
break
|
||||
fi
|
||||
done
|
||||
done
|
||||
|
||||
# Reset JVM parameters
|
||||
|
||||
Reference in new issue
Block a user