Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ on:

jobs:
publish:
uses: bentoboxworld/.github/.github/workflows/publish-platforms.yml@ca2dcd167e8db4e0f671a976080744dda43801a6 # master
uses: bentoboxworld/.github/.github/workflows/publish-platforms.yml@1f91a0edf72e8c86d671b3b8fdd3121ac6fb88e1 # master
with:
use_release_asset: "true" # publish the jar attached to the release; do not rebuild
hangar_slug: "MagicCobblestoneGenerator" # blank = skip Hangar
Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@
<!-- Revision variable removes warning about dynamic version -->
<revision>${build.version}-SNAPSHOT</revision>
<!-- This allows to change between versions and snapshots. -->
<build.version>2.10.0</build.version>
<build.version>2.10.1</build.version>
<build.number>-LOCAL</build.number>
<!-- Sonar Cloud -->
<sonar.projectKey>BentoBoxWorld_MagicCobblestoneGenerator</sonar.projectKey>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ public Optional<List<String>> tabComplete(User user, String alias, List<String>
File[] files = localeDir.listFiles(pathname ->
pathname.getName().endsWith(".json") && pathname.isFile());

if (files.length == 0)
if (files == null || files.length == 0)
{
// Don't show every player on the server. Require at least the first letter
return Optional.empty();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -614,6 +614,8 @@ public enum GuiAction
@ConfigComment("")
@ConfigComment("This indicates the length, in minutes, that a generator will remain on a cooldown, once it")
@ConfigComment("reaches its exhaustion limit. While on cooldown, the generator will not generate any new blocks.")
@ConfigComment("When the cooldown ends, a new period starts with the block count reset to 0.")
@ConfigComment("0 means no extra cooldown: the generator stops until the current period ends.")
@ConfigEntry(path = "exhaustion.cooldown")
private long generatorExhaustionCooldown = 1440;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public StoneGeneratorImportManager(StoneGeneratorAddon addon) {
public boolean importFile(@Nullable User user, World world) {
if (!this.generatorFile.exists()) {
if (user != null) {
Utils.sendMessage(user, user.getTranslation(Constants.ERRORS + "no-file", Constants.FILE,
Utils.sendMessage(user, user.getTranslation(NO_FILE, Constants.FILE,
this.generatorFile.getName()));
}

Expand All @@ -95,6 +95,25 @@ public boolean importFile(@Nullable User user, World world) {
return this.importFile(user, world, this.generatorFile.getName());
}

/**
* Resolves a file name given by an admin against the addon data folder, refusing names that point outside it
* (for example {@code ../../server.properties}).
*
* @param dataFolder addon data folder.
* @param fileName file name from a command argument.
* @return the file inside the data folder, or {@code null} if the name escapes the folder.
*/
@Nullable
static File resolveDataFile(File dataFolder, String fileName) {
try {
File folder = dataFolder.getCanonicalFile();
File file = new File(folder, fileName).getCanonicalFile();
return folder.equals(file.getParentFile()) ? file : null;
} catch (IOException e) {
return null;
}
}

/**
* This method imports generator tiers from template
*
Expand All @@ -104,11 +123,11 @@ public boolean importFile(@Nullable User user, World world) {
* @return true if successful
*/
public boolean importFile(@Nullable User user, World world, String file) {
File generatorFile = new File(this.addon.getDataFolder(), file.endsWith(".yml") ? file : file + ".yml");
File templateFile = resolveDataFile(this.addon.getDataFolder(), file.endsWith(".yml") ? file : file + ".yml");

if (!generatorFile.exists()) {
if (templateFile == null || !templateFile.exists()) {
if (user != null) {
Utils.sendMessage(user, user.getTranslation(Constants.ERRORS + "no-file", Constants.FILE, file));
Utils.sendMessage(user, user.getTranslation(NO_FILE, Constants.FILE, file));
}

return false;
Expand All @@ -117,7 +136,7 @@ public boolean importFile(@Nullable User user, World world, String file) {
YamlConfiguration config = new YamlConfiguration();

try {
config.load(generatorFile);
config.load(templateFile);
} catch (IOException | InvalidConfigurationException e) {
if (user != null) {
Utils.sendMessage(user, user.getTranslation(Constants.ERRORS + "no-load", Constants.FILE, file,
Expand Down Expand Up @@ -430,6 +449,24 @@ private void populateTreasures(GeneratorTierObject generatorTier, ConfigurationS
// Section: Database Methods
// ---------------------------------------------------------------------

/**
* Tells the user (or the console, for a console command) why an export could not be written.
*
* @param user user who ran the export.
* @param reference locale reference of the error.
* @param fileName file name the user gave.
* @return always {@code false}, so callers can {@code return} it.
*/
private boolean reportExportError(User user, String reference, String fileName) {
if (user.isPlayer()) {
Utils.sendMessage(user, user.getTranslation(reference, Constants.FILE, fileName));
} else {
this.addon.logWarning(reference + ": " + fileName);
}

return false;
}

/**
* This method generates file with a given name that contains everything from
* database for given world. It creates exact copy of data from database.
Expand All @@ -440,17 +477,16 @@ private void populateTreasures(GeneratorTierObject generatorTier, ConfigurationS
* @return {@code true} if export was successful, {@code false} otherwise.
*/
public boolean generateDatabaseFile(User user, World world, String fileName) {
File defaultFile = new File(this.addon.getDataFolder(),
File defaultFile = resolveDataFile(this.addon.getDataFolder(),
fileName.endsWith(".json") ? fileName : fileName + ".json");

if (defaultFile.exists()) {
if (user.isPlayer()) {
Utils.sendMessage(user, user.getTranslation(Constants.ERRORS + "file-exist", Constants.FILE, fileName));
} else {
this.addon.logWarning(Constants.ERRORS + "file-exist");
}
if (defaultFile == null) {
// File name points outside the addon folder (e.g. "../"). Refuse it.
return this.reportExportError(user, NO_FILE, fileName);
}

return false;
if (defaultFile.exists()) {
return this.reportExportError(user, Constants.ERRORS + "file-exist", fileName);
}

try {
Expand Down Expand Up @@ -525,8 +561,19 @@ public boolean generateDatabaseFile(User user, World world, String fileName) {
public boolean importDatabaseFile(User user, World world, String fileName) {
StoneGeneratorManager manager = this.addon.getAddonManager();

// If exist any generator that is bound to current world, then do not load
// generators.
// Load the file before touching existing data, so a missing or broken file does not wipe the
// game mode's generators.
DefaultDataHolder downloadedGenerators = new DefaultJSONHandler(this.addon).loadObject(fileName);

if (downloadedGenerators == null) {
if (user != null && user.isPlayer()) {
Utils.sendMessage(user, user.getTranslation(NO_FILE, Constants.FILE, fileName));
}

return false;
}

// If exist any generator that is bound to current world, then remove them before loading new ones.
if (!manager.getAllGeneratorTiers(world).isEmpty()) {
addon.getPlugin().getIWM().getAddon(world).ifPresent(this.addon.getAddonManager()::wipeGameModeGenerators);
}
Expand All @@ -536,11 +583,6 @@ public boolean importDatabaseFile(User user, World world, String fileName) {
// separate generators for
// each game mode.
String uniqueIDPrefix = Utils.getGameMode(world).toLowerCase() + "_";
DefaultDataHolder downloadedGenerators = new DefaultJSONHandler(this.addon).loadObject(fileName);

if (downloadedGenerators == null) {
return false;
}

// All new generators should get correct ID. So we need to map it to loaded
// generators.
Expand Down Expand Up @@ -659,18 +701,30 @@ DefaultDataHolder loadObject(String fileName) {
fileName = fileName + ".json";
}

File defaultFile = new File(this.addon.getDataFolder(), fileName);
File defaultFile = resolveDataFile(this.addon.getDataFolder(), fileName);

if (defaultFile == null) {
this.addon.logError(COULD_NOT_LOAD_FILE + fileName + "': it must be inside the addon folder.");
return null;
}

try (InputStreamReader reader = new InputStreamReader(new FileInputStream(defaultFile),
StandardCharsets.UTF_8)) {
DefaultDataHolder object = this.gson.fromJson(reader, DefaultDataHolder.class);

if (object == null) {
// Empty file.
this.addon.logError(COULD_NOT_LOAD_FILE + defaultFile.getName() + "': File is empty.");
return null;
}

object.setUniqueId(fileName);

reader.close(); // NOSONAR Required to keep OS file handlers low and not rely on GC

return object;
} catch (FileNotFoundException e) {
this.addon.logError("Could not load file '" + defaultFile.getName() + "': File not found.");
this.addon.logError(COULD_NOT_LOAD_FILE + defaultFile.getName() + "': File not found.");
} catch (Exception e) {
this.addon.logError("Could not load objects " + defaultFile.getName() + " " + e.getMessage());
}
Expand All @@ -694,12 +748,12 @@ DefaultDataHolder loadWebObject(String downloadedObject) {
/**
* Holds JSON builder object.
*/
private Gson gson;
private final Gson gson;

/**
* Holds StoneGeneratorAddon object.
*/
private StoneGeneratorAddon addon;
private final StoneGeneratorAddon addon;
}

/**
Expand Down Expand Up @@ -854,6 +908,16 @@ public void setAuthor(String author) {
*/
private final File generatorFile;

/**
* Locale reference for the "file not found" error.
*/
private static final String NO_FILE = Constants.ERRORS + "no-file";

/**
* Start of console messages for files that could not be loaded.
*/
private static final String COULD_NOT_LOAD_FILE = "Could not load file '";

private static final String DESCRIPTION = "description";

private static final String TIER_TEMPLATE_CONTEXT = ") in generatorTemplate.yml blocks section for tier ";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1288,10 +1288,15 @@ public void activateGenerator(@NotNull User user, @NotNull Island island,
if (this.addon.getSettings().isOverwriteOnActive() && generatorData.getActiveGeneratorCount() > 0
&& generatorData.getActiveGeneratorList().size() >= generatorData.getActiveGeneratorCount()) {
// Try to deactivate first generator, because overwrite is active.
GeneratorTierObject oldGenerator = this
.getGeneratorByID(generatorData.getActiveGeneratorList().iterator().next());
String oldId = generatorData.getActiveGeneratorList().iterator().next();
GeneratorTierObject oldGenerator = this.getGeneratorByID(oldId);

// The old generator may have been deleted while still active. It cannot be deactivated through
// deactivateGenerator (that needs the tier object), so just drop its id to free the slot.
boolean freed = oldGenerator == null ? generatorData.getActiveGeneratorList().remove(oldId)
: this.deactivateGenerator(user, generatorData, oldGenerator);

if (!this.deactivateGenerator(user, generatorData, oldGenerator)) {
if (!freed) {
// If deactivation was not successful, send message about reached limit.
Utils.sendMessage(user, user.getTranslation(Constants.MESSAGES + "active-generators-reached"));
activateGenerator.complete(false);
Expand Down Expand Up @@ -1322,7 +1327,8 @@ public boolean canPurchaseGenerator(@NotNull User user, @NotNull Island island,
@NotNull GeneratorDataObject generatorData, @NotNull GeneratorTierObject generatorTier) {

final User owner = island.isSpawn() || island.getOwner() == null ? null : User.getInstance(island.getOwner());
NumberFormat numberFormat = NumberFormat.getNumberInstance(owner.getLocale());
// Numbers are shown to the purchasing user, so format them in their locale. The owner may be null.
NumberFormat numberFormat = NumberFormat.getNumberInstance(user.getLocale());

if (generatorData.getPurchasedTiers().contains(generatorTier.getUniqueId())) {
// Generator is not unlocked. Return false.
Expand Down Expand Up @@ -1693,16 +1699,21 @@ public boolean canGenerateBlock(@NotNull Island island, @NotNull GeneratorTierOb
return false;
}

if (exhaustionData.getPeriodStart() == 0 || now - exhaustionData.getPeriodStart() >= periodMillis) {
// Start a new exhaustion period.
if (exhaustionData.getPeriodStart() == 0 || now - exhaustionData.getPeriodStart() >= periodMillis
|| exhaustionData.getCooldownUntil() > 0) {
// Start a new exhaustion period: first use, the previous period ended, or a cooldown just expired.
// Without the last condition, a cooldown shorter than the period would end with the count still at
// the limit and the generator would immediately go back on cooldown until the period ended.
exhaustionData.setPeriodStart(now);
exhaustionData.setGeneratedCount(0);
exhaustionData.setCooldownUntil(0);
}

if (exhaustionData.getGeneratedCount() >= limit) {
// Limit reached. Put the generator tier on a cooldown.
exhaustionData.setCooldownUntil(now + cooldownMillis);
// Limit reached. Put the generator tier on a cooldown. A cooldown of 0 means "no extra cooldown":
// the generator waits until the current period ends.
exhaustionData.setCooldownUntil(cooldownMillis > 0 ? now + cooldownMillis
: exhaustionData.getPeriodStart() + periodMillis);
this.notifyExhaustion(island, generatorTier, exhaustionData, now);
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,15 @@ protected void populateElements(PanelBuilder panelBuilder, List<T> objectList)
final int MAX_ELEMENTS = 21;
final int size = objectList.size();

// Index of the last page that has elements. Using size / MAX_ELEMENTS would point one page past the
// end when size is an exact multiple of MAX_ELEMENTS, showing an empty page.
final int lastPage = Math.max(0, (size - 1) / MAX_ELEMENTS);

if (this.pageIndex < 0)
{
this.pageIndex = size / MAX_ELEMENTS;
this.pageIndex = lastPage;
}
else if (this.pageIndex > (size / MAX_ELEMENTS))
else if (this.pageIndex > lastPage)
{
this.pageIndex = 0;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,8 @@ public void build()
PanelBuilder panelBuilder = new PanelBuilder().
user(this.user).
name(this.user.getTranslation(Constants.TITLE + "view-bundle",
Constants.BUNDLE, this.bundle.getFriendlyName()));
Constants.BUNDLE, Utils.fitTitleName(this.user, Constants.TITLE + "view-bundle",
Constants.BUNDLE, this.bundle.getFriendlyName())));

PanelUtils.fillBorder(panelBuilder, this.activeTab == Tab.BUNDLE_INFO ? 3 : 5, Material.MAGENTA_STAINED_GLASS_PANE);
this.populateHeader(panelBuilder);
Expand Down
Loading
Loading