Merge branch '2.x' into feature/socialspy

This commit is contained in:
William B 2024-02-14 15:15:12 -08:00 committed by GitHub
commit a19dd739ac
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
326 changed files with 26240 additions and 30529 deletions

View File

@ -6,18 +6,21 @@ dependencies {
compileOnly('com.github.milkbowl:VaultAPI:1.7') { compileOnly('com.github.milkbowl:VaultAPI:1.7') {
exclude group: "org.bukkit", module: "bukkit" exclude group: "org.bukkit", module: "bukkit"
} }
compileOnly 'net.luckperms:api:5.0' compileOnly 'net.luckperms:api:5.3'
api 'io.papermc:paperlib:1.0.6' api 'io.papermc:paperlib:1.0.6'
api 'org.bstats:bstats-bukkit:2.2.1'
implementation 'org.spongepowered:configurate-yaml:4.1.2' implementation 'org.spongepowered:configurate-yaml:4.1.2'
implementation 'org.checkerframework:checker-qual:3.14.0' implementation 'org.checkerframework:checker-qual:3.21.0'
implementation 'nu.studer:java-ordered-properties:1.0.4'
implementation 'net.kyori:adventure-api:4.15.0'
implementation 'net.kyori:adventure-text-minimessage:4.15.0'
implementation 'net.kyori:adventure-platform-bukkit:4.3.2'
// Providers // Providers
api project(':providers:BaseProviders') api project(':providers:BaseProviders')
api project(':providers:PaperProvider') api project(path: ':providers:PaperProvider', configuration: 'shadow')
api(project(':providers:NMSReflectionProvider')) { api(project(':providers:NMSReflectionProvider')) {
exclude group: "org.bukkit", module: "bukkit" exclude group: "org.bukkit", module: "bukkit"
} }
@ -43,8 +46,25 @@ shadowJar {
include (dependency('org.yaml:snakeyaml')) include (dependency('org.yaml:snakeyaml'))
include (dependency('io.leangen.geantyref:geantyref')) include (dependency('io.leangen.geantyref:geantyref'))
include (dependency('org.checkerframework:checker-qual')) include (dependency('org.checkerframework:checker-qual'))
include (dependency('nu.studer:java-ordered-properties'))
include (dependency('net.kyori:adventure-api'))
include (dependency('net.kyori:adventure-key'))
include (dependency('net.kyori:examination-api'))
include (dependency('net.kyori:examination-string'))
include (dependency('net.kyori:option'))
include (dependency('net.kyori:adventure-platform-bukkit'))
include (dependency('net.kyori:adventure-platform-api'))
include (dependency('net.kyori:adventure-platform-facet'))
include (dependency('net.kyori:adventure-nbt'))
include (dependency('net.kyori:adventure-text-serializer-bungeecord'))
include (dependency('net.kyori:adventure-text-serializer-gson'))
include (dependency('net.kyori:adventure-text-serializer-gson-legacy-impl'))
include (dependency('net.kyori:adventure-text-serializer-json'))
include (dependency('net.kyori:adventure-text-serializer-json-legacy-impl'))
include (dependency('net.kyori:adventure-text-serializer-legacy'))
include (dependency('net.kyori:adventure-text-minimessage'))
include (project(':providers:BaseProviders')) include (project(':providers:BaseProviders'))
include (project(':providers:PaperProvider')) include (project(path: ':providers:PaperProvider', configuration: 'shadow'))
include (project(':providers:NMSReflectionProvider')) include (project(':providers:NMSReflectionProvider'))
include (project(':providers:1_8Provider')) include (project(':providers:1_8Provider'))
include (project(':providers:1_12Provider')) include (project(':providers:1_12Provider'))
@ -55,8 +75,13 @@ shadowJar {
relocate 'org.yaml.snakeyaml', 'com.earth2me.essentials.libs.snakeyaml' relocate 'org.yaml.snakeyaml', 'com.earth2me.essentials.libs.snakeyaml'
relocate 'io.leangen.geantyref', 'com.earth2me.essentials.libs.geantyref' relocate 'io.leangen.geantyref', 'com.earth2me.essentials.libs.geantyref'
relocate 'org.checkerframework', 'com.earth2me.essentials.libs.checkerframework' relocate 'org.checkerframework', 'com.earth2me.essentials.libs.checkerframework'
relocate 'net.kyori', 'com.earth2me.essentials.libs.kyori'
relocate 'net.essentialsx.temp.adventure', 'net.kyori.adventure'
minimize { minimize {
include(dependency('org.checkerframework:checker-qual')) include(dependency('org.checkerframework:checker-qual'))
include(dependency('net.kyori:adventure-api'))
include(dependency('net.kyori:adventure-platform-bukkit'))
include(dependency('net.kyori:adventure-text-minimessage'))
} }
} }

View File

@ -8,6 +8,7 @@ import io.papermc.lib.PaperLib;
import net.ess3.api.IEssentials; import net.ess3.api.IEssentials;
import net.ess3.api.IUser; import net.ess3.api.IUser;
import net.ess3.api.InvalidWorldException; import net.ess3.api.InvalidWorldException;
import net.ess3.api.TranslatableException;
import net.ess3.api.events.UserWarpEvent; import net.ess3.api.events.UserWarpEvent;
import net.ess3.api.events.teleport.PreTeleportEvent; import net.ess3.api.events.teleport.PreTeleportEvent;
import net.ess3.api.events.teleport.TeleportWarmupEvent; import net.ess3.api.events.teleport.TeleportWarmupEvent;
@ -23,8 +24,6 @@ import java.util.GregorianCalendar;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import static com.earth2me.essentials.I18n.tl;
public class AsyncTeleport implements IAsyncTeleport { public class AsyncTeleport implements IAsyncTeleport {
private final IUser teleportOwner; private final IUser teleportOwner;
private final IEssentials ess; private final IEssentials ess;
@ -73,7 +72,7 @@ public class AsyncTeleport implements IAsyncTeleport {
time.setTimeInMillis(lastTime); time.setTimeInMillis(lastTime);
time.add(Calendar.SECOND, (int) cooldown); time.add(Calendar.SECOND, (int) cooldown);
time.add(Calendar.MILLISECOND, (int) ((cooldown * 1000.0) % 1000.0)); time.add(Calendar.MILLISECOND, (int) ((cooldown * 1000.0) % 1000.0));
future.completeExceptionally(new Exception(tl("timeBeforeTeleport", DateUtil.formatDateDiff(time.getTimeInMillis())))); future.completeExceptionally(new TranslatableException("timeBeforeTeleport", DateUtil.formatDateDiff(time.getTimeInMillis())));
return true; return true;
} }
} }
@ -107,7 +106,7 @@ public class AsyncTeleport implements IAsyncTeleport {
final Calendar c = new GregorianCalendar(); final Calendar c = new GregorianCalendar();
c.add(Calendar.SECOND, (int) delay); c.add(Calendar.SECOND, (int) delay);
c.add(Calendar.MILLISECOND, (int) ((delay * 1000.0) % 1000.0)); c.add(Calendar.MILLISECOND, (int) ((delay * 1000.0) % 1000.0));
user.sendMessage(tl("dontMoveMessage", DateUtil.formatDateDiff(c.getTimeInMillis()))); user.sendTl("dontMoveMessage", DateUtil.formatDateDiff(c.getTimeInMillis()));
} }
@Override @Override
@ -129,7 +128,7 @@ public class AsyncTeleport implements IAsyncTeleport {
nowAsync(teleportOwner, target, cause, future); nowAsync(teleportOwner, target, cause, future);
future.thenAccept(success -> { future.thenAccept(success -> {
if (success) { if (success) {
teleportOwner.sendMessage(tl("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ())); teleportOwner.sendTl("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ());
} }
}); });
} }
@ -166,7 +165,7 @@ public class AsyncTeleport implements IAsyncTeleport {
if (!ess.getSettings().isForcePassengerTeleport() && !teleportee.getBase().isEmpty()) { if (!ess.getSettings().isForcePassengerTeleport() && !teleportee.getBase().isEmpty()) {
if (!ess.getSettings().isTeleportPassengerDismount()) { if (!ess.getSettings().isTeleportPassengerDismount()) {
future.completeExceptionally(new Exception(tl("passengerTeleportFail"))); future.completeExceptionally(new TranslatableException("passengerTeleportFail"));
return; return;
} }
@ -204,7 +203,7 @@ public class AsyncTeleport implements IAsyncTeleport {
} }
} }
} else { } else {
future.completeExceptionally(new Exception(tl("unsafeTeleportDestination", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()))); future.completeExceptionally(new TranslatableException("unsafeTeleportDestination", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
return; return;
} }
} else { } else {
@ -233,7 +232,7 @@ public class AsyncTeleport implements IAsyncTeleport {
@Override @Override
public void teleport(final Player entity, final Trade chargeFor, final TeleportCause cause, final CompletableFuture<Boolean> future) { public void teleport(final Player entity, final Trade chargeFor, final TeleportCause cause, final CompletableFuture<Boolean> future) {
teleportOwner.sendMessage(tl("teleportToPlayer", entity.getDisplayName())); teleportOwner.sendTl("teleportToPlayer", entity.getDisplayName());
teleport(teleportOwner, new PlayerTarget(entity), chargeFor, cause, future); teleport(teleportOwner, new PlayerTarget(entity), chargeFor, cause, future);
} }
@ -248,8 +247,8 @@ public class AsyncTeleport implements IAsyncTeleport {
teleport(otherUser, target, chargeFor, cause, future); teleport(otherUser, target, chargeFor, cause, future);
future.thenAccept(success -> { future.thenAccept(success -> {
if (success) { if (success) {
otherUser.sendMessage(tl("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ())); otherUser.sendTl("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ());
teleportOwner.sendMessage(tl("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ())); teleportOwner.sendTl("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ());
} }
}); });
} }
@ -432,9 +431,9 @@ public class AsyncTeleport implements IAsyncTeleport {
final String finalWarp = warp; final String finalWarp = warp;
future.thenAccept(success -> { future.thenAccept(success -> {
if (success) { if (success) {
otherUser.sendMessage(tl("warpingTo", finalWarp, loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); otherUser.sendTl("warpingTo", finalWarp, loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
if (!otherUser.equals(teleportOwner)) { if (!otherUser.equals(teleportOwner)) {
teleportOwner.sendMessage(tl("warpingTo", finalWarp, loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); teleportOwner.sendTl("warpingTo", finalWarp, loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
} }
} }
}); });
@ -450,7 +449,7 @@ public class AsyncTeleport implements IAsyncTeleport {
public void back(final IUser teleporter, final Trade chargeFor, final CompletableFuture<Boolean> future) { public void back(final IUser teleporter, final Trade chargeFor, final CompletableFuture<Boolean> future) {
tpType = TeleportType.BACK; tpType = TeleportType.BACK;
final Location loc = teleportOwner.getLastLocation(); final Location loc = teleportOwner.getLastLocation();
teleportOwner.sendMessage(tl("backUsageMsg", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); teleportOwner.sendTl("backUsageMsg", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
teleportOther(teleporter, teleportOwner, new LocationTarget(loc), chargeFor, TeleportCause.COMMAND, future); teleportOther(teleporter, teleportOwner, new LocationTarget(loc), chargeFor, TeleportCause.COMMAND, future);
} }

View File

@ -8,8 +8,6 @@ import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import static com.earth2me.essentials.I18n.tl;
public class AsyncTimedTeleport implements Runnable { public class AsyncTimedTeleport implements Runnable {
private static final double MOVE_CONSTANT = 0.3; private static final double MOVE_CONSTANT = 0.3;
private final IUser teleportOwner; private final IUser teleportOwner;
@ -106,14 +104,14 @@ public class AsyncTimedTeleport implements Runnable {
try { try {
teleport.cooldown(false); teleport.cooldown(false);
} catch (final Throwable ex) { } catch (final Throwable ex) {
teleportOwner.sendMessage(tl("cooldownWithMessage", ex.getMessage())); teleportOwner.sendTl("cooldownWithMessage", ex.getMessage());
if (teleportOwner != teleportUser) { if (teleportOwner != teleportUser) {
teleportUser.sendMessage(tl("cooldownWithMessage", ex.getMessage())); teleportUser.sendTl("cooldownWithMessage", ex.getMessage());
} }
} }
try { try {
cancelTimer(false); cancelTimer(false);
teleportUser.sendMessage(tl("teleportationCommencing")); teleportUser.sendTl("teleportationCommencing");
if (timer_chargeFor != null) { if (timer_chargeFor != null) {
timer_chargeFor.isAffordableFor(teleportOwner); timer_chargeFor.isAffordableFor(teleportOwner);
@ -152,9 +150,9 @@ public class AsyncTimedTeleport implements Runnable {
try { try {
ess.getServer().getScheduler().cancelTask(timer_task); ess.getServer().getScheduler().cancelTask(timer_task);
if (notifyUser) { if (notifyUser) {
teleportOwner.sendMessage(tl("pendingTeleportCancelled")); teleportOwner.sendTl("pendingTeleportCancelled");
if (timer_teleportee != null && !timer_teleportee.equals(teleportOwner.getBase().getUniqueId())) { if (timer_teleportee != null && !timer_teleportee.equals(teleportOwner.getBase().getUniqueId())) {
ess.getUser(timer_teleportee).sendMessage(tl("pendingTeleportCancelled")); ess.getUser(timer_teleportee).sendTl("pendingTeleportCancelled");
} }
} }
} finally { } finally {

View File

@ -1,5 +1,6 @@
package com.earth2me.essentials; package com.earth2me.essentials;
import com.earth2me.essentials.utils.AdventureUtil;
import net.ess3.api.IEssentials; import net.ess3.api.IEssentials;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@ -11,7 +12,7 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level; import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tlLiteral;
public class Backup implements Runnable { public class Backup implements Runnable {
private transient final Server server; private transient final Server server;
@ -79,7 +80,7 @@ public class Backup implements Runnable {
taskLock.complete(new Object()); taskLock.complete(new Object());
return; return;
} }
ess.getLogger().log(Level.INFO, tl("backupStarted")); ess.getLogger().log(Level.INFO, AdventureUtil.miniToLegacy(tlLiteral("backupStarted")));
final CommandSender cs = server.getConsoleSender(); final CommandSender cs = server.getConsoleSender();
server.dispatchCommand(cs, "save-all"); server.dispatchCommand(cs, "save-all");
server.dispatchCommand(cs, "save-off"); server.dispatchCommand(cs, "save-off");
@ -118,7 +119,7 @@ public class Backup implements Runnable {
} }
active = false; active = false;
taskLock.complete(new Object()); taskLock.complete(new Object());
ess.getLogger().log(Level.INFO, tl("backupFinished")); ess.getLogger().log(Level.INFO, AdventureUtil.miniToLegacy(tlLiteral("backupFinished")));
} }
} }

View File

@ -1,12 +1,19 @@
package com.earth2me.essentials; package com.earth2me.essentials;
import com.earth2me.essentials.utils.AdventureUtil;
import net.kyori.adventure.platform.bukkit.BukkitAudiences;
import net.kyori.adventure.text.Component;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import static com.earth2me.essentials.I18n.tlLiteral;
public class CommandSource { public class CommandSource {
protected Essentials ess;
protected CommandSender sender; protected CommandSender sender;
public CommandSource(final CommandSender base) { public CommandSource(final Essentials ess, final CommandSender base) {
this.ess = ess;
this.sender = base; this.sender = base;
} }
@ -21,7 +28,40 @@ public class CommandSource {
return null; return null;
} }
public final net.ess3.api.IUser getUser(final IEssentials ess) { public void sendTl(final String tlKey, final Object... args) {
if (isPlayer()) {
//noinspection ConstantConditions
getUser().sendTl(tlKey, args);
return;
}
final String translation = tlLiteral(tlKey, args);
sendComponent(AdventureUtil.miniMessage().deserialize(translation));
}
public String tl(final String tlKey, final Object... args) {
if (isPlayer()) {
//noinspection ConstantConditions
return getUser().playerTl(tlKey, args);
}
return tlLiteral(tlKey, args);
}
public Component tlComponent(final String tlKey, final Object... args) {
if (isPlayer()) {
//noinspection ConstantConditions
return getUser().tlComponent(tlKey, args);
}
final String translation = tlLiteral(tlKey, args);
return AdventureUtil.miniMessage().deserialize(translation);
}
public void sendComponent(final Component component) {
final BukkitAudiences audiences = ess.getBukkitAudience();
audiences.sender(sender).sendMessage(component);
}
public final net.ess3.api.IUser getUser() {
if (sender instanceof Player) { if (sender instanceof Player) {
return ess.getUser((Player) sender); return ess.getUser((Player) sender);
} }
@ -42,15 +82,18 @@ public class CommandSource {
} }
} }
public boolean isAuthorized(final String permission, final IEssentials ess) { public boolean isAuthorized(final String permission) {
return !(sender instanceof Player) || getUser(ess).isAuthorized(permission); //noinspection ConstantConditions
return !(sender instanceof Player) || getUser().isAuthorized(permission);
} }
public String getSelfSelector() { public String getSelfSelector() {
//noinspection ConstantConditions
return sender instanceof Player ? getPlayer().getName() : "*"; return sender instanceof Player ? getPlayer().getName() : "*";
} }
public String getDisplayName() { public String getDisplayName() {
//noinspection ConstantConditions
return sender instanceof Player ? getPlayer().getDisplayName() : getSender().getName(); return sender instanceof Player ? getPlayer().getDisplayName() : getSender().getName();
} }
} }

View File

@ -2,17 +2,20 @@ package com.earth2me.essentials;
import com.earth2me.essentials.messaging.IMessageRecipient; import com.earth2me.essentials.messaging.IMessageRecipient;
import com.earth2me.essentials.messaging.SimpleMessageRecipient; import com.earth2me.essentials.messaging.SimpleMessageRecipient;
import com.earth2me.essentials.utils.AdventureUtil;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.util.UUID; import java.util.UUID;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tlLiteral;
public final class Console implements IMessageRecipient { public final class Console implements IMessageRecipient {
public static final String NAME = "Console"; public static final String NAME = "Console";
public static final String DISPLAY_NAME = tl("consoleName"); public static final String DISPLAY_NAME = tlLiteral("consoleName");
private static Console instance; // Set in essentials private static Console instance; // Set in essentials
private final IEssentials ess; private final IEssentials ess;
@ -63,6 +66,21 @@ public final class Console implements IMessageRecipient {
getCommandSender().sendMessage(message); getCommandSender().sendMessage(message);
} }
@Override
public void sendTl(String tlKey, Object... args) {
final String translation = tlLiteral(tlKey, args);
final Audience consoleAudience = ((Essentials) ess).getBukkitAudience().sender(getCommandSender());
final Component component = AdventureUtil.miniMessage()
.deserialize(translation);
consoleAudience.sendMessage(component);
}
@Override
public String tlSender(String tlKey, Object... args) {
return tlLiteral(tlKey, args);
}
@Override @Override
public boolean isReachable() { public boolean isReachable() {
return true; return true;

View File

@ -40,6 +40,7 @@ import com.earth2me.essentials.textreader.KeywordReplacer;
import com.earth2me.essentials.textreader.SimpleTextInput; import com.earth2me.essentials.textreader.SimpleTextInput;
import com.earth2me.essentials.updatecheck.UpdateChecker; import com.earth2me.essentials.updatecheck.UpdateChecker;
import com.earth2me.essentials.userstorage.ModernUserMap; import com.earth2me.essentials.userstorage.ModernUserMap;
import com.earth2me.essentials.utils.AdventureUtil;
import com.earth2me.essentials.utils.FormatUtil; import com.earth2me.essentials.utils.FormatUtil;
import com.earth2me.essentials.utils.VersionUtil; import com.earth2me.essentials.utils.VersionUtil;
import io.papermc.lib.PaperLib; import io.papermc.lib.PaperLib;
@ -48,6 +49,7 @@ import net.ess3.api.IEssentials;
import net.ess3.api.IItemDb; import net.ess3.api.IItemDb;
import net.ess3.api.IJails; import net.ess3.api.IJails;
import net.ess3.api.ISettings; import net.ess3.api.ISettings;
import net.ess3.api.TranslatableException;
import net.ess3.nms.refl.providers.ReflDataWorldInfoProvider; import net.ess3.nms.refl.providers.ReflDataWorldInfoProvider;
import net.ess3.nms.refl.providers.ReflFormattedCommandAliasProvider; import net.ess3.nms.refl.providers.ReflFormattedCommandAliasProvider;
import net.ess3.nms.refl.providers.ReflKnownCommandsProvider; import net.ess3.nms.refl.providers.ReflKnownCommandsProvider;
@ -63,6 +65,7 @@ import net.ess3.provider.ItemUnbreakableProvider;
import net.ess3.provider.KnownCommandsProvider; import net.ess3.provider.KnownCommandsProvider;
import net.ess3.provider.MaterialTagProvider; import net.ess3.provider.MaterialTagProvider;
import net.ess3.provider.PersistentDataProvider; import net.ess3.provider.PersistentDataProvider;
import net.ess3.provider.PlayerLocaleProvider;
import net.ess3.provider.PotionMetaProvider; import net.ess3.provider.PotionMetaProvider;
import net.ess3.provider.ProviderListener; import net.ess3.provider.ProviderListener;
import net.ess3.provider.SerializationProvider; import net.ess3.provider.SerializationProvider;
@ -81,11 +84,13 @@ import net.ess3.provider.providers.BukkitSpawnerBlockProvider;
import net.ess3.provider.providers.FixedHeightWorldInfoProvider; import net.ess3.provider.providers.FixedHeightWorldInfoProvider;
import net.ess3.provider.providers.FlatSpawnEggProvider; import net.ess3.provider.providers.FlatSpawnEggProvider;
import net.ess3.provider.providers.LegacyItemUnbreakableProvider; import net.ess3.provider.providers.LegacyItemUnbreakableProvider;
import net.ess3.provider.providers.LegacyPlayerLocaleProvider;
import net.ess3.provider.providers.LegacyPotionMetaProvider; import net.ess3.provider.providers.LegacyPotionMetaProvider;
import net.ess3.provider.providers.LegacySpawnEggProvider; import net.ess3.provider.providers.LegacySpawnEggProvider;
import net.ess3.provider.providers.ModernDataWorldInfoProvider; import net.ess3.provider.providers.ModernDataWorldInfoProvider;
import net.ess3.provider.providers.ModernItemUnbreakableProvider; import net.ess3.provider.providers.ModernItemUnbreakableProvider;
import net.ess3.provider.providers.ModernPersistentDataProvider; import net.ess3.provider.providers.ModernPersistentDataProvider;
import net.ess3.provider.providers.ModernPlayerLocaleProvider;
import net.ess3.provider.providers.ModernSignDataProvider; import net.ess3.provider.providers.ModernSignDataProvider;
import net.ess3.provider.providers.PaperContainerProvider; import net.ess3.provider.providers.PaperContainerProvider;
import net.ess3.provider.providers.PaperKnownCommandsProvider; import net.ess3.provider.providers.PaperKnownCommandsProvider;
@ -95,6 +100,9 @@ import net.ess3.provider.providers.PaperSerializationProvider;
import net.ess3.provider.providers.PaperServerStateProvider; import net.ess3.provider.providers.PaperServerStateProvider;
import net.essentialsx.api.v2.services.BalanceTop; import net.essentialsx.api.v2.services.BalanceTop;
import net.essentialsx.api.v2.services.mail.MailService; import net.essentialsx.api.v2.services.mail.MailService;
import net.kyori.adventure.platform.bukkit.BukkitAudiences;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.block.Block; import org.bukkit.block.Block;
@ -139,13 +147,15 @@ import java.util.function.Predicate;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tlLiteral;
import static com.earth2me.essentials.I18n.tlLocale;
public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
private static final Logger BUKKIT_LOGGER = Logger.getLogger("Essentials"); private static final Logger BUKKIT_LOGGER = Logger.getLogger("Essentials");
private static Logger LOGGER = null; private static Logger LOGGER = null;
private final transient TNTExplodeListener tntListener = new TNTExplodeListener(); private final transient TNTExplodeListener tntListener = new TNTExplodeListener();
private final transient Set<String> vanishedPlayers = new LinkedHashSet<>(); private final transient Set<String> vanishedPlayers = new LinkedHashSet<>();
private final transient Map<String, IEssentialsCommand> commandMap = new HashMap<>();
private transient ISettings settings; private transient ISettings settings;
private transient Jails jails; private transient Jails jails;
private transient Warps warps; private transient Warps warps;
@ -181,11 +191,12 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
private transient ReflOnlineModeProvider onlineModeProvider; private transient ReflOnlineModeProvider onlineModeProvider;
private transient ItemUnbreakableProvider unbreakableProvider; private transient ItemUnbreakableProvider unbreakableProvider;
private transient WorldInfoProvider worldInfoProvider; private transient WorldInfoProvider worldInfoProvider;
private transient PlayerLocaleProvider playerLocaleProvider;
private transient SignDataProvider signDataProvider; private transient SignDataProvider signDataProvider;
private transient Kits kits; private transient Kits kits;
private transient RandomTeleport randomTeleport; private transient RandomTeleport randomTeleport;
private transient UpdateChecker updateChecker; private transient UpdateChecker updateChecker;
private transient Map<String, IEssentialsCommand> commandMap = new HashMap<>(); private transient BukkitAudiences bukkitAudience;
static { static {
EconomyLayers.init(); EconomyLayers.init();
@ -221,7 +232,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
i18n.updateLocale("en"); i18n.updateLocale("en");
Console.setInstance(this); Console.setInstance(this);
LOGGER.log(Level.INFO, tl("usingTempFolderForTesting")); LOGGER.log(Level.INFO, AdventureUtil.miniToLegacy(tlLiteral("usingTempFolderForTesting")));
LOGGER.log(Level.INFO, dataFolder.toString()); LOGGER.log(Level.INFO, dataFolder.toString());
settings = new Settings(this); settings = new Settings(this);
mail = new MailServiceImpl(this); mail = new MailServiceImpl(this);
@ -233,6 +244,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
jails = new Jails(this); jails = new Jails(this);
registerListeners(server.getPluginManager()); registerListeners(server.getPluginManager());
kits = new Kits(this); kits = new Kits(this);
bukkitAudience = BukkitAudiences.create(this);
} }
@Override @Override
@ -257,6 +269,11 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
execTimer = new ExecuteTimer(); execTimer = new ExecuteTimer();
execTimer.start(); execTimer.start();
final EssentialsUpgrade upgrade = new EssentialsUpgrade(this);
upgrade.upgradeLang();
execTimer.mark("AdventureUpgrade");
i18n = new I18n(this); i18n = new I18n(this);
i18n.onEnable(); i18n.onEnable();
execTimer.mark("I18n1"); execTimer.mark("I18n1");
@ -265,37 +282,36 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
switch (VersionUtil.getServerSupportStatus()) { switch (VersionUtil.getServerSupportStatus()) {
case NMS_CLEANROOM: case NMS_CLEANROOM:
getLogger().severe(tl("serverUnsupportedCleanroom")); getLogger().severe(AdventureUtil.miniToLegacy(tlLiteral("serverUnsupportedCleanroom")));
break; break;
case DANGEROUS_FORK: case DANGEROUS_FORK:
getLogger().severe(tl("serverUnsupportedDangerous")); getLogger().severe(AdventureUtil.miniToLegacy(tlLiteral("serverUnsupportedDangerous")));
break; break;
case STUPID_PLUGIN: case STUPID_PLUGIN:
getLogger().severe(tl("serverUnsupportedDumbPlugins")); getLogger().severe(AdventureUtil.miniToLegacy(tlLiteral("serverUnsupportedDumbPlugins")));
break; break;
case UNSTABLE: case UNSTABLE:
getLogger().severe(tl("serverUnsupportedMods")); getLogger().severe(AdventureUtil.miniToLegacy(tlLiteral("serverUnsupportedMods")));
break; break;
case OUTDATED: case OUTDATED:
getLogger().severe(tl("serverUnsupported")); getLogger().severe(AdventureUtil.miniToLegacy(tlLiteral("serverUnsupported")));
break; break;
case LIMITED: case LIMITED:
getLogger().info(tl("serverUnsupportedLimitedApi")); getLogger().info(AdventureUtil.miniToLegacy(tlLiteral("serverUnsupportedLimitedApi")));
break; break;
} }
if (VersionUtil.getSupportStatusClass() != null) { if (VersionUtil.getSupportStatusClass() != null) {
getLogger().info(tl("serverUnsupportedClass", VersionUtil.getSupportStatusClass())); getLogger().info(AdventureUtil.miniToLegacy(tlLiteral("serverUnsupportedClass", VersionUtil.getSupportStatusClass())));
} }
final PluginManager pm = getServer().getPluginManager(); final PluginManager pm = getServer().getPluginManager();
for (final Plugin plugin : pm.getPlugins()) { for (final Plugin plugin : pm.getPlugins()) {
if (plugin.getDescription().getName().startsWith("Essentials") && !plugin.getDescription().getVersion().equals(this.getDescription().getVersion()) && !plugin.getDescription().getName().equals("EssentialsAntiCheat")) { if (plugin.getDescription().getName().startsWith("Essentials") && !plugin.getDescription().getVersion().equals(this.getDescription().getVersion()) && !plugin.getDescription().getName().equals("EssentialsAntiCheat")) {
getLogger().warning(tl("versionMismatch", plugin.getDescription().getName())); getLogger().warning(AdventureUtil.miniToLegacy(tlLiteral("versionMismatch", plugin.getDescription().getName())));
} }
} }
final EssentialsUpgrade upgrade = new EssentialsUpgrade(this);
upgrade.beforeSettings(); upgrade.beforeSettings();
execTimer.mark("Upgrade"); execTimer.mark("Upgrade");
@ -453,6 +469,12 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
signDataProvider = new ModernSignDataProvider(this); signDataProvider = new ModernSignDataProvider(this);
} }
if (VersionUtil.getServerBukkitVersion().isHigherThanOrEqualTo(VersionUtil.v1_12_2_R01)) {
playerLocaleProvider = new ModernPlayerLocaleProvider();
} else {
playerLocaleProvider = new LegacyPlayerLocaleProvider();
}
execTimer.mark("Init(Providers)"); execTimer.mark("Init(Providers)");
reload(); reload();
@ -475,9 +497,9 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
updateChecker = new UpdateChecker(this); updateChecker = new UpdateChecker(this);
runTaskAsynchronously(() -> { runTaskAsynchronously(() -> {
getLogger().log(Level.INFO, tl("versionFetching")); getLogger().log(Level.INFO, AdventureUtil.miniToLegacy(tlLiteral("versionFetching")));
for (String str : updateChecker.getVersionMessages(false, true)) { for (final Component component : updateChecker.getVersionMessages(false, true, new CommandSource(this, Bukkit.getConsoleSender()))) {
getLogger().log(getSettings().isUpdateCheckEnabled() ? Level.WARNING : Level.INFO, str); getLogger().log(getSettings().isUpdateCheckEnabled() ? Level.WARNING : Level.INFO, AdventureUtil.adventureToLegacy(component));
} }
}); });
@ -560,13 +582,13 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
public void onDisable() { public void onDisable() {
final boolean stopping = getServerStateProvider().isStopping(); final boolean stopping = getServerStateProvider().isStopping();
if (!stopping) { if (!stopping) {
LOGGER.log(Level.SEVERE, tl("serverReloading")); LOGGER.log(Level.SEVERE, AdventureUtil.miniToLegacy(tlLiteral("serverReloading")));
} }
getBackup().setPendingShutdown(true); getBackup().setPendingShutdown(true);
for (final User user : getOnlineUsers()) { for (final User user : getOnlineUsers()) {
if (user.isVanished()) { if (user.isVanished()) {
user.setVanished(false); user.setVanished(false);
user.sendMessage(tl("unvanishedReload")); user.sendTl("unvanishedReload");
} }
if (stopping) { if (stopping) {
user.setLogoutLocation(); user.setLogoutLocation();
@ -580,7 +602,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
} }
cleanupOpenInventories(); cleanupOpenInventories();
if (getBackup().getTaskLock() != null && !getBackup().getTaskLock().isDone()) { if (getBackup().getTaskLock() != null && !getBackup().getTaskLock().isDone()) {
LOGGER.log(Level.SEVERE, tl("backupInProgress")); LOGGER.log(Level.SEVERE, AdventureUtil.miniToLegacy(tlLiteral("backupInProgress")));
getBackup().getTaskLock().join(); getBackup().getTaskLock().join();
} }
if (i18n != null) { if (i18n != null) {
@ -612,13 +634,15 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
for (final String commandName : this.getDescription().getCommands().keySet()) { for (final String commandName : this.getDescription().getCommands().keySet()) {
final Command command = this.getCommand(commandName); final Command command = this.getCommand(commandName);
if (command != null) { if (command != null) {
command.setDescription(tl(commandName + "CommandDescription")); command.setDescription(tlLiteral(commandName + "CommandDescription"));
command.setUsage(tl(commandName + "CommandUsage")); command.setUsage(tlLiteral(commandName + "CommandUsage"));
} }
} }
final PluginManager pm = getServer().getPluginManager(); final PluginManager pm = getServer().getPluginManager();
registerListeners(pm); registerListeners(pm);
bukkitAudience = BukkitAudiences.create(this);
} }
private IEssentialsCommand loadCommand(final String path, final String name, final IEssentialsModule module, final ClassLoader classLoader) throws Exception { private IEssentialsCommand loadCommand(final String path, final String name, final IEssentialsModule module, final ClassLoader classLoader) throws Exception {
@ -667,7 +691,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
user = getUser((Player) cSender); user = getUser((Player) cSender);
} }
final CommandSource sender = new CommandSource(cSender); final CommandSource sender = new CommandSource(this, cSender);
// Check for disabled commands // Check for disabled commands
if (getSettings().isCommandDisabled(commandLabel)) { if (getSettings().isCommandDisabled(commandLabel)) {
@ -684,8 +708,8 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
try { try {
cmd = loadCommand(commandPath, command.getName(), module, classLoader); cmd = loadCommand(commandPath, command.getName(), module, classLoader);
} catch (final Exception ex) { } catch (final Exception ex) {
sender.sendMessage(tl("commandNotLoaded", commandLabel)); sender.sendTl("commandNotLoaded", commandLabel);
LOGGER.log(Level.SEVERE, tl("commandNotLoaded", commandLabel), ex); LOGGER.log(Level.SEVERE, AdventureUtil.miniToLegacy(tlLiteral("commandNotLoaded", commandLabel)), ex);
return Collections.emptyList(); return Collections.emptyList();
} }
@ -708,11 +732,11 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
} catch (final Exception ex) { } catch (final Exception ex) {
showError(sender, ex, commandLabel); showError(sender, ex, commandLabel);
// Tab completion shouldn't fail // Tab completion shouldn't fail
LOGGER.log(Level.SEVERE, tl("commandFailed", commandLabel), ex); LOGGER.log(Level.SEVERE, AdventureUtil.miniToLegacy(tlLiteral("commandFailed", commandLabel)), ex);
return Collections.emptyList(); return Collections.emptyList();
} }
} catch (final Throwable ex) { } catch (final Throwable ex) {
LOGGER.log(Level.SEVERE, tl("commandFailed", commandLabel), ex); LOGGER.log(Level.SEVERE, AdventureUtil.miniToLegacy(tlLiteral("commandFailed", commandLabel)), ex);
return Collections.emptyList(); return Collections.emptyList();
} }
} }
@ -737,7 +761,11 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
pc.execute(cSender, commandLabel, args); pc.execute(cSender, commandLabel, args);
} catch (final Exception ex) { } catch (final Exception ex) {
LOGGER.log(Level.SEVERE, ex.getMessage(), ex); LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
cSender.sendMessage(tl("internalError")); if (cSender instanceof Player) {
cSender.sendMessage(tlLocale(I18n.getLocale(getPlayerLocaleProvider().getLocale((Player) cSender)), "internalError"));
} else {
cSender.sendMessage(tlLiteral("internalError"));
}
} }
return true; return true;
} }
@ -762,7 +790,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
LOGGER.log(Level.INFO, cSender.getName()+ " issued server command: /" + commandLabel + " " + EssentialsCommand.getFinalArg(args, 0)); LOGGER.log(Level.INFO, cSender.getName()+ " issued server command: /" + commandLabel + " " + EssentialsCommand.getFinalArg(args, 0));
} }
final CommandSource sender = new CommandSource(cSender); final CommandSource sender = new CommandSource(this, cSender);
// New mail notification // New mail notification
if (user != null && !getSettings().isCommandDisabled("mail") && !command.getName().equals("mail") && user.isAuthorized("essentials.mail")) { if (user != null && !getSettings().isCommandDisabled("mail") && !command.getName().equals("mail") && user.isAuthorized("essentials.mail")) {
@ -783,7 +811,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
return newCmd.execute(cSender, commandLabel, args); return newCmd.execute(cSender, commandLabel, args);
} }
} }
sender.sendMessage(tl("commandDisabled", commandLabel)); sender.sendTl("commandDisabled", commandLabel);
return true; return true;
} }
@ -791,23 +819,23 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
try { try {
cmd = loadCommand(commandPath, command.getName(), module, classLoader); cmd = loadCommand(commandPath, command.getName(), module, classLoader);
} catch (final Exception ex) { } catch (final Exception ex) {
sender.sendMessage(tl("commandNotLoaded", commandLabel)); sender.sendTl("commandNotLoaded", commandLabel);
LOGGER.log(Level.SEVERE, tl("commandNotLoaded", commandLabel), ex); LOGGER.log(Level.SEVERE, AdventureUtil.miniToLegacy(tlLiteral("commandNotLoaded", commandLabel)), ex);
return true; return true;
} }
// Check authorization // Check authorization
if (user != null && !user.isAuthorized(cmd, permissionPrefix)) { if (user != null && !user.isAuthorized(cmd, permissionPrefix)) {
LOGGER.log(Level.INFO, tl("deniedAccessCommand", user.getName())); LOGGER.log(Level.INFO, AdventureUtil.miniToLegacy(tlLiteral("deniedAccessCommand", user.getName())));
user.sendMessage(tl("noAccessCommand")); user.sendTl("noAccessCommand");
return true; return true;
} }
if (user != null && user.isJailed() && !user.isAuthorized(cmd, "essentials.jail.allow.")) { if (user != null && user.isJailed() && !user.isAuthorized(cmd, "essentials.jail.allow.")) {
if (user.getJailTimeout() > 0) { if (user.getJailTimeout() > 0) {
user.sendMessage(tl("playerJailedFor", user.getName(), user.getFormattedJailTime())); user.sendTl("playerJailedFor", user.getName(), user.getFormattedJailTime());
} else { } else {
user.sendMessage(tl("jailMessage")); user.sendTl("jailMessage");
} }
return true; return true;
} }
@ -824,11 +852,11 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
return true; return true;
} catch (final NotEnoughArgumentsException ex) { } catch (final NotEnoughArgumentsException ex) {
if (getSettings().isVerboseCommandUsages() && !cmd.getUsageStrings().isEmpty()) { if (getSettings().isVerboseCommandUsages() && !cmd.getUsageStrings().isEmpty()) {
sender.sendMessage(tl("commandHelpLine1", commandLabel)); sender.sendTl("commandHelpLine1", commandLabel);
sender.sendMessage(tl("commandHelpLine2", command.getDescription())); sender.sendTl("commandHelpLine2", command.getDescription());
sender.sendMessage(tl("commandHelpLine3")); sender.sendTl("commandHelpLine3");
for (Map.Entry<String, String> usage : cmd.getUsageStrings().entrySet()) { for (Map.Entry<String, String> usage : cmd.getUsageStrings().entrySet()) {
sender.sendMessage(tl("commandHelpLineUsage", usage.getKey().replace("<command>", commandLabel), usage.getValue())); sender.sendTl("commandHelpLineUsage", AdventureUtil.parsed(usage.getKey().replace("<command>", commandLabel)), AdventureUtil.parsed(usage.getValue()));
} }
} else { } else {
sender.sendMessage(command.getDescription()); sender.sendMessage(command.getDescription());
@ -849,7 +877,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
return true; return true;
} }
} catch (final Throwable ex) { } catch (final Throwable ex) {
LOGGER.log(Level.SEVERE, tl("commandFailed", commandLabel), ex); LOGGER.log(Level.SEVERE, AdventureUtil.miniToLegacy(tlLiteral("commandFailed", commandLabel)), ex);
return true; return true;
} }
} }
@ -875,9 +903,14 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
@Override @Override
public void showError(final CommandSource sender, final Throwable exception, final String commandLabel) { public void showError(final CommandSource sender, final Throwable exception, final String commandLabel) {
sender.sendMessage(tl("errorWithMessage", exception.getMessage())); if (exception instanceof TranslatableException) {
final String tlMessage = sender.tl(((TranslatableException) exception).getTlKey(), ((TranslatableException) exception).getArgs());
sender.sendTl("errorWithMessage", AdventureUtil.parsed(tlMessage));
} else {
sender.sendTl("errorWithMessage", exception.getMessage());
}
if (getSettings().isDebug()) { if (getSettings().isDebug()) {
LOGGER.log(Level.INFO, tl("errorCallingCommand", commandLabel), exception); LOGGER.log(Level.INFO, AdventureUtil.miniToLegacy(tlLiteral("errorCallingCommand", commandLabel)), exception);
} }
} }
@ -1067,8 +1100,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
private void handleCrash(final Throwable exception) { private void handleCrash(final Throwable exception) {
final PluginManager pm = getServer().getPluginManager(); final PluginManager pm = getServer().getPluginManager();
LOGGER.log(Level.SEVERE, exception.toString()); getWrappedLogger().log(Level.SEVERE, exception.toString(), exception);
exception.printStackTrace();
pm.registerEvents(new Listener() { pm.registerEvents(new Listener() {
@EventHandler(priority = EventPriority.LOW) @EventHandler(priority = EventPriority.LOW)
public void onPlayerJoin(final PlayerJoinEvent event) { public void onPlayerJoin(final PlayerJoinEvent event) {
@ -1099,12 +1131,12 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
@Override @Override
public int broadcastMessage(final String message) { public int broadcastMessage(final String message) {
return broadcastMessage(null, null, message, true, u -> false); return broadcastMessage(null, null, message, true, null);
} }
@Override @Override
public int broadcastMessage(final IUser sender, final String message) { public int broadcastMessage(final IUser sender, final String message) {
return broadcastMessage(sender, null, message, false, u -> false); return broadcastMessage(sender, null, message, false, null);
} }
@Override @Override
@ -1114,7 +1146,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
@Override @Override
public int broadcastMessage(final String permission, final String message) { public int broadcastMessage(final String permission, final String message) {
return broadcastMessage(null, permission, message, false, u -> false); return broadcastMessage(null, permission, message, false, null);
} }
private int broadcastMessage(final IUser sender, final String permission, final String message, final boolean keywords, final Predicate<IUser> shouldExclude) { private int broadcastMessage(final IUser sender, final String permission, final String message, final boolean keywords, final Predicate<IUser> shouldExclude) {
@ -1128,11 +1160,11 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
for (final Player player : players) { for (final Player player : players) {
final User user = getUser(player); final User user = getUser(player);
if ((permission == null && (sender == null || !user.isIgnoredPlayer(sender))) || (permission != null && user.isAuthorized(permission))) { if ((permission == null && (sender == null || !user.isIgnoredPlayer(sender))) || (permission != null && user.isAuthorized(permission))) {
if (shouldExclude.test(user)) { if (shouldExclude != null && shouldExclude.test(user)) {
continue; continue;
} }
if (keywords) { if (keywords) {
broadcast = new KeywordReplacer(broadcast, new CommandSource(player), this, false); broadcast = new KeywordReplacer(broadcast, new CommandSource(this, player), this, false);
} }
for (final String messageText : broadcast.getLines()) { for (final String messageText : broadcast.getLines()) {
user.sendMessage(messageText); user.sendMessage(messageText);
@ -1143,6 +1175,52 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
return players.size(); return players.size();
} }
@Override
public void broadcastTl(final String tlKey, final Object... args) {
broadcastTl(null, null, true, tlKey, args);
}
@Override
public void broadcastTl(final IUser sender, final String tlKey, final Object... args) {
broadcastTl(sender, null, false, tlKey, args);
}
@Override
public void broadcastTl(final IUser sender, final String permission, final String tlKey, final Object... args) {
broadcastTl(sender, u -> !u.isAuthorized(permission), false, tlKey, args);
}
@Override
public void broadcastTl(IUser sender, Predicate<IUser> shouldExclude, String tlKey, Object... args) {
broadcastTl(sender, shouldExclude, false, tlKey, args);
}
@Override
public void broadcastTl(final IUser sender, final Predicate<IUser> shouldExclude, final boolean parseKeywords, final String tlKey, final Object... args) {
if (sender != null && sender.isHidden()) {
return;
}
for (final User user : getOnlineUsers()) {
if (sender != null && user.isIgnoredPlayer(sender)) {
continue;
}
if (shouldExclude != null && shouldExclude.test(user)) {
continue;
}
final Object[] processedArgs;
if (parseKeywords) {
processedArgs = I18n.mutateArgs(args, s -> new KeywordReplacer(new SimpleTextInput(s.toString()), new CommandSource(this, user.getBase()), this, false).getLines().get(0));
} else {
processedArgs = args;
}
user.sendTl(tlKey, processedArgs);
}
}
@Override @Override
public BukkitTask runTaskAsynchronously(final Runnable run) { public BukkitTask runTaskAsynchronously(final Runnable run) {
return this.getScheduler().runTaskAsynchronously(this, run); return this.getScheduler().runTaskAsynchronously(this, run);
@ -1322,6 +1400,11 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
return worldInfoProvider; return worldInfoProvider;
} }
@Override
public PlayerLocaleProvider getPlayerLocaleProvider() {
return playerLocaleProvider;
}
@Override @Override
public SignDataProvider getSignDataProvider() { public SignDataProvider getSignDataProvider() {
return signDataProvider; return signDataProvider;
@ -1332,6 +1415,10 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
return this.getCommand(cmd); return this.getCommand(cmd);
} }
public BukkitAudiences getBukkitAudience() {
return bukkitAudience;
}
private AbstractItemDb getItemDbFromConfig() { private AbstractItemDb getItemDbFromConfig() {
final String setting = settings.getItemDbType(); final String setting = settings.getItemDbType();

View File

@ -32,8 +32,6 @@ import java.util.List;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import static com.earth2me.essentials.I18n.tl;
public class EssentialsEntityListener implements Listener { public class EssentialsEntityListener implements Listener {
private static final transient Pattern powertoolPlayer = Pattern.compile("\\{player\\}"); private static final transient Pattern powertoolPlayer = Pattern.compile("\\{player\\}");
private final IEssentials ess; private final IEssentials ess;
@ -167,11 +165,11 @@ public class EssentialsEntityListener implements Listener {
final User user = ess.getUser(event.getEntity()); final User user = ess.getUser(event.getEntity());
if (ess.getSettings().infoAfterDeath()) { if (ess.getSettings().infoAfterDeath()) {
final Location loc = user.getLocation(); final Location loc = user.getLocation();
user.sendMessage(tl("infoAfterDeath", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); user.sendTl("infoAfterDeath", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
} }
if (user.isAuthorized("essentials.back.ondeath") && !ess.getSettings().isCommandDisabled("back")) { if (user.isAuthorized("essentials.back.ondeath") && !ess.getSettings().isCommandDisabled("back")) {
user.setLastLocation(); user.setLastLocation();
user.sendMessage(tl("backAfterDeath")); user.sendTl("backAfterDeath");
} }
if (!ess.getSettings().areDeathMessagesEnabled()) { if (!ess.getSettings().areDeathMessagesEnabled()) {
event.setDeathMessage(""); event.setDeathMessage("");

View File

@ -6,6 +6,8 @@ import com.earth2me.essentials.textreader.IText;
import com.earth2me.essentials.textreader.KeywordReplacer; import com.earth2me.essentials.textreader.KeywordReplacer;
import com.earth2me.essentials.textreader.TextInput; import com.earth2me.essentials.textreader.TextInput;
import com.earth2me.essentials.textreader.TextPager; import com.earth2me.essentials.textreader.TextPager;
import com.earth2me.essentials.utils.AdventureUtil;
import com.earth2me.essentials.utils.CommonPlaceholders;
import com.earth2me.essentials.utils.DateUtil; import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.FormatUtil; import com.earth2me.essentials.utils.FormatUtil;
import com.earth2me.essentials.utils.LocationUtil; import com.earth2me.essentials.utils.LocationUtil;
@ -18,6 +20,7 @@ import net.ess3.provider.CommandSendListenerProvider;
import net.ess3.provider.providers.BukkitCommandSendListenerProvider; import net.ess3.provider.providers.BukkitCommandSendListenerProvider;
import net.ess3.provider.providers.PaperCommandSendListenerProvider; import net.ess3.provider.providers.PaperCommandSendListenerProvider;
import net.essentialsx.api.v2.events.AsyncUserDataLoadEvent; import net.essentialsx.api.v2.events.AsyncUserDataLoadEvent;
import net.kyori.adventure.text.Component;
import org.bukkit.BanEntry; import org.bukkit.BanEntry;
import org.bukkit.BanList; import org.bukkit.BanList;
import org.bukkit.GameMode; import org.bukkit.GameMode;
@ -75,7 +78,7 @@ import java.util.function.Predicate;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tlLiteral;
public class EssentialsPlayerListener implements Listener, FakeAccessor { public class EssentialsPlayerListener implements Listener, FakeAccessor {
private final transient IEssentials ess; private final transient IEssentials ess;
@ -173,12 +176,20 @@ public class EssentialsPlayerListener implements Listener, FakeAccessor {
final String dateDiff = user.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(user.getMuteTimeout()) : null; final String dateDiff = user.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(user.getMuteTimeout()) : null;
if (dateDiff == null) { if (dateDiff == null) {
user.sendMessage(user.hasMuteReason() ? tl("voiceSilencedReason", user.getMuteReason()) : tl("voiceSilenced")); if (user.hasMuteReason()) {
user.sendTl("voiceSilencedReason", user.getMuteReason());
} else {
user.sendTl("voiceSilenced");
}
} else { } else {
user.sendMessage(user.hasMuteReason() ? tl("voiceSilencedReasonTime", dateDiff, user.getMuteReason()) : tl("voiceSilencedTime", dateDiff)); if (user.hasMuteReason()) {
user.sendTl("voiceSilencedReasonTime", dateDiff, user.getMuteReason());
} else {
user.sendTl("voiceSilencedTime", dateDiff);
}
} }
ess.getLogger().info(tl("mutedUserSpeaks", user.getName(), event.getMessage())); ess.getLogger().info(AdventureUtil.miniToLegacy(tlLiteral("mutedUserSpeaks", user.getName(), event.getMessage())));
} }
try { try {
final Iterator<Player> it = event.getRecipients().iterator(); final Iterator<Player> it = event.getRecipients().iterator();
@ -423,7 +434,7 @@ public class EssentialsPlayerListener implements Listener, FakeAccessor {
if (!ess.getSettings().isCommandDisabled("mail") && user.isAuthorized("essentials.mail")) { if (!ess.getSettings().isCommandDisabled("mail") && user.isAuthorized("essentials.mail")) {
if (user.getUnreadMailAmount() == 0) { if (user.getUnreadMailAmount() == 0) {
if (ess.getSettings().isNotifyNoNewMail()) { if (ess.getSettings().isNotifyNoNewMail()) {
user.sendMessage(tl("noNewMail")); // Only notify if they want us to. user.sendTl("noNewMail"); // Only notify if they want us to.
} }
} else { } else {
user.notifyOfMail(); user.notifyOfMail();
@ -432,8 +443,8 @@ public class EssentialsPlayerListener implements Listener, FakeAccessor {
if (user.isAuthorized("essentials.updatecheck")) { if (user.isAuthorized("essentials.updatecheck")) {
ess.runTaskAsynchronously(() -> { ess.runTaskAsynchronously(() -> {
for (String str : ess.getUpdateChecker().getVersionMessages(false, false)) { for (final Component component : ess.getUpdateChecker().getVersionMessages(false, false, user.getSource())) {
user.sendMessage(str); user.sendComponent(component);
} }
}); });
} }
@ -444,7 +455,7 @@ public class EssentialsPlayerListener implements Listener, FakeAccessor {
user.getBase().setAllowFlight(true); user.getBase().setAllowFlight(true);
user.getBase().setFlying(true); user.getBase().setFlying(true);
if (ess.getSettings().isSendFlyEnableOnJoin()) { if (ess.getSettings().isSendFlyEnableOnJoin()) {
user.getBase().sendMessage(tl("flyMode", tl("enabled"), user.getDisplayName())); user.sendTl("flyMode", CommonPlaceholders.enableDisable(user.getSource(), true), user.getDisplayName());
} }
} }
} }
@ -534,14 +545,14 @@ public class EssentialsPlayerListener implements Listener, FakeAccessor {
final Date banExpiry = banEntry.getExpiration(); final Date banExpiry = banEntry.getExpiration();
if (banExpiry != null) { if (banExpiry != null) {
final String expiry = DateUtil.formatDateDiff(banExpiry.getTime()); final String expiry = DateUtil.formatDateDiff(banExpiry.getTime());
event.setKickMessage(tl("tempbanJoin", expiry, banEntry.getReason())); event.setKickMessage(tlLiteral("tempbanJoin", expiry, banEntry.getReason()));
} else { } else {
event.setKickMessage(tl("banJoin", banEntry.getReason())); event.setKickMessage(tlLiteral("banJoin", banEntry.getReason()));
} }
} else { } else {
banEntry = ess.getServer().getBanList(BanList.Type.IP).getBanEntry(event.getAddress().getHostAddress()); banEntry = ess.getServer().getBanList(BanList.Type.IP).getBanEntry(event.getAddress().getHostAddress());
if (banEntry != null) { if (banEntry != null) {
event.setKickMessage(tl("banIpJoin", banEntry.getReason())); event.setKickMessage(tlLiteral("banIpJoin", banEntry.getReason()));
} }
} }
} }
@ -557,7 +568,7 @@ public class EssentialsPlayerListener implements Listener, FakeAccessor {
return; return;
} }
if (ess.getSettings().isCustomServerFullMessage()) { if (ess.getSettings().isCustomServerFullMessage()) {
event.disallow(Result.KICK_FULL, tl("serverFull")); event.disallow(Result.KICK_FULL, tlLiteral("serverFull"));
} }
} }
} }
@ -631,11 +642,10 @@ public class EssentialsPlayerListener implements Listener, FakeAccessor {
if (!user.isAuthorized("essentials.chat.spy.exempt")) { if (!user.isAuthorized("essentials.chat.spy.exempt")) {
for (final User spyer : ess.getOnlineUsers()) { for (final User spyer : ess.getOnlineUsers()) {
if (spyer.isSocialSpyEnabled() && !player.equals(spyer.getBase())) { if (spyer.isSocialSpyEnabled() && !player.equals(spyer.getBase())) {
if (user.isMuted() && ess.getSettings().getSocialSpyListenMutedPlayers()) { final Component base = (user.isMuted() && ess.getSettings().getSocialSpyListenMutedPlayers())
spyer.sendMessage(tl("socialSpyMutedPrefix") + player.getDisplayName() + ": " + event.getMessage()); ? spyer.tlComponent("socialSpyMutedPrefix")
} else { : spyer.tlComponent("socialSpyPrefix");
spyer.sendMessage(tl("socialSpyPrefix") + player.getDisplayName() + ": " + event.getMessage()); spyer.sendComponent(base.append(AdventureUtil.legacyToAdventure(player.getDisplayName())).append(Component.text(": " + event.getMessage())));
}
} }
} }
} }
@ -647,11 +657,19 @@ public class EssentialsPlayerListener implements Listener, FakeAccessor {
event.setCancelled(true); event.setCancelled(true);
final String dateDiff = user.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(user.getMuteTimeout()) : null; final String dateDiff = user.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(user.getMuteTimeout()) : null;
if (dateDiff == null) { if (dateDiff == null) {
player.sendMessage(user.hasMuteReason() ? tl("voiceSilencedReason", user.getMuteReason()) : tl("voiceSilenced")); if (user.hasMuteReason()) {
user.sendTl("voiceSilencedReason", user.getMuteReason());
} else {
user.sendTl("voiceSilenced");
}
} else { } else {
player.sendMessage(user.hasMuteReason() ? tl("voiceSilencedReasonTime", dateDiff, user.getMuteReason()) : tl("voiceSilencedTime", dateDiff)); if (user.hasMuteReason()) {
user.sendTl("voiceSilencedReasonTime", dateDiff, user.getMuteReason());
} else {
user.sendTl("voiceSilencedTime", dateDiff);
}
} }
ess.getLogger().info(tl("mutedUserSpeaks", player.getName(), event.getMessage())); ess.getLogger().info(AdventureUtil.miniToLegacy(tlLiteral("mutedUserSpeaks", player.getName(), event.getMessage())));
return; return;
} }
@ -696,7 +714,7 @@ public class EssentialsPlayerListener implements Listener, FakeAccessor {
// User's current cooldown hasn't expired, inform and terminate cooldown code. // User's current cooldown hasn't expired, inform and terminate cooldown code.
if (entry.getValue() > System.currentTimeMillis()) { if (entry.getValue() > System.currentTimeMillis()) {
final String commandCooldownTime = DateUtil.formatDateDiff(entry.getValue()); final String commandCooldownTime = DateUtil.formatDateDiff(entry.getValue());
user.sendMessage(tl("commandCooldown", commandCooldownTime)); user.sendTl("commandCooldown", commandCooldownTime);
cooldownFound = true; cooldownFound = true;
event.setCancelled(true); event.setCancelled(true);
break; break;
@ -759,11 +777,11 @@ public class EssentialsPlayerListener implements Listener, FakeAccessor {
if (ess.getSettings().getNoGodWorlds().contains(newWorld) && user.isGodModeEnabledRaw()) { if (ess.getSettings().getNoGodWorlds().contains(newWorld) && user.isGodModeEnabledRaw()) {
// Player god mode is never disabled in order to retain it when changing worlds once more. // Player god mode is never disabled in order to retain it when changing worlds once more.
// With that said, players will still take damage as per the result of User#isGodModeEnabled() // With that said, players will still take damage as per the result of User#isGodModeEnabled()
user.sendMessage(tl("noGodWorldWarning")); user.sendTl("noGodWorldWarning");
} }
if (!user.getWorld().getName().equals(newWorld)) { if (!user.getWorld().getName().equals(newWorld)) {
user.sendMessage(tl("currentWorld", newWorld)); user.sendTl("currentWorld", newWorld);
} }
if (user.isVanished()) { if (user.isVanished()) {
user.setVanished(user.isAuthorized("essentials.vanish")); user.setVanished(user.isAuthorized("essentials.vanish"));
@ -785,7 +803,7 @@ public class EssentialsPlayerListener implements Listener, FakeAccessor {
player.getBase().setBedSpawnLocation(event.getClickedBlock().getLocation()); player.getBase().setBedSpawnLocation(event.getClickedBlock().getLocation());
// In 1.15 and above, vanilla sends its own bed spawn message. // In 1.15 and above, vanilla sends its own bed spawn message.
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_15_R01)) { if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_15_R01)) {
player.sendMessage(tl("bedSet", player.getLocation().getWorld().getName(), player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ())); player.sendTl("bedSet", player.getLocation().getWorld().getName(), player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ());
} }
} }
} }

View File

@ -5,12 +5,14 @@ import com.earth2me.essentials.config.EssentialsConfiguration;
import com.earth2me.essentials.config.EssentialsUserConfiguration; import com.earth2me.essentials.config.EssentialsUserConfiguration;
import com.earth2me.essentials.craftbukkit.BanLookup; import com.earth2me.essentials.craftbukkit.BanLookup;
import com.earth2me.essentials.userstorage.ModernUUIDCache; import com.earth2me.essentials.userstorage.ModernUUIDCache;
import com.earth2me.essentials.utils.AdventureUtil;
import com.earth2me.essentials.utils.StringUtil; import com.earth2me.essentials.utils.StringUtil;
import com.google.common.base.Charsets; import com.google.common.base.Charsets;
import com.google.common.io.Files; import com.google.common.io.Files;
import com.google.gson.reflect.TypeToken; import com.google.gson.reflect.TypeToken;
import net.ess3.api.IEssentials; import net.ess3.api.IEssentials;
import net.essentialsx.api.v2.services.mail.MailMessage; import net.essentialsx.api.v2.services.mail.MailMessage;
import nu.studer.java.util.OrderedProperties;
import org.bukkit.BanList; import org.bukkit.BanList;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
@ -49,7 +51,7 @@ import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tlLiteral;
public class EssentialsUpgrade { public class EssentialsUpgrade {
public static final FileFilter YML_FILTER = pathname -> pathname.isFile() && pathname.getName().endsWith(".yml"); public static final FileFilter YML_FILTER = pathname -> pathname.isFile() && pathname.getName().endsWith(".yml");
@ -493,7 +495,7 @@ public class EssentialsUpgrade {
doneFile.setProperty("move" + name + "ToFile", true); doneFile.setProperty("move" + name + "ToFile", true);
doneFile.save(); doneFile.save();
} catch (final IOException e) { } catch (final IOException e) {
ess.getLogger().log(Level.SEVERE, tl("upgradingFilesError"), e); ess.getLogger().log(Level.SEVERE, AdventureUtil.miniToLegacy(tlLiteral("upgradingFilesError")), e);
} }
} }
@ -528,10 +530,10 @@ public class EssentialsUpgrade {
bWriter.close(); bWriter.close();
if (needUpdate) { if (needUpdate) {
if (!file.renameTo(new File(file.getParentFile(), file.getName().concat("." + System.currentTimeMillis() + ".upgradebackup")))) { if (!file.renameTo(new File(file.getParentFile(), file.getName().concat("." + System.currentTimeMillis() + ".upgradebackup")))) {
throw new Exception(tl("configFileMoveError")); throw new Exception(tlLiteral("configFileMoveError"));
} }
if (!tempFile.renameTo(file)) { if (!tempFile.renameTo(file)) {
throw new Exception(tl("configFileRenameError")); throw new Exception(tlLiteral("configFileRenameError"));
} }
} else { } else {
tempFile.delete(); tempFile.delete();
@ -656,15 +658,15 @@ public class EssentialsUpgrade {
final File tmpFile = new File(listOfFile.getParentFile(), sanitizedFilename + ".tmp"); final File tmpFile = new File(listOfFile.getParentFile(), sanitizedFilename + ".tmp");
final File newFile = new File(listOfFile.getParentFile(), sanitizedFilename); final File newFile = new File(listOfFile.getParentFile(), sanitizedFilename);
if (!listOfFile.renameTo(tmpFile)) { if (!listOfFile.renameTo(tmpFile)) {
ess.getLogger().log(Level.WARNING, tl("userdataMoveError", filename, sanitizedFilename)); ess.getLogger().log(Level.WARNING, AdventureUtil.miniToLegacy(tlLiteral("userdataMoveError", filename, sanitizedFilename)));
continue; continue;
} }
if (newFile.exists()) { if (newFile.exists()) {
ess.getLogger().log(Level.WARNING, tl("duplicatedUserdata", filename, sanitizedFilename)); ess.getLogger().log(Level.WARNING, AdventureUtil.miniToLegacy(tlLiteral("duplicatedUserdata", filename, sanitizedFilename)));
continue; continue;
} }
if (!tmpFile.renameTo(newFile)) { if (!tmpFile.renameTo(newFile)) {
ess.getLogger().log(Level.WARNING, tl("userdataMoveBackError", sanitizedFilename, sanitizedFilename)); ess.getLogger().log(Level.WARNING, AdventureUtil.miniToLegacy(tlLiteral("userdataMoveBackError", sanitizedFilename, sanitizedFilename)));
} }
} }
doneFile.setProperty("sanitizeAllUserFilenames", true); doneFile.setProperty("sanitizeAllUserFilenames", true);
@ -742,7 +744,7 @@ public class EssentialsUpgrade {
config.setProperty(entry.getKey(), loc); config.setProperty(entry.getKey(), loc);
} }
if (!configFile.renameTo(new File(ess.getDataFolder(), "spawn.yml.old"))) { if (!configFile.renameTo(new File(ess.getDataFolder(), "spawn.yml.old"))) {
throw new Exception(tl("fileRenameError", "spawn.yml")); throw new Exception(tlLiteral("fileRenameError", "spawn.yml"));
} }
config.blockingSave(); config.blockingSave();
} }
@ -770,7 +772,7 @@ public class EssentialsUpgrade {
config.setProperty(entry.getKey(), loc); config.setProperty(entry.getKey(), loc);
} }
if (!configFile.renameTo(new File(ess.getDataFolder(), "jail.yml.old"))) { if (!configFile.renameTo(new File(ess.getDataFolder(), "jail.yml.old"))) {
throw new Exception(tl("fileRenameError", "jail.yml")); throw new Exception(tlLiteral("fileRenameError", "jail.yml"));
} }
config.blockingSave(); config.blockingSave();
} }
@ -986,6 +988,60 @@ public class EssentialsUpgrade {
} }
} }
public void upgradeLang() {
if (doneFile.getBoolean("updateLegacyToAdventure", false)) {
return;
}
ess.getLogger().log(Level.WARNING, "Beginning Adventure locale file conversion.");
try {
final File dataFolder = ess.getDataFolder();
if (!dataFolder.exists() || !dataFolder.isDirectory()) {
return;
}
final File backDir = new File(dataFolder, "msg-backups-" + System.currentTimeMillis());
if (backDir.exists() || !backDir.mkdir()) {
ess.getLogger().log(Level.SEVERE, "Unable to make msg-backups dir?!");
return;
}
final File messagesDir = new File(dataFolder, "messages");
//noinspection ResultOfMethodCallIgnored
messagesDir.mkdir();
final File[] files = dataFolder.listFiles();
boolean isThereAtLeastOneBackup = false;
if (files != null) {
for (final File file : files) {
if (file.getName().endsWith(".properties")) {
final File newFile = new File(messagesDir, file.getName());
final File backup = new File(backDir, file.getName());
Files.move(file, backup);
isThereAtLeastOneBackup = true;
final OrderedProperties properties = new OrderedProperties();
properties.load(Files.newReader(backup, Charsets.UTF_8));
for (final String key : properties.stringPropertyNames()) {
final String value = properties.getProperty(key);
properties.setProperty(key, AdventureUtil.legacyToMini(AdventureUtil.miniMessage().escapeTags(value), true));
}
properties.store(Files.newWriter(newFile, Charsets.UTF_8), null);
}
}
}
if (!isThereAtLeastOneBackup) {
backDir.delete();
}
doneFile.setProperty("updateLegacyToAdventure", true);
doneFile.save();
} catch (final Throwable e) {
ess.getLogger().log(Level.SEVERE, "Error while upgrading custom locales", e);
}
}
public void beforeSettings() { public void beforeSettings() {
if (!ess.getDataFolder().exists()) { if (!ess.getDataFolder().exists()) {
ess.getDataFolder().mkdirs(); ess.getDataFolder().mkdirs();

View File

@ -1,6 +1,8 @@
package com.earth2me.essentials; package com.earth2me.essentials;
import com.earth2me.essentials.utils.AdventureUtil;
import net.ess3.api.IEssentials; import net.ess3.api.IEssentials;
import org.jetbrains.annotations.NotNull;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
@ -13,25 +15,34 @@ import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.text.MessageFormat; import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.MissingResourceException; import java.util.MissingResourceException;
import java.util.PropertyResourceBundle; import java.util.PropertyResourceBundle;
import java.util.ResourceBundle; import java.util.ResourceBundle;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Function;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public class I18n implements net.ess3.api.II18n { public class I18n implements net.ess3.api.II18n {
private static final String MESSAGES = "messages"; private static final String MESSAGES = "messages";
private static final Pattern NODOUBLEMARK = Pattern.compile("''"); private static final Pattern NODOUBLEMARK = Pattern.compile("''");
private static final ExecutorService BUNDLE_LOADER_EXECUTOR = Executors.newFixedThreadPool(2);
private static final ResourceBundle NULL_BUNDLE = new ResourceBundle() { private static final ResourceBundle NULL_BUNDLE = new ResourceBundle() {
@SuppressWarnings("NullableProblems")
public Enumeration<String> getKeys() { public Enumeration<String> getKeys() {
return null; return null;
} }
protected Object handleGetObject(final String key) { protected Object handleGetObject(final @NotNull String key) {
return null; return null;
} }
}; };
@ -40,30 +51,53 @@ public class I18n implements net.ess3.api.II18n {
private final transient ResourceBundle defaultBundle; private final transient ResourceBundle defaultBundle;
private final transient IEssentials ess; private final transient IEssentials ess;
private transient Locale currentLocale = defaultLocale; private transient Locale currentLocale = defaultLocale;
private transient ResourceBundle customBundle; private final transient Map<Locale, ResourceBundle> loadedBundles = new ConcurrentHashMap<>();
private final transient List<Locale> loadingBundles = new ArrayList<>();
private transient ResourceBundle localeBundle; private transient ResourceBundle localeBundle;
private transient Map<String, MessageFormat> messageFormatCache = new HashMap<>(); private final transient Map<Locale, Map<String, MessageFormat>> messageFormatCache = new HashMap<>();
public I18n(final IEssentials ess) { public I18n(final IEssentials ess) {
this.ess = ess; this.ess = ess;
defaultBundle = ResourceBundle.getBundle(MESSAGES, Locale.ENGLISH, new UTF8PropertiesControl()); defaultBundle = ResourceBundle.getBundle(MESSAGES, Locale.ENGLISH, new UTF8PropertiesControl());
localeBundle = defaultBundle; localeBundle = defaultBundle;
customBundle = NULL_BUNDLE;
} }
public static String tl(final String string, final Object... objects) { /**
* Translates a message using the server's configured locale.
* @param tlKey The translation key.
* @param objects Translation parameters, if applicable. Note: by default, these will not be parsed for MiniMessage.
* @return The translated message.
* @see AdventureUtil#parsed(String)
*/
public static String tlLiteral(final String tlKey, final Object... objects) {
if (instance == null) {
return "";
}
return tlLocale(instance.currentLocale, tlKey, objects);
}
/**
* Translates a message using the provided locale.
* @param locale The locale to translate the key to.
* @param tlKey The translation key.
* @param objects Translation parameters, if applicable. Note: by default, these will not be parsed for MiniMessage.
* @return The translated message.
* @see AdventureUtil#parsed(String)
*/
public static String tlLocale(final Locale locale, final String tlKey, final Object... objects) {
if (instance == null) { if (instance == null) {
return ""; return "";
} }
if (objects.length == 0) { if (objects.length == 0) {
return NODOUBLEMARK.matcher(instance.translate(string)).replaceAll("'"); return NODOUBLEMARK.matcher(instance.translate(locale, tlKey)).replaceAll("'");
} else { } else {
return instance.format(string, objects); return instance.format(tlKey, objects);
} }
} }
public static String capitalCase(final String input) { public static String capitalCase(final String input) {
return input == null || input.length() == 0 ? input : input.toUpperCase(Locale.ENGLISH).charAt(0) + input.toLowerCase(Locale.ENGLISH).substring(1); return input == null || input.isEmpty() ? input : input.toUpperCase(Locale.ENGLISH).charAt(0) + input.toLowerCase(Locale.ENGLISH).substring(1);
} }
public void onEnable() { public void onEnable() {
@ -79,10 +113,44 @@ public class I18n implements net.ess3.api.II18n {
return currentLocale; return currentLocale;
} }
private String translate(final String string) { /**
* Returns the {@link ResourceBundle} for the given {@link Locale}, if loaded. If a bundle is requested which is
* not loaded, it will be loaded asynchronously and the default bundle will be returned in the meantime.
*/
private ResourceBundle getBundle(final Locale locale) {
if (loadedBundles.containsKey(locale)) {
return loadedBundles.get(locale);
} else {
synchronized (loadingBundles) {
if (!loadingBundles.contains(locale)) {
loadingBundles.add(locale);
BUNDLE_LOADER_EXECUTOR.submit(() -> {
ResourceBundle bundle;
try {
bundle = ResourceBundle.getBundle(MESSAGES, locale, new FileResClassLoader(I18n.class.getClassLoader(), ess), new UTF8PropertiesControl());
} catch (MissingResourceException ex) {
try {
bundle = ResourceBundle.getBundle(MESSAGES, locale, new UTF8PropertiesControl());
} catch (MissingResourceException ex2) {
bundle = NULL_BUNDLE;
}
}
loadedBundles.put(locale, bundle);
synchronized (loadingBundles) {
loadingBundles.remove(locale);
}
});
}
}
return defaultBundle;
}
}
private String translate(final Locale locale, final String string) {
try { try {
try { try {
return customBundle.getString(string); return getBundle(locale).getString(string);
} catch (final MissingResourceException ex) { } catch (final MissingResourceException ex) {
return localeBundle.getString(string); return localeBundle.getString(string);
} }
@ -94,37 +162,55 @@ public class I18n implements net.ess3.api.II18n {
} }
} }
public String format(final String string, final Object... objects) { private String format(final String string, final Object... objects) {
String format = translate(string); return format(currentLocale, string, objects);
MessageFormat messageFormat = messageFormatCache.get(format); }
private String format(final Locale locale, final String string, final Object... objects) {
String format = translate(locale, string);
MessageFormat messageFormat = messageFormatCache.computeIfAbsent(locale, l -> new HashMap<>()).get(format);
if (messageFormat == null) { if (messageFormat == null) {
try { try {
messageFormat = new MessageFormat(format); messageFormat = new MessageFormat(format);
} catch (final IllegalArgumentException e) { } catch (final IllegalArgumentException e) {
ess.getLogger().log(Level.SEVERE, "Invalid Translation key for '" + string + "': " + e.getMessage()); ess.getLogger().log(Level.SEVERE, "Invalid Translation key for '" + string + "': " + e.getMessage());
format = format.replaceAll("\\{(\\D*?)\\}", "\\[$1\\]"); format = format.replaceAll("\\{(\\D*?)}", "\\[$1\\]");
messageFormat = new MessageFormat(format); messageFormat = new MessageFormat(format);
} }
messageFormatCache.put(format, messageFormat); messageFormatCache.get(locale).put(format, messageFormat);
} }
return messageFormat.format(objects).replace(' ', ' '); // replace nbsp with a space
final Object[] processedArgs = mutateArgs(objects, arg -> {
final String str = arg instanceof AdventureUtil.ParsedPlaceholder ? arg.toString() : AdventureUtil.miniMessage().escapeTags(arg.toString());
return AdventureUtil.legacyToMini(str);
});
return messageFormat.format(processedArgs).replace(' ', ' '); // replace nbsp with a space
}
public static Object[] mutateArgs(final Object[] objects, final Function<Object, String> mutator) {
final Object[] args = new Object[objects.length];
for (int i = 0; i < objects.length; i++) {
final Object object = objects[i];
// MessageFormat will format these itself, troll face.
if (object instanceof Number || object instanceof Date || object == null) {
args[i] = object;
continue;
}
args[i] = mutator.apply(object);
}
return args;
} }
public void updateLocale(final String loc) { public void updateLocale(final String loc) {
if (loc != null && !loc.isEmpty()) { if (loc != null && !loc.isEmpty()) {
final String[] parts = loc.split("[_\\.]"); currentLocale = getLocale(loc);
if (parts.length == 1) {
currentLocale = new Locale(parts[0]);
}
if (parts.length == 2) {
currentLocale = new Locale(parts[0], parts[1]);
}
if (parts.length == 3) {
currentLocale = new Locale(parts[0], parts[1], parts[2]);
}
} }
ResourceBundle.clearCache(); ResourceBundle.clearCache();
messageFormatCache = new HashMap<>(); loadedBundles.clear();
messageFormatCache.clear();
ess.getLogger().log(Level.INFO, String.format("Using locale %s", currentLocale.toString())); ess.getLogger().log(Level.INFO, String.format("Using locale %s", currentLocale.toString()));
try { try {
@ -132,28 +218,41 @@ public class I18n implements net.ess3.api.II18n {
} catch (final MissingResourceException ex) { } catch (final MissingResourceException ex) {
localeBundle = NULL_BUNDLE; localeBundle = NULL_BUNDLE;
} }
}
try { public static Locale getLocale(final String loc) {
customBundle = ResourceBundle.getBundle(MESSAGES, currentLocale, new FileResClassLoader(I18n.class.getClassLoader(), ess), new UTF8PropertiesControl()); if (loc == null || loc.isEmpty()) {
} catch (final MissingResourceException ex) { return instance.currentLocale;
customBundle = NULL_BUNDLE;
} }
final String[] parts = loc.split("[_.]");
if (parts.length == 1) {
return new Locale(parts[0]);
}
if (parts.length == 2) {
return new Locale(parts[0], parts[1]);
}
if (parts.length == 3) {
return new Locale(parts[0], parts[1], parts[2]);
}
return instance.currentLocale;
} }
/** /**
* Attempts to load properties files from the plugin directory before falling back to the jar. * Attempts to load properties files from the plugin directory before falling back to the jar.
*/ */
private static class FileResClassLoader extends ClassLoader { private static class FileResClassLoader extends ClassLoader {
private final transient File dataFolder; private final transient File messagesFolder;
FileResClassLoader(final ClassLoader classLoader, final IEssentials ess) { FileResClassLoader(final ClassLoader classLoader, final IEssentials ess) {
super(classLoader); super(classLoader);
this.dataFolder = ess.getDataFolder(); this.messagesFolder = new File(ess.getDataFolder(), "messages");
//noinspection ResultOfMethodCallIgnored
this.messagesFolder.mkdirs();
} }
@Override @Override
public URL getResource(final String string) { public URL getResource(final String string) {
final File file = new File(dataFolder, string); final File file = new File(messagesFolder, string);
if (file.exists()) { if (file.exists()) {
try { try {
return file.toURI().toURL(); return file.toURI().toURL();
@ -165,7 +264,7 @@ public class I18n implements net.ess3.api.II18n {
@Override @Override
public InputStream getResourceAsStream(final String string) { public InputStream getResourceAsStream(final String string) {
final File file = new File(dataFolder, string); final File file = new File(messagesFolder, string);
if (file.exists()) { if (file.exists()) {
try { try {
return new FileInputStream(file); return new FileInputStream(file);
@ -207,5 +306,13 @@ public class I18n implements net.ess3.api.II18n {
} }
return bundle; return bundle;
} }
@Override
public Locale getFallbackLocale(String baseName, Locale locale) {
if (baseName == null || locale == null) {
throw new NullPointerException();
}
return null;
}
} }
} }

View File

@ -15,6 +15,7 @@ import net.ess3.provider.ItemUnbreakableProvider;
import net.ess3.provider.KnownCommandsProvider; import net.ess3.provider.KnownCommandsProvider;
import net.ess3.provider.MaterialTagProvider; import net.ess3.provider.MaterialTagProvider;
import net.ess3.provider.PersistentDataProvider; import net.ess3.provider.PersistentDataProvider;
import net.ess3.provider.PlayerLocaleProvider;
import net.ess3.provider.SerializationProvider; import net.ess3.provider.SerializationProvider;
import net.ess3.provider.ServerStateProvider; import net.ess3.provider.ServerStateProvider;
import net.ess3.provider.SignDataProvider; import net.ess3.provider.SignDataProvider;
@ -80,6 +81,16 @@ public interface IEssentials extends Plugin {
int broadcastMessage(String permission, String message); int broadcastMessage(String permission, String message);
void broadcastTl(String tlKey, Object... args);
void broadcastTl(IUser sender, String tlKey, Object... args);
void broadcastTl(IUser sender, String permission, String tlKey, Object... args);
void broadcastTl(IUser sender, Predicate<IUser> shouldExclude, String tlKey, Object... args);
void broadcastTl(IUser sender, Predicate<IUser> shouldExclude, boolean parseKeywords, String tlKey, Object... args);
ISettings getSettings(); ISettings getSettings();
BukkitScheduler getScheduler(); BukkitScheduler getScheduler();
@ -170,5 +181,7 @@ public interface IEssentials extends Plugin {
SignDataProvider getSignDataProvider(); SignDataProvider getSignDataProvider();
PlayerLocaleProvider getPlayerLocaleProvider();
PluginCommand getPluginCommand(String cmd); PluginCommand getPluginCommand(String cmd);
} }

View File

@ -3,6 +3,7 @@ package com.earth2me.essentials;
import com.earth2me.essentials.commands.IEssentialsCommand; import com.earth2me.essentials.commands.IEssentialsCommand;
import com.earth2me.essentials.signs.EssentialsSign; import com.earth2me.essentials.signs.EssentialsSign;
import com.earth2me.essentials.textreader.IText; import com.earth2me.essentials.textreader.IText;
import net.kyori.adventure.text.minimessage.tag.Tag;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.spongepowered.configurate.CommentedConfigurationNode; import org.spongepowered.configurate.CommentedConfigurationNode;
@ -81,6 +82,8 @@ public interface ISettings extends IConf {
String getLocale(); String getLocale();
boolean isPerPlayerLocale();
String getNewbieSpawn(); String getNewbieSpawn();
String getNicknamePrefix(); String getNicknamePrefix();
@ -408,6 +411,10 @@ public interface ISettings extends IConf {
int getMaxItemLore(); int getMaxItemLore();
Tag getPrimaryColor();
Tag getSecondaryColor();
enum KeepInvPolicy { enum KeepInvPolicy {
KEEP, KEEP,
DELETE, DELETE,

View File

@ -8,6 +8,8 @@ import net.ess3.api.MaxMoneyException;
import net.ess3.api.events.AfkStatusChangeEvent; import net.ess3.api.events.AfkStatusChangeEvent;
import net.essentialsx.api.v2.services.mail.MailMessage; import net.essentialsx.api.v2.services.mail.MailMessage;
import net.essentialsx.api.v2.services.mail.MailSender; import net.essentialsx.api.v2.services.mail.MailSender;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.ComponentLike;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.Block; import org.bukkit.block.Block;
@ -15,7 +17,6 @@ import org.bukkit.entity.Player;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@ -142,6 +143,14 @@ public interface IUser {
void sendMessage(String message); void sendMessage(String message);
void sendComponent(ComponentLike component);
Component tlComponent(String tlKey, Object... args);
String playerTl(String tlKey, Object... args);
void sendTl(String tlKey, Object... args);
/* /*
* UserData * UserData
*/ */

View File

@ -3,8 +3,10 @@ package com.earth2me.essentials;
import com.earth2me.essentials.config.ConfigurateUtil; import com.earth2me.essentials.config.ConfigurateUtil;
import com.earth2me.essentials.config.EssentialsConfiguration; import com.earth2me.essentials.config.EssentialsConfiguration;
import com.earth2me.essentials.config.entities.LazyLocation; import com.earth2me.essentials.config.entities.LazyLocation;
import com.earth2me.essentials.utils.AdventureUtil;
import net.ess3.api.IEssentials; import net.ess3.api.IEssentials;
import net.ess3.api.IUser; import net.ess3.api.IUser;
import net.ess3.api.TranslatableException;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType; import org.bukkit.entity.EntityType;
@ -35,7 +37,7 @@ import java.util.Map;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.logging.Level; import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tlLiteral;
public class Jails implements net.ess3.api.IJails { public class Jails implements net.ess3.api.IJails {
private static transient boolean enabled = false; private static transient boolean enabled = false;
@ -102,17 +104,17 @@ public class Jails implements net.ess3.api.IJails {
@Override @Override
public Location getJail(String jailName) throws Exception { public Location getJail(String jailName) throws Exception {
if (jailName == null) { if (jailName == null) {
throw new Exception(tl("jailNotExist")); throw new TranslatableException("jailNotExist");
} }
jailName = jailName.toLowerCase(Locale.ENGLISH); jailName = jailName.toLowerCase(Locale.ENGLISH);
synchronized (jails) { synchronized (jails) {
if (!jails.containsKey(jailName)) { if (!jails.containsKey(jailName)) {
throw new Exception(tl("jailNotExist")); throw new TranslatableException("jailNotExist");
} }
final Location location = jails.get(jailName).location(); final Location location = jails.get(jailName).location();
if (location == null) { if (location == null) {
throw new Exception(tl("jailWorldNotExist")); throw new TranslatableException("jailWorldNotExist");
} }
return location; return location;
} }
@ -293,9 +295,9 @@ public class Jails implements net.ess3.api.IJails {
event.setRespawnLocation(getJail(user.getJail())); event.setRespawnLocation(getJail(user.getJail()));
} catch (final Exception ex) { } catch (final Exception ex) {
if (ess.getSettings().isDebug()) { if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex); ess.getLogger().log(Level.INFO, AdventureUtil.miniToLegacy(tlLiteral("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage())), ex);
} else { } else {
ess.getLogger().log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage())); ess.getLogger().log(Level.INFO, AdventureUtil.miniToLegacy(tlLiteral("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage())));
} }
} }
} }
@ -315,12 +317,12 @@ public class Jails implements net.ess3.api.IJails {
event.setTo(getJail(user.getJail())); event.setTo(getJail(user.getJail()));
} catch (final Exception ex) { } catch (final Exception ex) {
if (ess.getSettings().isDebug()) { if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex); ess.getLogger().log(Level.INFO, AdventureUtil.miniToLegacy(tlLiteral("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage())), ex);
} else { } else {
ess.getLogger().log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage())); ess.getLogger().log(Level.INFO, AdventureUtil.miniToLegacy(tlLiteral("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage())));
} }
} }
user.sendMessage(tl("jailMessage")); user.sendTl("jailMessage");
} }
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
@ -339,13 +341,13 @@ public class Jails implements net.ess3.api.IJails {
final CompletableFuture<Boolean> future = new CompletableFuture<>(); final CompletableFuture<Boolean> future = new CompletableFuture<>();
future.exceptionally(ex -> { future.exceptionally(ex -> {
if (ess.getSettings().isDebug()) { if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex); ess.getLogger().log(Level.INFO, AdventureUtil.miniToLegacy(tlLiteral("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage())), ex);
} else { } else {
ess.getLogger().log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage())); ess.getLogger().log(Level.INFO, AdventureUtil.miniToLegacy(tlLiteral("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage())));
} }
return false; return false;
}); });
future.thenAccept(success -> user.sendMessage(tl("jailMessage"))); future.thenAccept(success -> user.sendTl("jailMessage"));
try { try {
sendToJail(user, user.getJail(), future); sendToJail(user, user.getJail(), future);

View File

@ -6,9 +6,11 @@ import com.earth2me.essentials.craftbukkit.Inventories;
import com.earth2me.essentials.textreader.IText; import com.earth2me.essentials.textreader.IText;
import com.earth2me.essentials.textreader.KeywordReplacer; import com.earth2me.essentials.textreader.KeywordReplacer;
import com.earth2me.essentials.textreader.SimpleTextInput; import com.earth2me.essentials.textreader.SimpleTextInput;
import com.earth2me.essentials.utils.AdventureUtil;
import com.earth2me.essentials.utils.DateUtil; import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.NumberUtil; import com.earth2me.essentials.utils.NumberUtil;
import net.ess3.api.IEssentials; import net.ess3.api.IEssentials;
import net.ess3.api.TranslatableException;
import net.ess3.api.events.KitClaimEvent; import net.ess3.api.events.KitClaimEvent;
import net.essentialsx.api.v2.events.KitPreExpandItemsEvent; import net.essentialsx.api.v2.events.KitPreExpandItemsEvent;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@ -25,7 +27,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.logging.Level; import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tlLiteral;
public class Kit { public class Kit {
final IEssentials ess; final IEssentials ess;
@ -40,7 +42,7 @@ public class Kit {
this.charge = new Trade("kit-" + kitName, new Trade("kit-kit", ess), ess); this.charge = new Trade("kit-" + kitName, new Trade("kit-kit", ess), ess);
if (kit == null) { if (kit == null) {
throw new Exception(tl("kitNotFound")); throw new TranslatableException("kitNotFound");
} }
} }
@ -50,7 +52,7 @@ public class Kit {
public void checkPerms(final User user) throws Exception { public void checkPerms(final User user) throws Exception {
if (!user.isAuthorized("essentials.kits." + kitName)) { if (!user.isAuthorized("essentials.kits." + kitName)) {
throw new Exception(tl("noKitPermission", "essentials.kits." + kitName)); throw new TranslatableException("noKitPermission", "essentials.kits." + kitName);
} }
} }
@ -59,10 +61,10 @@ public class Kit {
if (nextUse == 0L) { if (nextUse == 0L) {
} else if (nextUse < 0L) { } else if (nextUse < 0L) {
user.sendMessage(tl("kitOnce")); user.sendTl("kitOnce");
throw new NoChargeException(); throw new NoChargeException();
} else { } else {
user.sendMessage(tl("kitTimed", DateUtil.formatDateDiff(nextUse))); user.sendTl("kitTimed", DateUtil.formatDateDiff(nextUse));
throw new NoChargeException(); throw new NoChargeException();
} }
} }
@ -96,7 +98,7 @@ public class Kit {
// Make sure delay is valid // Make sure delay is valid
delay = kit.containsKey("delay") ? ((Number) kit.get("delay")).doubleValue() : 0.0d; delay = kit.containsKey("delay") ? ((Number) kit.get("delay")).doubleValue() : 0.0d;
} catch (final Exception e) { } catch (final Exception e) {
throw new Exception(tl("kitError2")); throw new TranslatableException("kitError2");
} }
// When was the last kit used? // When was the last kit used?
@ -130,7 +132,7 @@ public class Kit {
public List<String> getItems() throws Exception { public List<String> getItems() throws Exception {
if (kit == null) { if (kit == null) {
throw new Exception(tl("kitNotFound")); throw new TranslatableException("kitNotFound");
} }
try { try {
final List<String> itemList = new ArrayList<>(); final List<String> itemList = new ArrayList<>();
@ -148,7 +150,7 @@ public class Kit {
throw new Exception("Invalid item list"); throw new Exception("Invalid item list");
} catch (final Exception e) { } catch (final Exception e) {
ess.getLogger().log(Level.WARNING, "Error parsing kit " + kitName + ": " + e.getMessage()); ess.getLogger().log(Level.WARNING, "Error parsing kit " + kitName + ": " + e.getMessage());
throw new Exception(tl("kitError2"), e); throw new TranslatableException(e,"kitError2");
} }
} }
@ -192,7 +194,7 @@ public class Kit {
if (kitItem.startsWith("@")) { if (kitItem.startsWith("@")) {
if (ess.getSerializationProvider() == null) { if (ess.getSerializationProvider() == null) {
ess.getLogger().log(Level.WARNING, tl("kitError3", kitName, user.getName())); ess.getLogger().log(Level.WARNING, AdventureUtil.miniToLegacy(tlLiteral("kitError3", kitName, user.getName())));
continue; continue;
} }
stack = ess.getSerializationProvider().deserializeItem(Base64Coder.decodeLines(kitItem.substring(1))); stack = ess.getSerializationProvider().deserializeItem(Base64Coder.decodeLines(kitItem.substring(1)));
@ -226,7 +228,7 @@ public class Kit {
final ItemStack[] itemArray = itemList.toArray(new ItemStack[0]); final ItemStack[] itemArray = itemList.toArray(new ItemStack[0]);
if (!isDropItemsIfFull && !Inventories.hasSpace(user.getBase(), maxStackSize, autoEquip, itemArray)) { if (!isDropItemsIfFull && !Inventories.hasSpace(user.getBase(), maxStackSize, autoEquip, itemArray)) {
user.sendMessage(tl("kitInvFullNoDrop")); user.sendTl("kitInvFullNoDrop");
return false; return false;
} }
@ -263,12 +265,12 @@ public class Kit {
} }
if (spew) { if (spew) {
user.sendMessage(tl("kitInvFull")); user.sendTl("kitInvFull");
} }
} catch (final Exception e) { } catch (final Exception e) {
user.getBase().updateInventory(); user.getBase().updateInventory();
ess.getLogger().log(Level.WARNING, e.getMessage()); ess.getLogger().log(Level.WARNING, e.getMessage());
throw new Exception(tl("kitError2"), e); throw new TranslatableException(e, "kitError2");
} }
return true; return true;
} }

View File

@ -3,6 +3,7 @@ package com.earth2me.essentials;
import com.earth2me.essentials.config.ConfigurateUtil; import com.earth2me.essentials.config.ConfigurateUtil;
import com.earth2me.essentials.config.EssentialsConfiguration; import com.earth2me.essentials.config.EssentialsConfiguration;
import com.earth2me.essentials.utils.NumberUtil; import com.earth2me.essentials.utils.NumberUtil;
import net.ess3.api.TranslatableException;
import org.spongepowered.configurate.CommentedConfigurationNode; import org.spongepowered.configurate.CommentedConfigurationNode;
import java.io.File; import java.io.File;
@ -14,7 +15,6 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import static com.earth2me.essentials.I18n.capitalCase; import static com.earth2me.essentials.I18n.capitalCase;
import static com.earth2me.essentials.I18n.tl;
public class Kits implements IConf { public class Kits implements IConf {
private final IEssentials ess; private final IEssentials ess;
@ -145,7 +145,7 @@ public class Kits implements IConf {
String name = capitalCase(kitItem); String name = capitalCase(kitItem);
final BigDecimal costPrice = new Trade("kit-" + kitItem.toLowerCase(Locale.ENGLISH), ess).getCommandCost(user); final BigDecimal costPrice = new Trade("kit-" + kitItem.toLowerCase(Locale.ENGLISH), ess).getCommandCost(user);
if (costPrice.signum() > 0) { if (costPrice.signum() > 0) {
cost = tl("kitCost", NumberUtil.displayCurrency(costPrice, ess)); cost = user.playerTl("kitCost", NumberUtil.displayCurrency(costPrice, ess));
} }
final Kit kit = new Kit(kitItem, ess); final Kit kit = new Kit(kitItem, ess);
@ -153,7 +153,7 @@ public class Kits implements IConf {
if (nextUse == -1 && ess.getSettings().isSkippingUsedOneTimeKitsFromKitList()) { if (nextUse == -1 && ess.getSettings().isSkippingUsedOneTimeKitsFromKitList()) {
continue; continue;
} else if (nextUse != 0) { } else if (nextUse != 0) {
name = tl("kitDelay", name); name = user.playerTl("kitDelay", name);
} }
list.append(" ").append(name).append(cost); list.append(" ").append(name).append(cost);
@ -161,7 +161,7 @@ public class Kits implements IConf {
} }
return list.toString().trim(); return list.toString().trim();
} catch (final Exception ex) { } catch (final Exception ex) {
throw new Exception(tl("kitError"), ex); throw new TranslatableException(ex, "kitError");
} }
} }

View File

@ -12,7 +12,7 @@ import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tlLiteral;
public class MailServiceImpl implements MailService { public class MailServiceImpl implements MailService {
private final transient ThreadLocal<SimpleDateFormat> df = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy/MM/dd HH:mm")); private final transient ThreadLocal<SimpleDateFormat> df = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy/MM/dd HH:mm"));
@ -52,10 +52,28 @@ public class MailServiceImpl implements MailService {
public String getMailLine(MailMessage mail) { public String getMailLine(MailMessage mail) {
final String message = mail.getMessage(); final String message = mail.getMessage();
if (mail.isLegacy()) { if (mail.isLegacy()) {
return tl("mailMessage", message); return tlLiteral("mailMessage", message);
} }
final String expire = mail.getTimeExpire() != 0 ? "Timed" : ""; final String expire = mail.getTimeExpire() != 0 ? "Timed" : "";
return tl((mail.isRead() ? "mailFormatNewRead" : "mailFormatNew") + expire, df.get().format(new Date(mail.getTimeSent())), mail.getSenderUsername(), message); return tlLiteral((mail.isRead() ? "mailFormatNewRead" : "mailFormatNew") + expire, df.get().format(new Date(mail.getTimeSent())), mail.getSenderUsername(), message);
}
@Override
public String getMailTlKey(MailMessage message) {
if (message.isLegacy()) {
return "mailMessage";
}
final String expire = message.getTimeExpire() != 0 ? "Timed" : "";
return (message.isRead() ? "mailFormatNewRead" : "mailFormatNew") + expire;
}
@Override
public Object[] getMailTlArgs(MailMessage message) {
if (message.isLegacy()) {
return new Object[] {message.getMessage()};
}
return new Object[] {df.get().format(new Date(message.getTimeSent())), message.getSenderUsername(), message.getMessage()};
} }
} }

View File

@ -1,5 +1,6 @@
package com.earth2me.essentials; package com.earth2me.essentials;
import com.earth2me.essentials.utils.AdventureUtil;
import net.ess3.api.IEssentials; import net.ess3.api.IEssentials;
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
@ -22,7 +23,7 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.logging.Level; import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tlLiteral;
public class ManagedFile { public class ManagedFile {
private static final int BUFFERSIZE = 1024 * 8; private static final int BUFFERSIZE = 1024 * 8;
@ -45,7 +46,7 @@ public class ManagedFile {
try { try {
copyResourceAscii("/" + filename, file); copyResourceAscii("/" + filename, file);
} catch (final IOException ex) { } catch (final IOException ex) {
Essentials.getWrappedLogger().log(Level.SEVERE, tl("itemsCsvNotLoaded", filename), ex); Essentials.getWrappedLogger().log(Level.SEVERE, AdventureUtil.miniToLegacy(tlLiteral("itemsCsvNotLoaded", filename)), ex);
} }
} }
} }

View File

@ -10,6 +10,7 @@ import com.earth2me.essentials.utils.NumberUtil;
import com.earth2me.essentials.utils.VersionUtil; import com.earth2me.essentials.utils.VersionUtil;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
import net.ess3.api.IEssentials; import net.ess3.api.IEssentials;
import net.ess3.api.TranslatableException;
import org.bukkit.Color; import org.bukkit.Color;
import org.bukkit.DyeColor; import org.bukkit.DyeColor;
import org.bukkit.FireworkEffect; import org.bukkit.FireworkEffect;
@ -42,8 +43,6 @@ import java.util.Map;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import static com.earth2me.essentials.I18n.tl;
public class MetaItemStack { public class MetaItemStack {
private static final Map<String, DyeColor> colorMap = new HashMap<>(); private static final Map<String, DyeColor> colorMap = new HashMap<>();
private static final Map<String, FireworkEffect.Type> fireworkShape = new HashMap<>(); private static final Map<String, FireworkEffect.Type> fireworkShape = new HashMap<>();
@ -153,7 +152,7 @@ public class MetaItemStack {
ess.getLogger().log(Level.INFO, "Itemstack is invalid", npe); ess.getLogger().log(Level.INFO, "Itemstack is invalid", npe);
} }
} catch (final NoSuchMethodError nsme) { } catch (final NoSuchMethodError nsme) {
throw new Exception(tl("noMetaJson"), nsme); throw new TranslatableException(nsme, "noMetaJson");
} catch (final Throwable throwable) { } catch (final Throwable throwable) {
throw new Exception(throwable.getMessage(), throwable); throw new Exception(throwable.getMessage(), throwable);
} }
@ -163,19 +162,19 @@ public class MetaItemStack {
} }
if (validFirework) { if (validFirework) {
if (!hasMetaPermission(sender, "firework", true, true, ess)) { if (!hasMetaPermission(sender, "firework", true, true, ess)) {
throw new Exception(tl("noMetaFirework")); throw new TranslatableException("noMetaFirework");
} }
final FireworkEffect effect = builder.build(); final FireworkEffect effect = builder.build();
final FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta(); final FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta();
fmeta.addEffect(effect); fmeta.addEffect(effect);
if (fmeta.getEffects().size() > 1 && !hasMetaPermission(sender, "firework-multiple", true, true, ess)) { if (fmeta.getEffects().size() > 1 && !hasMetaPermission(sender, "firework-multiple", true, true, ess)) {
throw new Exception(tl("multipleCharges")); throw new TranslatableException("multipleCharges");
} }
stack.setItemMeta(fmeta); stack.setItemMeta(fmeta);
} }
if (validFireworkCharge) { if (validFireworkCharge) {
if (!hasMetaPermission(sender, "firework", true, true, ess)) { if (!hasMetaPermission(sender, "firework", true, true, ess)) {
throw new Exception(tl("noMetaFirework")); throw new TranslatableException("noMetaFirework");
} }
final FireworkEffect effect = builder.build(); final FireworkEffect effect = builder.build();
final FireworkEffectMeta meta = (FireworkEffectMeta) stack.getItemMeta(); final FireworkEffectMeta meta = (FireworkEffectMeta) stack.getItemMeta();
@ -221,7 +220,7 @@ public class MetaItemStack {
final String owner = split[1]; final String owner = split[1];
setSkullOwner(ess, stack, owner); setSkullOwner(ess, stack, owner);
} else { } else {
throw new Exception(tl("onlyPlayerSkulls")); throw new TranslatableException("onlyPlayerSkulls");
} }
} else if (split.length > 1 && split[0].equalsIgnoreCase("book") && MaterialUtil.isEditableBook(stack.getType()) && (hasMetaPermission(sender, "book", true, true, ess) || hasMetaPermission(sender, "chapter-" + split[1].toLowerCase(Locale.ENGLISH), true, true, ess))) { } else if (split.length > 1 && split[0].equalsIgnoreCase("book") && MaterialUtil.isEditableBook(stack.getType()) && (hasMetaPermission(sender, "book", true, true, ess) || hasMetaPermission(sender, "chapter-" + split[1].toLowerCase(Locale.ENGLISH), true, true, ess))) {
final BookMeta meta = (BookMeta) stack.getItemMeta(); final BookMeta meta = (BookMeta) stack.getItemMeta();
@ -318,7 +317,7 @@ public class MetaItemStack {
meta.setColor(Color.fromRGB(red, green, blue)); meta.setColor(Color.fromRGB(red, green, blue));
stack.setItemMeta(meta); stack.setItemMeta(meta);
} else { } else {
throw new Exception(tl("leatherSyntax")); throw new TranslatableException("leatherSyntax");
} }
} else { } else {
parseEnchantmentStrings(sender, allowUnsafe, split, ess); parseEnchantmentStrings(sender, allowUnsafe, split, ess);
@ -328,7 +327,7 @@ public class MetaItemStack {
public void addItemFlags(final String string) throws Exception { public void addItemFlags(final String string) throws Exception {
final String[] separate = splitPattern.split(string, 2); final String[] separate = splitPattern.split(string, 2);
if (separate.length != 2) { if (separate.length != 2) {
throw new Exception(tl("invalidItemFlagMeta", string)); throw new TranslatableException("invalidItemFlagMeta", string);
} }
final String[] split = separate[1].split(","); final String[] split = separate[1].split(",");
@ -343,7 +342,7 @@ public class MetaItemStack {
} }
if (meta.getItemFlags().isEmpty()) { if (meta.getItemFlags().isEmpty()) {
throw new Exception(tl("invalidItemFlagMeta", string)); throw new TranslatableException("invalidItemFlagMeta", string);
} }
stack.setItemMeta(meta); stack.setItemMeta(meta);
@ -366,7 +365,7 @@ public class MetaItemStack {
validFireworkCharge = true; validFireworkCharge = true;
primaryColors.add(Color.fromRGB(Integer.decode(color))); primaryColors.add(Color.fromRGB(Integer.decode(color)));
} else { } else {
throw new Exception(tl("invalidFireworkFormat", split[1], split[0])); throw new TranslatableException("invalidFireworkFormat", split[1], split[0]);
} }
} }
builder.withColor(primaryColors); builder.withColor(primaryColors);
@ -376,7 +375,7 @@ public class MetaItemStack {
if (fireworkShape.containsKey(split[1].toUpperCase())) { if (fireworkShape.containsKey(split[1].toUpperCase())) {
finalEffect = fireworkShape.get(split[1].toUpperCase()); finalEffect = fireworkShape.get(split[1].toUpperCase());
} else { } else {
throw new Exception(tl("invalidFireworkFormat", split[1], split[0])); throw new TranslatableException("invalidFireworkFormat", split[1], split[0]);
} }
if (finalEffect != null) { if (finalEffect != null) {
builder.with(finalEffect); builder.with(finalEffect);
@ -390,7 +389,7 @@ public class MetaItemStack {
} else if (hexPattern.matcher(color).matches()) { } else if (hexPattern.matcher(color).matches()) {
fadeColors.add(Color.fromRGB(Integer.decode(color))); fadeColors.add(Color.fromRGB(Integer.decode(color)));
} else { } else {
throw new Exception(tl("invalidFireworkFormat", split[1], split[0])); throw new TranslatableException("invalidFireworkFormat", split[1], split[0]);
} }
} }
if (!fadeColors.isEmpty()) { if (!fadeColors.isEmpty()) {
@ -404,7 +403,7 @@ public class MetaItemStack {
} else if (effect.equalsIgnoreCase("trail")) { } else if (effect.equalsIgnoreCase("trail")) {
builder.trail(true); builder.trail(true);
} else { } else {
throw new Exception(tl("invalidFireworkFormat", split[1], split[0])); throw new TranslatableException("invalidFireworkFormat", split[1], split[0]);
} }
} }
} }
@ -420,13 +419,13 @@ public class MetaItemStack {
if (split[0].equalsIgnoreCase("color") || split[0].equalsIgnoreCase("colour") || (allowShortName && split[0].equalsIgnoreCase("c"))) { if (split[0].equalsIgnoreCase("color") || split[0].equalsIgnoreCase("colour") || (allowShortName && split[0].equalsIgnoreCase("c"))) {
if (validFirework) { if (validFirework) {
if (!hasMetaPermission(sender, "firework", true, true, ess)) { if (!hasMetaPermission(sender, "firework", true, true, ess)) {
throw new Exception(tl("noMetaFirework")); throw new TranslatableException("noMetaFirework");
} }
final FireworkEffect effect = builder.build(); final FireworkEffect effect = builder.build();
final FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta(); final FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta();
fmeta.addEffect(effect); fmeta.addEffect(effect);
if (fmeta.getEffects().size() > 1 && !hasMetaPermission(sender, "firework-multiple", true, true, ess)) { if (fmeta.getEffects().size() > 1 && !hasMetaPermission(sender, "firework-multiple", true, true, ess)) {
throw new Exception(tl("multipleCharges")); throw new TranslatableException("multipleCharges");
} }
stack.setItemMeta(fmeta); stack.setItemMeta(fmeta);
builder = FireworkEffect.builder(); builder = FireworkEffect.builder();
@ -442,7 +441,7 @@ public class MetaItemStack {
validFirework = true; validFirework = true;
primaryColors.add(Color.fromRGB(Integer.decode(color))); primaryColors.add(Color.fromRGB(Integer.decode(color)));
} else { } else {
throw new Exception(tl("invalidFireworkFormat", split[1], split[0])); throw new TranslatableException("invalidFireworkFormat", split[1], split[0]);
} }
} }
builder.withColor(primaryColors); builder.withColor(primaryColors);
@ -452,7 +451,7 @@ public class MetaItemStack {
if (fireworkShape.containsKey(split[1].toUpperCase())) { if (fireworkShape.containsKey(split[1].toUpperCase())) {
finalEffect = fireworkShape.get(split[1].toUpperCase()); finalEffect = fireworkShape.get(split[1].toUpperCase());
} else { } else {
throw new Exception(tl("invalidFireworkFormat", split[1], split[0])); throw new TranslatableException("invalidFireworkFormat", split[1], split[0]);
} }
if (finalEffect != null) { if (finalEffect != null) {
builder.with(finalEffect); builder.with(finalEffect);
@ -466,7 +465,7 @@ public class MetaItemStack {
} else if (hexPattern.matcher(color).matches()) { } else if (hexPattern.matcher(color).matches()) {
fadeColors.add(Color.fromRGB(Integer.decode(color))); fadeColors.add(Color.fromRGB(Integer.decode(color)));
} else { } else {
throw new Exception(tl("invalidFireworkFormat", split[1], split[0])); throw new TranslatableException("invalidFireworkFormat", split[1], split[0]);
} }
} }
if (!fadeColors.isEmpty()) { if (!fadeColors.isEmpty()) {
@ -480,7 +479,7 @@ public class MetaItemStack {
} else if (effect.equalsIgnoreCase("trail")) { } else if (effect.equalsIgnoreCase("trail")) {
builder.trail(true); builder.trail(true);
} else { } else {
throw new Exception(tl("invalidFireworkFormat", split[1], split[0])); throw new TranslatableException("invalidFireworkFormat", split[1], split[0]);
} }
} }
} }
@ -501,10 +500,10 @@ public class MetaItemStack {
if (hasMetaPermission(sender, "potions." + pEffectType.getName().toLowerCase(Locale.ENGLISH), true, false, ess)) { if (hasMetaPermission(sender, "potions." + pEffectType.getName().toLowerCase(Locale.ENGLISH), true, false, ess)) {
validPotionEffect = true; validPotionEffect = true;
} else { } else {
throw new Exception(tl("noPotionEffectPerm", pEffectType.getName().toLowerCase(Locale.ENGLISH))); throw new TranslatableException("noPotionEffectPerm", pEffectType.getName().toLowerCase(Locale.ENGLISH));
} }
} else { } else {
throw new Exception(tl("invalidPotionMeta", split[1])); throw new TranslatableException("invalidPotionMeta", split[1]);
} }
} else if (split[0].equalsIgnoreCase("power") || (allowShortName && split[0].equalsIgnoreCase("p"))) { } else if (split[0].equalsIgnoreCase("power") || (allowShortName && split[0].equalsIgnoreCase("p"))) {
if (NumberUtil.isInt(split[1])) { if (NumberUtil.isInt(split[1])) {
@ -514,21 +513,21 @@ public class MetaItemStack {
power -= 1; power -= 1;
} }
} else { } else {
throw new Exception(tl("invalidPotionMeta", split[1])); throw new TranslatableException("invalidPotionMeta", split[1]);
} }
} else if (split[0].equalsIgnoreCase("amplifier") || (allowShortName && split[0].equalsIgnoreCase("a"))) { } else if (split[0].equalsIgnoreCase("amplifier") || (allowShortName && split[0].equalsIgnoreCase("a"))) {
if (NumberUtil.isInt(split[1])) { if (NumberUtil.isInt(split[1])) {
validPotionPower = true; validPotionPower = true;
power = Integer.parseInt(split[1]); power = Integer.parseInt(split[1]);
} else { } else {
throw new Exception(tl("invalidPotionMeta", split[1])); throw new TranslatableException("invalidPotionMeta", split[1]);
} }
} else if (split[0].equalsIgnoreCase("duration") || (allowShortName && split[0].equalsIgnoreCase("d"))) { } else if (split[0].equalsIgnoreCase("duration") || (allowShortName && split[0].equalsIgnoreCase("d"))) {
if (NumberUtil.isInt(split[1])) { if (NumberUtil.isInt(split[1])) {
validPotionDuration = true; validPotionDuration = true;
duration = Integer.parseInt(split[1]) * 20; //Duration is in ticks by default, converted to seconds duration = Integer.parseInt(split[1]) * 20; //Duration is in ticks by default, converted to seconds
} else { } else {
throw new Exception(tl("invalidPotionMeta", split[1])); throw new TranslatableException("invalidPotionMeta", split[1]);
} }
} else if (split[0].equalsIgnoreCase("splash") || (allowShortName && split[0].equalsIgnoreCase("s"))) { } else if (split[0].equalsIgnoreCase("splash") || (allowShortName && split[0].equalsIgnoreCase("s"))) {
isSplashPotion = Boolean.parseBoolean(split[1]); isSplashPotion = Boolean.parseBoolean(split[1]);
@ -538,14 +537,14 @@ public class MetaItemStack {
final PotionMeta pmeta = (PotionMeta) stack.getItemMeta(); final PotionMeta pmeta = (PotionMeta) stack.getItemMeta();
pEffect = pEffectType.createEffect(duration, power); pEffect = pEffectType.createEffect(duration, power);
if (pmeta.getCustomEffects().size() > 1 && !hasMetaPermission(sender, "potions.multiple", true, false, ess)) { if (pmeta.getCustomEffects().size() > 1 && !hasMetaPermission(sender, "potions.multiple", true, false, ess)) {
throw new Exception(tl("multiplePotionEffects")); throw new TranslatableException("multiplePotionEffects");
} }
pmeta.addCustomEffect(pEffect, true); pmeta.addCustomEffect(pEffect, true);
stack.setItemMeta(pmeta); stack.setItemMeta(pmeta);
if (VersionUtil.getServerBukkitVersion().isHigherThanOrEqualTo(VersionUtil.v1_9_R01)) { if (VersionUtil.getServerBukkitVersion().isHigherThanOrEqualTo(VersionUtil.v1_9_R01)) {
if (isSplashPotion && stack.getType() != Material.SPLASH_POTION) { if (isSplashPotion && stack.getType() == Material.POTION) {
stack.setType(Material.SPLASH_POTION); stack.setType(Material.SPLASH_POTION);
} else if (!isSplashPotion && stack.getType() != Material.POTION) { } else if (!isSplashPotion && stack.getType() == Material.SPLASH_POTION) {
stack.setType(Material.POTION); stack.setType(Material.POTION);
} }
} else { } else {
@ -583,7 +582,7 @@ public class MetaItemStack {
public void addEnchantment(final CommandSource sender, final boolean allowUnsafe, final Enchantment enchantment, final int level) throws Exception { public void addEnchantment(final CommandSource sender, final boolean allowUnsafe, final Enchantment enchantment, final int level) throws Exception {
if (enchantment == null) { if (enchantment == null) {
throw new Exception(tl("enchantmentNotFound")); throw new TranslatableException("enchantmentNotFound");
} }
try { try {
if (stack.getType().equals(Material.ENCHANTED_BOOK)) { if (stack.getType().equals(Material.ENCHANTED_BOOK)) {
@ -619,7 +618,7 @@ public class MetaItemStack {
final String enchantmentName = enchantment.getName().toLowerCase(Locale.ENGLISH); final String enchantmentName = enchantment.getName().toLowerCase(Locale.ENGLISH);
if (!hasMetaPermission(user, "enchantments." + enchantmentName, true, false)) { if (!hasMetaPermission(user, "enchantments." + enchantmentName, true, false)) {
throw new Exception(tl("enchantmentPerm", enchantmentName)); throw new TranslatableException("enchantmentPerm", enchantmentName);
} }
return enchantment; return enchantment;
} }
@ -629,7 +628,7 @@ public class MetaItemStack {
final String[] split = splitPattern.split(string, 2); final String[] split = splitPattern.split(string, 2);
if (split.length < 2) { if (split.length < 2) {
throw new Exception(tl("invalidBanner", split[1])); throw new TranslatableException("invalidBanner", split[1]);
} }
PatternType patternType = null; PatternType patternType = null;
@ -654,7 +653,7 @@ public class MetaItemStack {
final String[] split = splitPattern.split(string, 2); final String[] split = splitPattern.split(string, 2);
if (split.length < 2) { if (split.length < 2) {
throw new Exception(tl("invalidBanner", split[1])); throw new TranslatableException("invalidBanner", split[1]);
} }
PatternType patternType = null; PatternType patternType = null;
@ -695,7 +694,7 @@ public class MetaItemStack {
if (graceful) { if (graceful) {
return false; return false;
} else { } else {
throw new Exception(tl("noMetaPerm", metaPerm)); throw new TranslatableException("noMetaPerm", metaPerm);
} }
} }

View File

@ -1,5 +1,6 @@
package com.earth2me.essentials; package com.earth2me.essentials;
import com.earth2me.essentials.utils.AdventureUtil;
import com.earth2me.essentials.utils.EnumUtil; import com.earth2me.essentials.utils.EnumUtil;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Server; import org.bukkit.Server;
@ -14,7 +15,7 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.logging.Level; import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tlLiteral;
// Suffixes can be appended on the end of a mob name to make it plural // Suffixes can be appended on the end of a mob name to make it plural
// Entities without a suffix, will default to 's' // Entities without a suffix, will default to 's'
@ -171,7 +172,7 @@ public enum Mob {
public Entity spawn(final World world, final Server server, final Location loc) throws MobException { public Entity spawn(final World world, final Server server, final Location loc) throws MobException {
final Entity entity = world.spawn(loc, this.bukkitType.getEntityClass()); final Entity entity = world.spawn(loc, this.bukkitType.getEntityClass());
if (entity == null) { if (entity == null) {
Essentials.getWrappedLogger().log(Level.WARNING, tl("unableToSpawnMob")); Essentials.getWrappedLogger().log(Level.WARNING, AdventureUtil.miniToLegacy(tlLiteral("unableToSpawnMob")));
throw new MobException(); throw new MobException();
} }
return entity; return entity;

View File

@ -4,6 +4,7 @@ import com.earth2me.essentials.craftbukkit.Inventories;
import com.earth2me.essentials.utils.EnumUtil; import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.StringUtil; import com.earth2me.essentials.utils.StringUtil;
import com.earth2me.essentials.utils.VersionUtil; import com.earth2me.essentials.utils.VersionUtil;
import net.ess3.api.TranslatableException;
import org.bukkit.DyeColor; import org.bukkit.DyeColor;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.entity.Ageable; import org.bukkit.entity.Ageable;
@ -38,8 +39,6 @@ import java.util.Locale;
import java.util.Random; import java.util.Random;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static com.earth2me.essentials.I18n.tl;
public enum MobData { public enum MobData {
BABY_AGEABLE("baby", Ageable.class, Data.BABY, true), BABY_AGEABLE("baby", Ageable.class, Data.BABY, true),
@ -328,14 +327,14 @@ public enum MobData {
} }
this.matched = rawData; this.matched = rawData;
} catch (final Exception e) { } catch (final Exception e) {
throw new Exception(tl("sheepMalformedColor"), e); throw new TranslatableException(e, "sheepMalformedColor");
} }
} else if (this.value.equals(Data.EXP)) { } else if (this.value.equals(Data.EXP)) {
try { try {
((ExperienceOrb) spawned).setExperience(Integer.parseInt(rawData)); ((ExperienceOrb) spawned).setExperience(Integer.parseInt(rawData));
this.matched = rawData; this.matched = rawData;
} catch (final NumberFormatException e) { } catch (final NumberFormatException e) {
throw new Exception(tl("invalidNumber"), e); throw new TranslatableException(e, "invalidNumber");
} }
} else if (this.value.equals(Data.SIZE)) { } else if (this.value.equals(Data.SIZE)) {
try { try {
@ -347,7 +346,7 @@ public enum MobData {
} }
this.matched = rawData; this.matched = rawData;
} catch (final NumberFormatException e) { } catch (final NumberFormatException e) {
throw new Exception(tl("slimeMalformedSize"), e); throw new TranslatableException(e, "slimeMalformedSize");
} }
} else if (this.value instanceof Horse.Color) { } else if (this.value instanceof Horse.Color) {
((Horse) spawned).setColor((Horse.Color) this.value); ((Horse) spawned).setColor((Horse.Color) this.value);

View File

@ -1,8 +1,9 @@
package com.earth2me.essentials; package com.earth2me.essentials;
import com.earth2me.essentials.utils.AdventureUtil;
import com.earth2me.essentials.utils.FormatUtil; import com.earth2me.essentials.utils.FormatUtil;
import com.earth2me.essentials.utils.NumberUtil; import com.earth2me.essentials.utils.NumberUtil;
import org.bukkit.ChatColor; import net.ess3.api.TranslatableException;
import org.bukkit.Server; import org.bukkit.Server;
import java.util.ArrayList; import java.util.ArrayList;
@ -14,7 +15,7 @@ import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tlLiteral;
public final class PlayerList { public final class PlayerList {
@ -32,19 +33,19 @@ public final class PlayerList {
} }
needComma = true; needComma = true;
if (user.isAfk()) { if (user.isAfk()) {
groupString.append(tl("listAfkTag")); groupString.append(tlLiteral("listAfkTag"));
} }
if (user.isHidden()) { if (user.isHidden()) {
groupString.append(tl("listHiddenTag")); groupString.append(tlLiteral("listHiddenTag"));
} }
user.setDisplayNick(); user.setDisplayNick();
groupString.append(user.getDisplayName()); groupString.append(AdventureUtil.legacyToMini(user.getDisplayName()));
final String strippedNick = FormatUtil.stripFormat(user.getNickname()); final String strippedNick = FormatUtil.stripFormat(user.getNickname());
if (ess.getSettings().realNamesOnList() && strippedNick != null && !strippedNick.equals(user.getName())) { if (ess.getSettings().realNamesOnList() && strippedNick != null && !strippedNick.equals(user.getName())) {
groupString.append(" ").append(tl("listRealName",user.getName())); groupString.append(" ").append(tlLiteral("listRealName",user.getName()));
} }
groupString.append(ChatColor.WHITE.toString()); groupString.append("<white>");
} }
return groupString.toString(); return groupString.toString();
} }
@ -62,13 +63,17 @@ public final class PlayerList {
} }
} }
} }
final String online;
final String tlKey;
final Object[] objects;
if (hiddenCount > 0) { if (hiddenCount > 0) {
online = tl("listAmountHidden", ess.getOnlinePlayers().size() - playerHidden, hiddenCount, server.getMaxPlayers()); tlKey = "listAmountHidden";
objects = new Object[]{ess.getOnlinePlayers().size() - playerHidden, hiddenCount, server.getMaxPlayers()};
} else { } else {
online = tl("listAmount", ess.getOnlinePlayers().size() - playerHidden, server.getMaxPlayers()); tlKey = "listAmount";
objects = new Object[]{ess.getOnlinePlayers().size() - playerHidden, server.getMaxPlayers()};
} }
return online; return user == null ? tlLiteral(tlKey, objects) : user.playerTl(tlKey, objects);
} }
// Build the basic player list, divided by groups. // Build the basic player list, divided by groups.
@ -117,7 +122,7 @@ public final class PlayerList {
users.addAll(groupUsers); users.addAll(groupUsers);
} }
if (users.isEmpty()) { if (users.isEmpty()) {
throw new Exception(tl("groupDoesNotExist")); throw new TranslatableException("groupDoesNotExist");
} }
final String displayGroupName = Character.toTitleCase(groupName.charAt(0)) + final String displayGroupName = Character.toTitleCase(groupName.charAt(0)) +
groupName.substring(1); groupName.substring(1);
@ -126,11 +131,11 @@ public final class PlayerList {
// Build the output string // Build the output string
public static String outputFormat(final String group, final String message) { public static String outputFormat(final String group, final String message) {
return tl("listGroupTag", FormatUtil.replaceFormat(group)) + return tlLiteral("listGroupTag", FormatUtil.replaceFormat(group)) +
message; message;
} }
public static List<String> prepareGroupedList(final IEssentials ess, final String commandLabel, final Map<String, List<User>> playerList) { public static List<String> prepareGroupedList(final IEssentials ess, final CommandSource source, final String commandLabel, final Map<String, List<User>> playerList) {
final List<String> output = new ArrayList<>(); final List<String> output = new ArrayList<>();
final Set<String> configGroups = ess.getSettings().getListGroupConfig().keySet(); final Set<String> configGroups = ess.getSettings().getListGroupConfig().keySet();
@ -163,7 +168,9 @@ public final class PlayerList {
outputUserList = new ArrayList<>(matchedList); outputUserList = new ArrayList<>(matchedList);
final int limit = Integer.parseInt(groupValue); final int limit = Integer.parseInt(groupValue);
if (matchedList.size() > limit) { if (matchedList.size() > limit) {
output.add(outputFormat(oConfigGroup, tl("groupNumber", matchedList.size(), commandLabel, FormatUtil.stripFormat(configGroup)))); final String tlKey = "groupNumber";
final Object[] objects = {matchedList.size(), commandLabel, FormatUtil.stripFormat(configGroup)};
output.add(outputFormat(oConfigGroup, source == null ? tlLiteral(tlKey, objects) : source.tl(tlKey, objects)));
} else { } else {
output.add(outputFormat(oConfigGroup, listUsers(ess, outputUserList, ", "))); output.add(outputFormat(oConfigGroup, listUsers(ess, outputUserList, ", ")));
} }
@ -203,7 +210,7 @@ public final class PlayerList {
String groupName = asterisk.isEmpty() ? users.get(0).getGroup() : onlineGroup; String groupName = asterisk.isEmpty() ? users.get(0).getGroup() : onlineGroup;
if (ess.getPermissionsHandler().getName().equals("ConfigPermissions")) { if (ess.getPermissionsHandler().getName().equals("ConfigPermissions")) {
groupName = tl("connectedPlayers"); groupName = source == null ? tlLiteral("connectedPlayers") : source.tl("connectedPlayers");
} }
if (users == null || users.isEmpty()) { if (users == null || users.isEmpty()) {
continue; continue;

View File

@ -8,12 +8,17 @@ import com.earth2me.essentials.signs.EssentialsSign;
import com.earth2me.essentials.signs.Signs; import com.earth2me.essentials.signs.Signs;
import com.earth2me.essentials.textreader.IText; import com.earth2me.essentials.textreader.IText;
import com.earth2me.essentials.textreader.SimpleTextInput; import com.earth2me.essentials.textreader.SimpleTextInput;
import com.earth2me.essentials.utils.AdventureUtil;
import com.earth2me.essentials.utils.EnumUtil; import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.FormatUtil; import com.earth2me.essentials.utils.FormatUtil;
import com.earth2me.essentials.utils.LocationUtil; import com.earth2me.essentials.utils.LocationUtil;
import com.earth2me.essentials.utils.NumberUtil; import com.earth2me.essentials.utils.NumberUtil;
import net.ess3.api.IEssentials; import net.ess3.api.IEssentials;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextColor;
import net.kyori.adventure.text.minimessage.tag.Tag;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
@ -43,7 +48,7 @@ import java.util.logging.Level;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException; import java.util.regex.PatternSyntaxException;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tlLiteral;
public class Settings implements net.ess3.api.ISettings { public class Settings implements net.ess3.api.ISettings {
private static final BigDecimal DEFAULT_MAX_MONEY = new BigDecimal("10000000000000"); private static final BigDecimal DEFAULT_MAX_MONEY = new BigDecimal("10000000000000");
@ -136,6 +141,8 @@ public class Settings implements net.ess3.api.ISettings {
private double maxProjectileSpeed; private double maxProjectileSpeed;
private boolean removeEffectsOnHeal; private boolean removeEffectsOnHeal;
private Map<String, String> worldAliases; private Map<String, String> worldAliases;
private Tag primaryColor = Tag.styling(NamedTextColor.GOLD);
private Tag secondaryColor = Tag.styling(NamedTextColor.RED);
public Settings(final IEssentials ess) { public Settings(final IEssentials ess) {
this.ess = ess; this.ess = ess;
@ -779,6 +786,8 @@ public class Settings implements net.ess3.api.ISettings {
bindingItemPolicy = _getBindingItemsPolicy(); bindingItemPolicy = _getBindingItemsPolicy();
currencySymbol = _getCurrencySymbol(); currencySymbol = _getCurrencySymbol();
worldAliases = _getWorldAliases(); worldAliases = _getWorldAliases();
primaryColor = _getPrimaryColor();
secondaryColor = _getSecondaryColor();
reloadCount.incrementAndGet(); reloadCount.incrementAndGet();
} }
@ -809,7 +818,7 @@ public class Settings implements net.ess3.api.ISettings {
final ItemStack iStack = itemDb.get(itemName); final ItemStack iStack = itemDb.get(itemName);
epItemSpwn.add(iStack.getType()); epItemSpwn.add(iStack.getType());
} catch (final Exception ex) { } catch (final Exception ex) {
ess.getLogger().log(Level.SEVERE, tl("unknownItemInList", itemName, "item-spawn-blacklist"), ex); ess.getLogger().log(Level.SEVERE, AdventureUtil.miniToLegacy(tlLiteral("unknownItemInList", itemName, "item-spawn-blacklist")), ex);
} }
} }
return epItemSpwn; return epItemSpwn;
@ -837,7 +846,7 @@ public class Settings implements net.ess3.api.ISettings {
try { try {
newSigns.add(Signs.valueOf(signName).getSign()); newSigns.add(Signs.valueOf(signName).getSign());
} catch (final Exception ex) { } catch (final Exception ex) {
ess.getLogger().log(Level.SEVERE, tl("unknownItemInList", signName, "enabledSigns")); ess.getLogger().log(Level.SEVERE, AdventureUtil.miniToLegacy(tlLiteral("unknownItemInList", signName, "enabledSigns")));
continue; continue;
} }
signsEnabled = true; signsEnabled = true;
@ -883,6 +892,11 @@ public class Settings implements net.ess3.api.ISettings {
return config.getString("locale", ""); return config.getString("locale", "");
} }
@Override
public boolean isPerPlayerLocale() {
return config.getBoolean("per-player-locale", false);
}
private String currencySymbol = "$"; private String currencySymbol = "$";
// A valid currency symbol value must be one non-integer character. // A valid currency symbol value must be one non-integer character.
@ -951,7 +965,7 @@ public class Settings implements net.ess3.api.ISettings {
} }
if (mat == null) { if (mat == null) {
ess.getLogger().log(Level.SEVERE, tl("unknownItemInList", itemName, configName)); ess.getLogger().log(Level.SEVERE, AdventureUtil.miniToLegacy(tlLiteral("unknownItemInList", itemName, configName)));
} else { } else {
list.add(mat); list.add(mat);
} }
@ -1699,7 +1713,7 @@ public class Settings implements net.ess3.api.ISettings {
try { try {
newSigns.add(Signs.valueOf(signName).getSign()); newSigns.add(Signs.valueOf(signName).getSign());
} catch (final Exception ex) { } catch (final Exception ex) {
ess.getLogger().log(Level.SEVERE, tl("unknownItemInList", signName, "unprotected-sign-names")); ess.getLogger().log(Level.SEVERE, AdventureUtil.miniToLegacy(tlLiteral("unknownItemInList", signName, "unprotected-sign-names")));
} }
} }
return newSigns; return newSigns;
@ -1948,4 +1962,42 @@ public class Settings implements net.ess3.api.ISettings {
public int getMaxItemLore() { public int getMaxItemLore() {
return config.getInt("max-itemlore-lines", 10); return config.getInt("max-itemlore-lines", 10);
} }
@Override
public Tag getPrimaryColor() {
return primaryColor;
}
private Tag _getPrimaryColor() {
final String color = config.getString("message-colors.primary", "#ffaa00");
return Tag.styling(_getTagColor(color, NamedTextColor.GOLD));
}
@Override
public Tag getSecondaryColor() {
return secondaryColor;
}
private Tag _getSecondaryColor() {
final String color = config.getString("message-colors.secondary", "#ff5555");
return Tag.styling(_getTagColor(color, NamedTextColor.RED));
}
private TextColor _getTagColor(final String color, final TextColor def) {
try {
if (color.startsWith("#") && color.length() == 7 && NumberUtil.isNumeric(color.substring(1))) {
return TextColor.color(Color.fromRGB(Integer.decode(color)).asRGB());
}
if (color.length() == 1) {
final NamedTextColor named = AdventureUtil.fromChar(color.charAt(0));
return named != null ? named : def;
}
final NamedTextColor named = NamedTextColor.NAMES.value(color.toLowerCase(Locale.ENGLISH));
return named != null ? named : def;
} catch (IllegalArgumentException ignored) {
}
return def;
}
} }

View File

@ -7,6 +7,7 @@ import com.earth2me.essentials.utils.LocationUtil;
import com.earth2me.essentials.utils.StringUtil; import com.earth2me.essentials.utils.StringUtil;
import com.earth2me.essentials.utils.VersionUtil; import com.earth2me.essentials.utils.VersionUtil;
import net.ess3.api.IEssentials; import net.ess3.api.IEssentials;
import net.ess3.api.TranslatableException;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.Server; import org.bukkit.Server;
@ -27,8 +28,6 @@ import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Set; import java.util.Set;
import static com.earth2me.essentials.I18n.tl;
public final class SpawnMob { public final class SpawnMob {
private static final Material GOLDEN_HELMET = EnumUtil.getMaterial("GOLDEN_HELMET", "GOLD_HELMET"); private static final Material GOLDEN_HELMET = EnumUtil.getMaterial("GOLDEN_HELMET", "GOLD_HELMET");
@ -49,7 +48,7 @@ public final class SpawnMob {
} }
} }
if (availableList.isEmpty()) { if (availableList.isEmpty()) {
availableList.add(tl("none")); availableList.add(user.playerTl("none"));
} }
return StringUtil.joinList(availableList); return StringUtil.joinList(availableList);
} }
@ -91,7 +90,7 @@ public final class SpawnMob {
public static void spawnmob(final IEssentials ess, final Server server, final User user, final List<String> parts, final List<String> data, final int mobCount) throws Exception { public static void spawnmob(final IEssentials ess, final Server server, final User user, final List<String> parts, final List<String> data, final int mobCount) throws Exception {
final Block block = LocationUtil.getTarget(user.getBase()).getBlock(); final Block block = LocationUtil.getTarget(user.getBase()).getBlock();
if (block == null) { if (block == null) {
throw new Exception(tl("unableToSpawnMob")); throw new TranslatableException("unableToSpawnMob");
} }
spawnmob(ess, server, user.getSource(), user, block.getLocation(), parts, data, mobCount); spawnmob(ess, server, user.getSource(), user, block.getLocation(), parts, data, mobCount);
} }
@ -122,7 +121,7 @@ public final class SpawnMob {
if (mobCount > effectiveLimit) { if (mobCount > effectiveLimit) {
mobCount = effectiveLimit; mobCount = effectiveLimit;
sender.sendMessage(tl("mobSpawnLimit")); sender.sendTl("mobSpawnLimit");
} }
final Mob mob = Mob.fromName(parts.get(0)); // Get the first mob final Mob mob = Mob.fromName(parts.get(0)); // Get the first mob
@ -130,13 +129,13 @@ public final class SpawnMob {
for (int i = 0; i < mobCount; i++) { for (int i = 0; i < mobCount; i++) {
spawnMob(ess, server, sender, target, sloc, parts, data); spawnMob(ess, server, sender, target, sloc, parts, data);
} }
sender.sendMessage(mobCount * parts.size() + " " + mob.name.toLowerCase(Locale.ENGLISH) + mob.suffix + " " + tl("spawned")); sender.sendMessage(mobCount * parts.size() + " " + mob.name.toLowerCase(Locale.ENGLISH) + mob.suffix + " " + sender.tl("spawned"));
} catch (final MobException e1) { } catch (final MobException e1) {
throw new Exception(tl("unableToSpawnMob"), e1); throw new TranslatableException(e1, "unableToSpawnMob");
} catch (final NumberFormatException e2) { } catch (final NumberFormatException e2) {
throw new Exception(tl("numberRequired"), e2); throw new TranslatableException(e2, "numberRequired");
} catch (final NullPointerException np) { } catch (final NullPointerException np) {
throw new Exception(tl("soloMob"), np); throw new TranslatableException(np, "soloMob");
} }
} }
@ -176,15 +175,15 @@ public final class SpawnMob {
private static void checkSpawnable(final IEssentials ess, final CommandSource sender, final Mob mob) throws Exception { private static void checkSpawnable(final IEssentials ess, final CommandSource sender, final Mob mob) throws Exception {
if (mob == null || mob.getType() == null) { if (mob == null || mob.getType() == null) {
throw new Exception(tl("invalidMob")); throw new TranslatableException("invalidMob");
} }
if (ess.getSettings().getProtectPreventSpawn(mob.getType().toString().toLowerCase(Locale.ENGLISH))) { if (ess.getSettings().getProtectPreventSpawn(mob.getType().toString().toLowerCase(Locale.ENGLISH))) {
throw new Exception(tl("disabledToSpawnMob")); throw new TranslatableException("disabledToSpawnMob");
} }
if (sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.spawnmob." + mob.name.toLowerCase(Locale.ENGLISH))) { if (sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.spawnmob." + mob.name.toLowerCase(Locale.ENGLISH))) {
throw new Exception(tl("noPermToSpawnMob")); throw new TranslatableException("noPermToSpawnMob");
} }
} }
@ -192,7 +191,7 @@ public final class SpawnMob {
String data = inputData; String data = inputData;
if (data.isEmpty()) { if (data.isEmpty()) {
sender.sendMessage(tl("mobDataList", StringUtil.joinList(MobData.getValidHelp(spawned)))); sender.sendTl("mobDataList", StringUtil.joinList(MobData.getValidHelp(spawned)));
} }
if (spawned instanceof Zombie) { if (spawned instanceof Zombie) {

View File

@ -6,6 +6,7 @@ import io.papermc.lib.PaperLib;
import net.ess3.api.IEssentials; import net.ess3.api.IEssentials;
import net.ess3.api.ITeleport; import net.ess3.api.ITeleport;
import net.ess3.api.IUser; import net.ess3.api.IUser;
import net.ess3.api.TranslatableException;
import net.ess3.api.events.UserWarpEvent; import net.ess3.api.events.UserWarpEvent;
import net.ess3.api.events.teleport.PreTeleportEvent; import net.ess3.api.events.teleport.PreTeleportEvent;
import net.ess3.api.events.teleport.TeleportWarmupEvent; import net.ess3.api.events.teleport.TeleportWarmupEvent;
@ -19,8 +20,6 @@ import java.math.BigDecimal;
import java.util.Calendar; import java.util.Calendar;
import java.util.GregorianCalendar; import java.util.GregorianCalendar;
import static com.earth2me.essentials.I18n.tl;
/** /**
* @deprecated This API is not asynchronous. Use {@link com.earth2me.essentials.AsyncTeleport AsyncTeleport} * @deprecated This API is not asynchronous. Use {@link com.earth2me.essentials.AsyncTeleport AsyncTeleport}
*/ */
@ -64,7 +63,7 @@ public class Teleport implements ITeleport {
time.setTimeInMillis(lastTime); time.setTimeInMillis(lastTime);
time.add(Calendar.SECOND, (int) cooldown); time.add(Calendar.SECOND, (int) cooldown);
time.add(Calendar.MILLISECOND, (int) ((cooldown * 1000.0) % 1000.0)); time.add(Calendar.MILLISECOND, (int) ((cooldown * 1000.0) % 1000.0));
throw new Exception(tl("timeBeforeTeleport", DateUtil.formatDateDiff(time.getTimeInMillis()))); throw new TranslatableException("timeBeforeTeleport", DateUtil.formatDateDiff(time.getTimeInMillis()));
} }
} }
// if justCheck is set, don't update lastTeleport; we're just checking // if justCheck is set, don't update lastTeleport; we're just checking
@ -98,7 +97,7 @@ public class Teleport implements ITeleport {
final Calendar c = new GregorianCalendar(); final Calendar c = new GregorianCalendar();
c.add(Calendar.SECOND, (int) delay); c.add(Calendar.SECOND, (int) delay);
c.add(Calendar.MILLISECOND, (int) ((delay * 1000.0) % 1000.0)); c.add(Calendar.MILLISECOND, (int) ((delay * 1000.0) % 1000.0));
user.sendMessage(tl("dontMoveMessage", DateUtil.formatDateDiff(c.getTimeInMillis()))); user.sendTl("dontMoveMessage", DateUtil.formatDateDiff(c.getTimeInMillis()));
} }
//The now function is used when you want to skip tp delay when teleporting someone to a location or player. //The now function is used when you want to skip tp delay when teleporting someone to a location or player.
@ -120,7 +119,7 @@ public class Teleport implements ITeleport {
} }
final ITarget target = new PlayerTarget(entity); final ITarget target = new PlayerTarget(entity);
now(teleportOwner, target, cause); now(teleportOwner, target, cause);
teleportOwner.sendMessage(tl("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ())); teleportOwner.sendTl("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ());
} }
@Deprecated @Deprecated
@ -140,7 +139,7 @@ public class Teleport implements ITeleport {
if (!teleportee.getBase().isEmpty()) { if (!teleportee.getBase().isEmpty()) {
if (!ess.getSettings().isTeleportPassengerDismount()) { if (!ess.getSettings().isTeleportPassengerDismount()) {
throw new Exception(tl("passengerTeleportFail")); throw new TranslatableException("passengerTeleportFail");
} }
teleportee.getBase().eject(); teleportee.getBase().eject();
} }
@ -153,7 +152,7 @@ public class Teleport implements ITeleport {
PaperLib.teleportAsync(teleportee.getBase(), LocationUtil.getSafeDestination(ess, teleportee, loc), cause); PaperLib.teleportAsync(teleportee.getBase(), LocationUtil.getSafeDestination(ess, teleportee, loc), cause);
} }
} else { } else {
throw new Exception(tl("unsafeTeleportDestination", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); throw new TranslatableException("unsafeTeleportDestination", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
} }
} else { } else {
if (ess.getSettings().isForceDisableTeleportSafety()) { if (ess.getSettings().isForceDisableTeleportSafety()) {
@ -186,7 +185,7 @@ public class Teleport implements ITeleport {
@Deprecated @Deprecated
public void teleport(final Player entity, final Trade chargeFor, final TeleportCause cause) throws Exception { public void teleport(final Player entity, final Trade chargeFor, final TeleportCause cause) throws Exception {
final ITarget target = new PlayerTarget(entity); final ITarget target = new PlayerTarget(entity);
teleportOwner.sendMessage(tl("teleportToPlayer", entity.getDisplayName())); teleportOwner.sendTl("teleportToPlayer", entity.getDisplayName());
teleport(teleportOwner, target, chargeFor, cause); teleport(teleportOwner, target, chargeFor, cause);
} }
@ -203,8 +202,8 @@ public class Teleport implements ITeleport {
public void teleportPlayer(final IUser teleportee, final Player entity, final Trade chargeFor, final TeleportCause cause) throws Exception { public void teleportPlayer(final IUser teleportee, final Player entity, final Trade chargeFor, final TeleportCause cause) throws Exception {
final ITarget target = new PlayerTarget(entity); final ITarget target = new PlayerTarget(entity);
teleport(teleportee, target, chargeFor, cause); teleport(teleportee, target, chargeFor, cause);
teleportee.sendMessage(tl("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ())); teleportee.sendTl("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ());
teleportOwner.sendMessage(tl("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ())); teleportOwner.sendTl("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ());
} }
@Deprecated @Deprecated
@ -345,9 +344,9 @@ public class Teleport implements ITeleport {
warp = event.getWarp(); warp = event.getWarp();
final Location loc = ess.getWarps().getWarp(warp); final Location loc = ess.getWarps().getWarp(warp);
teleportee.sendMessage(tl("warpingTo", warp, loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); teleportee.sendTl("warpingTo", warp, loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
if (!teleportee.equals(teleportOwner)) { if (!teleportee.equals(teleportOwner)) {
teleportOwner.sendMessage(tl("warpingTo", warp, loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); teleportOwner.sendTl("warpingTo", warp, loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
} }
teleport(teleportee, new LocationTarget(loc), chargeFor, cause); teleport(teleportee, new LocationTarget(loc), chargeFor, cause);
} }
@ -365,7 +364,7 @@ public class Teleport implements ITeleport {
public void back(final IUser teleporter, final Trade chargeFor) throws Exception { public void back(final IUser teleporter, final Trade chargeFor) throws Exception {
tpType = TeleportType.BACK; tpType = TeleportType.BACK;
final Location loc = teleportOwner.getLastLocation(); final Location loc = teleportOwner.getLastLocation();
teleportOwner.sendMessage(tl("backUsageMsg", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); teleportOwner.sendTl("backUsageMsg", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
teleportOther(teleporter, teleportOwner, new LocationTarget(loc), chargeFor, TeleportCause.COMMAND); teleportOther(teleporter, teleportOwner, new LocationTarget(loc), chargeFor, TeleportCause.COMMAND);
} }

View File

@ -7,8 +7,6 @@ import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import java.util.UUID; import java.util.UUID;
import static com.earth2me.essentials.I18n.tl;
@Deprecated @Deprecated
public class TimedTeleport implements Runnable { public class TimedTeleport implements Runnable {
private static final double MOVE_CONSTANT = 0.3; private static final double MOVE_CONSTANT = 0.3;
@ -89,14 +87,14 @@ public class TimedTeleport implements Runnable {
try { try {
teleport.cooldown(false); teleport.cooldown(false);
} catch (final Exception ex) { } catch (final Exception ex) {
teleportOwner.sendMessage(tl("cooldownWithMessage", ex.getMessage())); teleportOwner.sendTl("cooldownWithMessage", ex.getMessage());
if (teleportOwner != teleportUser) { if (teleportOwner != teleportUser) {
teleportUser.sendMessage(tl("cooldownWithMessage", ex.getMessage())); teleportUser.sendTl("cooldownWithMessage", ex.getMessage());
} }
} }
try { try {
cancelTimer(false); cancelTimer(false);
teleportUser.sendMessage(tl("teleportationCommencing")); teleportUser.sendTl("teleportationCommencing");
if (timer_chargeFor != null) { if (timer_chargeFor != null) {
timer_chargeFor.isAffordableFor(teleportOwner); timer_chargeFor.isAffordableFor(teleportOwner);
@ -128,9 +126,9 @@ public class TimedTeleport implements Runnable {
try { try {
ess.getServer().getScheduler().cancelTask(timer_task); ess.getServer().getScheduler().cancelTask(timer_task);
if (notifyUser) { if (notifyUser) {
teleportOwner.sendMessage(tl("pendingTeleportCancelled")); teleportOwner.sendTl("pendingTeleportCancelled");
if (timer_teleportee != null && !timer_teleportee.equals(teleportOwner.getBase().getUniqueId())) { if (timer_teleportee != null && !timer_teleportee.equals(teleportOwner.getBase().getUniqueId())) {
ess.getUser(timer_teleportee).sendMessage(tl("pendingTeleportCancelled")); ess.getUser(timer_teleportee).sendTl("pendingTeleportCancelled");
} }
} }
} finally { } finally {

View File

@ -23,8 +23,6 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.logging.Level; import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tl;
public class Trade { public class Trade {
private static FileWriter fw = null; private static FileWriter fw = null;
private final transient String command; private final transient String command;
@ -193,23 +191,23 @@ public class Trade {
} }
if (getMoney() != null && getMoney().signum() > 0 && !user.canAfford(getMoney())) { if (getMoney() != null && getMoney().signum() > 0 && !user.canAfford(getMoney())) {
future.completeExceptionally(new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(getMoney(), ess)))); future.completeExceptionally(new ChargeException(user.playerTl("notEnoughMoney", NumberUtil.displayCurrency(getMoney(), ess))));
return; return;
} }
if (getItemStack() != null && !Inventories.containsAtLeast(user.getBase(), itemStack, itemStack.getAmount())) { if (getItemStack() != null && !Inventories.containsAtLeast(user.getBase(), itemStack, itemStack.getAmount())) {
future.completeExceptionally(new ChargeException(tl("missingItems", getItemStack().getAmount(), ess.getItemDb().name(getItemStack())))); future.completeExceptionally(new ChargeException(user.playerTl("missingItems", getItemStack().getAmount(), ess.getItemDb().name(getItemStack()))));
return; return;
} }
final BigDecimal money; final BigDecimal money;
if (command != null && !command.isEmpty() && (money = getCommandCost(user)).signum() > 0 && !user.canAfford(money)) { if (command != null && !command.isEmpty() && (money = getCommandCost(user)).signum() > 0 && !user.canAfford(money)) {
future.completeExceptionally(new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(money, ess)))); future.completeExceptionally(new ChargeException(user.playerTl("notEnoughMoney", NumberUtil.displayCurrency(money, ess))));
return; return;
} }
if (exp != null && exp > 0 && SetExpFix.getTotalExperience(user.getBase()) < exp) { if (exp != null && exp > 0 && SetExpFix.getTotalExperience(user.getBase()) < exp) {
future.completeExceptionally(new ChargeException(tl("notEnoughExperience"))); future.completeExceptionally(new ChargeException(user.playerTl("notEnoughExperience")));
} }
} }
@ -287,7 +285,7 @@ public class Trade {
ess.getLogger().log(Level.INFO, "charging user " + user.getName() + " money " + getMoney().toPlainString()); ess.getLogger().log(Level.INFO, "charging user " + user.getName() + " money " + getMoney().toPlainString());
} }
if (!user.canAfford(getMoney()) && getMoney().signum() > 0) { if (!user.canAfford(getMoney()) && getMoney().signum() > 0) {
future.completeExceptionally(new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(getMoney(), ess)))); future.completeExceptionally(new ChargeException(user.playerTl("notEnoughMoney", NumberUtil.displayCurrency(getMoney(), ess))));
return; return;
} }
user.takeMoney(getMoney()); user.takeMoney(getMoney());
@ -297,7 +295,7 @@ public class Trade {
ess.getLogger().log(Level.INFO, "charging user " + user.getName() + " itemstack " + getItemStack().toString()); ess.getLogger().log(Level.INFO, "charging user " + user.getName() + " itemstack " + getItemStack().toString());
} }
if (!Inventories.containsAtLeast(user.getBase(), getItemStack(), getItemStack().getAmount())) { if (!Inventories.containsAtLeast(user.getBase(), getItemStack(), getItemStack().getAmount())) {
future.completeExceptionally(new ChargeException(tl("missingItems", getItemStack().getAmount(), getItemStack().getType().toString().toLowerCase(Locale.ENGLISH).replace("_", " ")))); future.completeExceptionally(new ChargeException(user.playerTl("missingItems", getItemStack().getAmount(), getItemStack().getType().toString().toLowerCase(Locale.ENGLISH).replace("_", " "))));
return; return;
} }
Inventories.removeItemAmount(user.getBase(), getItemStack(), getItemStack().getAmount()); Inventories.removeItemAmount(user.getBase(), getItemStack(), getItemStack().getAmount());
@ -306,7 +304,7 @@ public class Trade {
if (command != null) { if (command != null) {
final BigDecimal cost = getCommandCost(user); final BigDecimal cost = getCommandCost(user);
if (!user.canAfford(cost) && cost.signum() > 0) { if (!user.canAfford(cost) && cost.signum() > 0) {
future.completeExceptionally(new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(cost, ess)))); future.completeExceptionally(new ChargeException(user.playerTl("notEnoughMoney", NumberUtil.displayCurrency(cost, ess))));
return; return;
} }
user.takeMoney(cost); user.takeMoney(cost);
@ -317,7 +315,7 @@ public class Trade {
} }
final int experience = SetExpFix.getTotalExperience(user.getBase()); final int experience = SetExpFix.getTotalExperience(user.getBase());
if (experience < getExperience() && getExperience() > 0) { if (experience < getExperience() && getExperience() > 0) {
future.completeExceptionally(new ChargeException(tl("notEnoughExperience"))); future.completeExceptionally(new ChargeException(user.playerTl("notEnoughExperience")));
return; return;
} }
SetExpFix.setTotalExperience(user.getBase(), experience - getExperience()); SetExpFix.setTotalExperience(user.getBase(), experience - getExperience());

View File

@ -6,6 +6,7 @@ import com.earth2me.essentials.economy.EconomyLayer;
import com.earth2me.essentials.economy.EconomyLayers; import com.earth2me.essentials.economy.EconomyLayers;
import com.earth2me.essentials.messaging.IMessageRecipient; import com.earth2me.essentials.messaging.IMessageRecipient;
import com.earth2me.essentials.messaging.SimpleMessageRecipient; import com.earth2me.essentials.messaging.SimpleMessageRecipient;
import com.earth2me.essentials.utils.AdventureUtil;
import com.earth2me.essentials.utils.DateUtil; import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.EnumUtil; import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.FormatUtil; import com.earth2me.essentials.utils.FormatUtil;
@ -21,6 +22,8 @@ import net.ess3.api.events.MuteStatusChangeEvent;
import net.ess3.api.events.UserBalanceUpdateEvent; import net.ess3.api.events.UserBalanceUpdateEvent;
import net.essentialsx.api.v2.events.TransactionEvent; import net.essentialsx.api.v2.events.TransactionEvent;
import net.essentialsx.api.v2.services.mail.MailSender; import net.essentialsx.api.v2.services.mail.MailSender;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.ComponentLike;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.Statistic; import org.bukkit.Statistic;
@ -49,7 +52,8 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.logging.Level; import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tlLiteral;
import static com.earth2me.essentials.I18n.tlLocale;
public class User extends UserData implements Comparable<User>, IMessageRecipient, net.ess3.api.IUser { public class User extends UserData implements Comparable<User>, IMessageRecipient, net.ess3.api.IUser {
private static final Statistic PLAY_ONE_TICK = EnumUtil.getStatistic("PLAY_ONE_MINUTE", "PLAY_ONE_TICK"); private static final Statistic PLAY_ONE_TICK = EnumUtil.getStatistic("PLAY_ONE_MINUTE", "PLAY_ONE_TICK");
@ -57,10 +61,13 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
// User modules // User modules
private final IMessageRecipient messageRecipient; private final IMessageRecipient messageRecipient;
private transient final AsyncTeleport teleport; private transient final AsyncTeleport teleport;
@SuppressWarnings("deprecation")
private transient final Teleport legacyTeleport; private transient final Teleport legacyTeleport;
// User command confirmation strings // User command confirmation strings
private final Map<User, BigDecimal> confirmingPayments = new WeakHashMap<>(); private final Map<User, BigDecimal> confirmingPayments = new WeakHashMap<>();
private String confirmingClearCommand;
private String lastHomeConfirmation;
// User teleport variables // User teleport variables
private final transient LinkedHashMap<String, TpaRequest> teleportRequestQueue = new LinkedHashMap<>(); private final transient LinkedHashMap<String, TpaRequest> teleportRequestQueue = new LinkedHashMap<>();
@ -74,29 +81,32 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
private boolean recipeSee = false; private boolean recipeSee = false;
private boolean enderSee = false; private boolean enderSee = false;
private boolean ignoreMsg = false; private boolean ignoreMsg = false;
private Boolean toggleShout;
private boolean freeze = false;
// User afk variables // User afk variables
private String afkMessage; private String afkMessage;
private long afkSince; private long afkSince;
private transient Location afkPosition = null; private transient Location afkPosition = null;
// Misc // Timestamps
private transient long lastOnlineActivity; private transient long lastOnlineActivity;
private transient long lastThrottledAction; private transient long lastThrottledAction;
private transient long lastActivity = System.currentTimeMillis(); private transient long lastActivity = System.currentTimeMillis();
private transient long teleportInvulnerabilityTimestamp = 0; private transient long teleportInvulnerabilityTimestamp = 0;
private String confirmingClearCommand;
private long lastNotifiedAboutMailsMs; private long lastNotifiedAboutMailsMs;
private String lastHomeConfirmation;
private long lastHomeConfirmationTimestamp; private long lastHomeConfirmationTimestamp;
private Boolean toggleShout;
private boolean freeze = false; // Misc
private transient final List<String> signCopy = Lists.newArrayList("", "", "", ""); private transient final List<String> signCopy = Lists.newArrayList("", "", "", "");
private transient long lastVanishTime = System.currentTimeMillis(); private transient long lastVanishTime = System.currentTimeMillis();
private String lastLocaleString;
private Locale playerLocale;
public User(final Player base, final IEssentials ess) { public User(final Player base, final IEssentials ess) {
super(base, ess); super(base, ess);
teleport = new AsyncTeleport(this, ess); teleport = new AsyncTeleport(this, ess);
//noinspection deprecation
legacyTeleport = new Teleport(this, ess); legacyTeleport = new Teleport(this, ess);
if (isAfk()) { if (isAfk()) {
afkPosition = this.getLocation(); afkPosition = this.getLocation();
@ -215,7 +225,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
cooldownTime.add(Calendar.SECOND, (int) cooldown); cooldownTime.add(Calendar.SECOND, (int) cooldown);
cooldownTime.add(Calendar.MILLISECOND, (int) ((cooldown * 1000.0) % 1000.0)); cooldownTime.add(Calendar.MILLISECOND, (int) ((cooldown * 1000.0) % 1000.0));
if (cooldownTime.after(now) && !isAuthorized("essentials.heal.cooldown.bypass")) { if (cooldownTime.after(now) && !isAuthorized("essentials.heal.cooldown.bypass")) {
throw new Exception(tl("timeBeforeHeal", DateUtil.formatDateDiff(cooldownTime.getTimeInMillis()))); throw new Exception(playerTl("timeBeforeHeal", DateUtil.formatDateDiff(cooldownTime.getTimeInMillis())));
} }
} }
setLastHealTimestamp(now.getTimeInMillis()); setLastHealTimestamp(now.getTimeInMillis());
@ -236,9 +246,9 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
return; return;
} }
setMoney(getMoney().add(value), cause); setMoney(getMoney().add(value), cause);
sendMessage(tl("addedToAccount", NumberUtil.displayCurrency(value, ess))); sendTl("addedToAccount", NumberUtil.displayCurrency(value, ess));
if (initiator != null) { if (initiator != null) {
initiator.sendMessage(tl("addedToOthersAccount", NumberUtil.displayCurrency(value, ess), this.getDisplayName(), NumberUtil.displayCurrency(getMoney(), ess))); initiator.sendTl("addedToOthersAccount", NumberUtil.displayCurrency(value, ess), getDisplayName(), NumberUtil.displayCurrency(getMoney(), ess));
} }
} }
@ -249,18 +259,18 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
public void payUser(final User reciever, final BigDecimal value, final UserBalanceUpdateEvent.Cause cause) throws Exception { public void payUser(final User reciever, final BigDecimal value, final UserBalanceUpdateEvent.Cause cause) throws Exception {
if (value.compareTo(BigDecimal.ZERO) < 1) { if (value.compareTo(BigDecimal.ZERO) < 1) {
throw new Exception(tl("payMustBePositive")); throw new Exception(tlLocale(playerLocale, "payMustBePositive"));
} }
if (canAfford(value)) { if (canAfford(value)) {
setMoney(getMoney().subtract(value), cause); setMoney(getMoney().subtract(value), cause);
reciever.setMoney(reciever.getMoney().add(value), cause); reciever.setMoney(reciever.getMoney().add(value), cause);
sendMessage(tl("moneySentTo", NumberUtil.displayCurrency(value, ess), reciever.getDisplayName())); sendTl("moneySentTo", NumberUtil.displayCurrency(value, ess), reciever.getDisplayName());
reciever.sendMessage(tl("moneyRecievedFrom", NumberUtil.displayCurrency(value, ess), getDisplayName())); reciever.sendTl("moneyRecievedFrom", NumberUtil.displayCurrency(value, ess), getDisplayName());
final TransactionEvent transactionEvent = new TransactionEvent(this.getSource(), reciever, value); final TransactionEvent transactionEvent = new TransactionEvent(this.getSource(), reciever, value);
ess.getServer().getPluginManager().callEvent(transactionEvent); ess.getServer().getPluginManager().callEvent(transactionEvent);
} else { } else {
throw new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(value, ess))); throw new ChargeException(tlLocale(playerLocale, "notEnoughMoney", NumberUtil.displayCurrency(value, ess)));
} }
} }
@ -283,9 +293,9 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
} catch (final MaxMoneyException ex) { } catch (final MaxMoneyException ex) {
ess.getLogger().log(Level.WARNING, "Invalid call to takeMoney, total balance can't be more than the max-money limit.", ex); ess.getLogger().log(Level.WARNING, "Invalid call to takeMoney, total balance can't be more than the max-money limit.", ex);
} }
sendMessage(tl("takenFromAccount", NumberUtil.displayCurrency(value, ess))); sendTl("takenFromAccount", NumberUtil.displayCurrency(value, ess));
if (initiator != null) { if (initiator != null) {
initiator.sendMessage(tl("takenFromOthersAccount", NumberUtil.displayCurrency(value, ess), this.getDisplayName(), NumberUtil.displayCurrency(getMoney(), ess))); initiator.sendTl("takenFromOthersAccount", NumberUtil.displayCurrency(value, ess), getDisplayName(), NumberUtil.displayCurrency(getMoney(), ess));
} }
} }
@ -325,8 +335,9 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
return true; return true;
if (VersionUtil.PRE_FLATTENING) { if (VersionUtil.PRE_FLATTENING) {
//noinspection deprecation
final int id = material.getId(); final int id = material.getId();
if (isAuthorized("essentials.itemspawn.item-" + id)) return true; return isAuthorized("essentials.itemspawn.item-" + id);
} }
return false; return false;
@ -363,6 +374,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
teleportRequestQueue.put(request.getName(), request); teleportRequestQueue.put(request.getName(), request);
} }
@SuppressWarnings("deprecation")
@Override @Override
@Deprecated @Deprecated
public boolean hasOutstandingTeleportRequest() { public boolean hasOutstandingTeleportRequest() {
@ -395,7 +407,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
} }
teleportRequestQueue.remove(playerUsername); teleportRequestQueue.remove(playerUsername);
if (inform) { if (inform) {
sendMessage(tl("requestTimedOutFrom", ess.getUser(request.getRequesterUuid()).getDisplayName())); sendTl("requestTimedOutFrom", ess.getUser(request.getRequesterUuid()).getDisplayName());
} }
return null; return null;
} }
@ -429,7 +441,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
} }
} else { } else {
if (inform) { if (inform) {
sendMessage(tl("requestTimedOutFrom", ess.getUser(request.getRequesterUuid()).getDisplayName())); sendTl("requestTimedOutFrom", ess.getUser(request.getRequesterUuid()).getDisplayName());
} }
teleportRequestQueue.remove(key); teleportRequestQueue.remove(key);
} }
@ -444,14 +456,15 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
/** /**
* Needed for backwards compatibility. * Needed for backwards compatibility.
*/ */
public String getNick(final boolean longnick) { public String getNick(@SuppressWarnings("unused") final boolean longNick) {
return getNick(true, true); return getNick(true, true);
} }
/** /**
* Needed for backwards compatibility. * Needed for backwards compatibility.
*/ */
public String getNick(final boolean longnick, final boolean withPrefix, final boolean withSuffix) { @SuppressWarnings("unused")
public String getNick(@SuppressWarnings("unused") final boolean longNick, final boolean withPrefix, final boolean withSuffix) {
return getNick(withPrefix, withSuffix); return getNick(withPrefix, withSuffix);
} }
@ -533,6 +546,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
@Override @Override
public String getDisplayName() { public String getDisplayName() {
//noinspection ConstantConditions
return super.getBase().getDisplayName() == null || (ess.getSettings().hideDisplayNameInVanish() && isHidden()) ? super.getBase().getName() : super.getBase().getDisplayName(); return super.getBase().getDisplayName() == null || (ess.getSettings().hideDisplayNameInVanish() && isHidden()) ? super.getBase().getName() : super.getBase().getDisplayName();
} }
@ -553,6 +567,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
/** /**
* @deprecated This API is not asynchronous. Use {@link User#getAsyncTeleport()} * @deprecated This API is not asynchronous. Use {@link User#getAsyncTeleport()}
*/ */
@SuppressWarnings("deprecation")
@Override @Override
@Deprecated @Deprecated
public Teleport getTeleport() { public Teleport getTeleport() {
@ -629,6 +644,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
} }
} }
@SuppressWarnings("deprecation")
@Override @Override
public void setAfk(final boolean set) { public void setAfk(final boolean set) {
setAfk(set, AfkStatusChangeEvent.Cause.UNKNOWN); setAfk(set, AfkStatusChangeEvent.Cause.UNKNOWN);
@ -722,6 +738,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
} }
//Returns true if status expired during this check //Returns true if status expired during this check
@SuppressWarnings("UnusedReturnValue")
public boolean checkJailTimeout(final long currentTime) { public boolean checkJailTimeout(final long currentTime) {
if (getJailTimeout() > 0) { if (getJailTimeout() > 0) {
@ -739,7 +756,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
setJailTimeout(0); setJailTimeout(0);
setOnlineJailedTime(0); setOnlineJailedTime(0);
setJailed(false); setJailed(false);
sendMessage(tl("haveBeenReleased")); sendTl("haveBeenReleased");
setJail(null); setJail(null);
if (ess.getSettings().getTeleportWhenFreePolicy() == ISettings.TeleportWhenFreePolicy.BACK) { if (ess.getSettings().getTeleportWhenFreePolicy() == ISettings.TeleportWhenFreePolicy.BACK) {
final CompletableFuture<Boolean> future = new CompletableFuture<>(); final CompletableFuture<Boolean> future = new CompletableFuture<>();
@ -759,6 +776,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
} }
//Returns true if status expired during this check //Returns true if status expired during this check
@SuppressWarnings("UnusedReturnValue")
public boolean checkMuteTimeout(final long currentTime) { public boolean checkMuteTimeout(final long currentTime) {
if (getMuteTimeout() > 0 && getMuteTimeout() < currentTime && isMuted()) { if (getMuteTimeout() > 0 && getMuteTimeout() < currentTime && isMuted()) {
final MuteStatusChangeEvent event = new MuteStatusChangeEvent(this, null, false, getMuteTimeout(), getMuteReason()); final MuteStatusChangeEvent event = new MuteStatusChangeEvent(this, null, false, getMuteTimeout(), getMuteReason());
@ -766,7 +784,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
if (!event.isCancelled()) { if (!event.isCancelled()) {
setMuteTimeout(0); setMuteTimeout(0);
sendMessage(tl("canTalkAgain")); sendTl("canTalkAgain");
setMuted(false); setMuted(false);
setMuteReason(null); setMuteReason(null);
return true; return true;
@ -785,15 +803,10 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
setAfk(false, cause); setAfk(false, cause);
if (broadcast && !isHidden() && !isAfk()) { if (broadcast && !isHidden() && !isAfk()) {
setDisplayNick(); setDisplayNick();
final String msg = tl("userIsNotAway", getDisplayName()); if (ess.getSettings().broadcastAfkMessage()) {
final String selfmsg = tl("userIsNotAwaySelf", getDisplayName()); ess.broadcastTl(this, u -> u == this, "userIsNotAway", getDisplayName());
if (!msg.isEmpty() && ess.getSettings().broadcastAfkMessage()) {
// exclude user from receiving general AFK announcement in favor of personal message
ess.broadcastMessage(this, msg, u -> u == this);
}
if (!selfmsg.isEmpty()) {
this.sendMessage(selfmsg);
} }
sendTl("userIsNotAwaySelf", getDisplayName());
} }
} }
lastActivity = System.currentTimeMillis(); lastActivity = System.currentTimeMillis();
@ -814,14 +827,12 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
public void updateActivityOnChat(final boolean broadcast) { public void updateActivityOnChat(final boolean broadcast) {
if (ess.getSettings().cancelAfkOnChat()) { if (ess.getSettings().cancelAfkOnChat()) {
//Chat happens async, make sure we have a sync context //Chat happens async, make sure we have a sync context
ess.scheduleSyncDelayedTask(() -> { ess.scheduleSyncDelayedTask(() -> updateActivity(broadcast, AfkStatusChangeEvent.Cause.CHAT));
updateActivity(broadcast, AfkStatusChangeEvent.Cause.CHAT);
});
} }
} }
public void checkActivity() { public void checkActivity() {
// Graceful time before the first afk check call. // Graceful time before the first afk check call.
if (System.currentTimeMillis() - lastActivity <= 10000) { if (System.currentTimeMillis() - lastActivity <= 10000) {
return; return;
} }
@ -831,13 +842,14 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
&& lastActivity > 0 && (lastActivity + (autoafkkick * 1000)) < System.currentTimeMillis() && lastActivity > 0 && (lastActivity + (autoafkkick * 1000)) < System.currentTimeMillis()
&& !isAuthorized("essentials.kick.exempt") && !isAuthorized("essentials.kick.exempt")
&& !isAuthorized("essentials.afk.kickexempt")) { && !isAuthorized("essentials.afk.kickexempt")) {
final String kickReason = tl("autoAfkKickReason", autoafkkick / 60.0);
lastActivity = 0; lastActivity = 0;
this.getBase().kickPlayer(kickReason); final double kickTime = autoafkkick / 60.0;
this.getBase().kickPlayer(AdventureUtil.miniToLegacy(playerTl("autoAfkKickReason", kickTime)));
for (final User user : ess.getOnlineUsers()) { for (final User user : ess.getOnlineUsers()) {
if (user.isAuthorized("essentials.kick.notify")) { if (user.isAuthorized("essentials.kick.notify")) {
user.sendMessage(tl("playerKicked", Console.DISPLAY_NAME, getName(), kickReason)); user.sendTl("playerKicked", Console.DISPLAY_NAME, getName(), user.playerTl("autoAfkKickReason", kickTime));
} }
} }
} }
@ -846,15 +858,10 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
setAfk(true, AfkStatusChangeEvent.Cause.ACTIVITY); setAfk(true, AfkStatusChangeEvent.Cause.ACTIVITY);
if (isAfk() && !isHidden()) { if (isAfk() && !isHidden()) {
setDisplayNick(); setDisplayNick();
final String msg = tl("userIsAway", getDisplayName()); if (ess.getSettings().broadcastAfkMessage()) {
final String selfmsg = tl("userIsAwaySelf", getDisplayName()); ess.broadcastTl(this, u -> u == this, "userIsAway", getDisplayName());
if (!msg.isEmpty() && ess.getSettings().broadcastAfkMessage()) {
// exclude user from receiving general AFK announcement in favor of personal message
ess.broadcastMessage(this, msg, u -> u == this);
}
if (!selfmsg.isEmpty()) {
this.sendMessage(selfmsg);
} }
sendTl("userIsAwaySelf", getDisplayName());
} }
} }
} }
@ -869,6 +876,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
// This enables the no-god-in-worlds functionality where the actual player god mode state is never modified in disabled worlds, // This enables the no-god-in-worlds functionality where the actual player god mode state is never modified in disabled worlds,
// but this method gets called every time the player takes damage. In the case that the world has god-mode disabled then this method // but this method gets called every time the player takes damage. In the case that the world has god-mode disabled then this method
// will return false and the player will take damage, even though they are in god mode (isGodModeEnabledRaw()). // will return false and the player will take damage, even though they are in god mode (isGodModeEnabledRaw()).
//noinspection ConstantConditions
if (!ess.getSettings().getNoGodWorlds().contains(this.getLocation().getWorld().getName())) { if (!ess.getSettings().getNoGodWorlds().contains(this.getLocation().getWorld().getName())) {
return true; return true;
} }
@ -910,6 +918,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
return ess.getPermissionsHandler().canBuild(base, getGroup()); return ess.getPermissionsHandler().canBuild(base, getGroup());
} }
@SuppressWarnings("deprecation")
@Override @Override
@Deprecated @Deprecated
public long getTeleportRequestTime() { public long getTeleportRequestTime() {
@ -978,6 +987,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
if (set) { if (set) {
for (final User user : ess.getOnlineUsers()) { for (final User user : ess.getOnlineUsers()) {
if (!user.isAuthorized("essentials.vanish.see")) { if (!user.isAuthorized("essentials.vanish.see")) {
//noinspection deprecation
user.getBase().hidePlayer(getBase()); user.getBase().hidePlayer(getBase());
} }
} }
@ -993,6 +1003,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
} }
} else { } else {
for (final Player p : ess.getOnlinePlayers()) { for (final Player p : ess.getOnlinePlayers()) {
//noinspection deprecation
p.showPlayer(getBase()); p.showPlayer(getBase());
} }
setHidden(false); setHidden(false);
@ -1052,6 +1063,48 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
} }
} }
@Override
public void sendComponent(ComponentLike component) {
ess.getBukkitAudience().player(base).sendMessage(component);
}
@Override
public Component tlComponent(String tlKey, Object... args) {
final String translation = playerTl(tlKey, args);
return AdventureUtil.miniMessage().deserialize(translation);
}
@Override
public void sendTl(String tlKey, Object... args) {
final String translation = playerTl(tlKey, args);
if (translation.trim().isEmpty()) {
return;
}
sendComponent(AdventureUtil.miniMessage().deserialize(translation));
}
@Override
public String playerTl(String tlKey, Object... args) {
if (ess.getSettings().isPerPlayerLocale()) {
return tlLocale(getPlayerLocale(ess.getPlayerLocaleProvider().getLocale(base)), tlKey, args);
}
return tlLiteral(tlKey, args);
}
@Override
public String tlSender(String tlKey, Object... args) {
return playerTl(tlKey, args);
}
public Locale getPlayerLocale(final String locale) {
if (locale.equals(lastLocaleString)) {
return playerLocale;
}
lastLocaleString = locale;
return playerLocale = I18n.getLocale(locale);
}
@Override @Override
public int compareTo(final User other) { public int compareTo(final User other) {
return FormatUtil.stripFormat(getDisplayName()).compareToIgnoreCase(FormatUtil.stripFormat(other.getDisplayName())); return FormatUtil.stripFormat(getDisplayName()).compareToIgnoreCase(FormatUtil.stripFormat(other.getDisplayName()));
@ -1073,7 +1126,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
@Override @Override
public CommandSource getSource() { public CommandSource getSource() {
return new CommandSource(getBase()); return new CommandSource(ess, getBase());
} }
@Override @Override
@ -1158,6 +1211,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
ess.getMail().sendMail(this, sender, message, expireAt); ess.getMail().sendMail(this, sender, message, expireAt);
} }
@SuppressWarnings("deprecation")
@Override @Override
@Deprecated @Deprecated
public void addMail(String mail) { public void addMail(String mail) {
@ -1169,7 +1223,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
if (unread != 0) { if (unread != 0) {
final int notifyPlayerOfMailCooldown = ess.getSettings().getNotifyPlayerOfMailCooldown() * 1000; final int notifyPlayerOfMailCooldown = ess.getSettings().getNotifyPlayerOfMailCooldown() * 1000;
if (System.currentTimeMillis() - lastNotifiedAboutMailsMs >= notifyPlayerOfMailCooldown) { if (System.currentTimeMillis() - lastNotifiedAboutMailsMs >= notifyPlayerOfMailCooldown) {
sendMessage(tl("youHaveNewMail", unread)); sendTl("youHaveNewMail", unread);
lastNotifiedAboutMailsMs = System.currentTimeMillis(); lastNotifiedAboutMailsMs = System.currentTimeMillis();
} }
} }

View File

@ -11,6 +11,7 @@ import com.earth2me.essentials.utils.StringUtil;
import com.google.common.base.Charsets; import com.google.common.base.Charsets;
import net.ess3.api.IEssentials; import net.ess3.api.IEssentials;
import net.ess3.api.MaxMoneyException; import net.ess3.api.MaxMoneyException;
import net.ess3.api.TranslatableException;
import net.essentialsx.api.v2.services.mail.MailMessage; import net.essentialsx.api.v2.services.mail.MailMessage;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.Location; import org.bukkit.Location;
@ -31,17 +32,15 @@ import java.util.UUID;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import static com.earth2me.essentials.I18n.tl;
public abstract class UserData extends PlayerExtension implements IConf { public abstract class UserData extends PlayerExtension implements IConf {
protected final transient IEssentials ess; protected final transient Essentials ess;
private final EssentialsUserConfiguration config; private final EssentialsUserConfiguration config;
private UserConfigHolder holder; private UserConfigHolder holder;
private BigDecimal money; private BigDecimal money;
protected UserData(final Player base, final IEssentials ess) { protected UserData(final Player base, final IEssentials ess) {
super(base); super(base);
this.ess = ess; this.ess = (Essentials) ess;
final File folder = new File(ess.getDataFolder(), "userdata"); final File folder = new File(ess.getDataFolder(), "userdata");
if (!folder.exists() && !folder.mkdirs()) { if (!folder.exists() && !folder.mkdirs()) {
throw new RuntimeException("Unable to create userdata folder!"); throw new RuntimeException("Unable to create userdata folder!");
@ -194,7 +193,7 @@ public abstract class UserData extends PlayerExtension implements IConf {
holder.homes().remove(search); holder.homes().remove(search);
config.save(); config.save();
} else { } else {
throw new Exception(tl("invalidHome", search)); throw new TranslatableException("invalidHome", search);
} }
} }
@ -204,7 +203,7 @@ public abstract class UserData extends PlayerExtension implements IConf {
holder.homes().put(StringUtil.safeString(newName), location); holder.homes().put(StringUtil.safeString(newName), location);
config.save(); config.save();
} else { } else {
throw new Exception(tl("invalidHome", name)); throw new TranslatableException("invalidHome", name);
} }
} }

View File

@ -2,9 +2,11 @@ package com.earth2me.essentials;
import com.earth2me.essentials.commands.WarpNotFoundException; import com.earth2me.essentials.commands.WarpNotFoundException;
import com.earth2me.essentials.config.EssentialsConfiguration; import com.earth2me.essentials.config.EssentialsConfiguration;
import com.earth2me.essentials.utils.AdventureUtil;
import com.earth2me.essentials.utils.StringUtil; import com.earth2me.essentials.utils.StringUtil;
import net.ess3.api.InvalidNameException; import net.ess3.api.InvalidNameException;
import net.ess3.api.InvalidWorldException; import net.ess3.api.InvalidWorldException;
import net.ess3.api.TranslatableException;
import org.bukkit.Location; import org.bukkit.Location;
import java.io.File; import java.io.File;
@ -17,7 +19,7 @@ import java.util.Map;
import java.util.UUID; import java.util.UUID;
import java.util.logging.Level; import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tlLiteral;
public class Warps implements IConf, net.ess3.api.IWarps { public class Warps implements IConf, net.ess3.api.IWarps {
private final Map<StringIgnoreCase, EssentialsConfiguration> warpPoints = new HashMap<>(); private final Map<StringIgnoreCase, EssentialsConfiguration> warpPoints = new HashMap<>();
@ -77,7 +79,7 @@ public class Warps implements IConf, net.ess3.api.IWarps {
if (conf == null) { if (conf == null) {
final File confFile = new File(warpsFolder, filename + ".yml"); final File confFile = new File(warpsFolder, filename + ".yml");
if (confFile.exists()) { if (confFile.exists()) {
throw new Exception(tl("similarWarpExist")); throw new Exception(user == null ? tlLiteral("similarWarpExist") : user.playerTl("similarWarpExist"));
} }
conf = new EssentialsConfiguration(confFile); conf = new EssentialsConfiguration(confFile);
conf.load(); conf.load();
@ -109,10 +111,10 @@ public class Warps implements IConf, net.ess3.api.IWarps {
public void removeWarp(final String name) throws Exception { public void removeWarp(final String name) throws Exception {
final EssentialsConfiguration conf = warpPoints.get(new StringIgnoreCase(name)); final EssentialsConfiguration conf = warpPoints.get(new StringIgnoreCase(name));
if (conf == null) { if (conf == null) {
throw new Exception(tl("warpNotExist")); throw new TranslatableException("warpNotExist");
} }
if (!conf.getFile().delete()) { if (!conf.getFile().delete()) {
throw new Exception(tl("warpDeleteError")); throw new TranslatableException("warpDeleteError");
} }
warpPoints.remove(new StringIgnoreCase(name)); warpPoints.remove(new StringIgnoreCase(name));
} }
@ -133,7 +135,7 @@ public class Warps implements IConf, net.ess3.api.IWarps {
warpPoints.put(new StringIgnoreCase(name), conf); warpPoints.put(new StringIgnoreCase(name), conf);
} }
} catch (final Exception ex) { } catch (final Exception ex) {
Essentials.getWrappedLogger().log(Level.WARNING, tl("loadWarpError", filename), ex); Essentials.getWrappedLogger().log(Level.WARNING, AdventureUtil.miniToLegacy(tlLiteral("loadWarpError", filename)), ex);
} }
} }
} }

View File

@ -5,6 +5,7 @@ import com.earth2me.essentials.config.ConfigurateUtil;
import com.earth2me.essentials.config.EssentialsConfiguration; import com.earth2me.essentials.config.EssentialsConfiguration;
import com.earth2me.essentials.craftbukkit.Inventories; import com.earth2me.essentials.craftbukkit.Inventories;
import com.earth2me.essentials.utils.VersionUtil; import com.earth2me.essentials.utils.VersionUtil;
import net.ess3.api.TranslatableException;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.spongepowered.configurate.CommentedConfigurationNode; import org.spongepowered.configurate.CommentedConfigurationNode;
@ -13,8 +14,6 @@ import java.io.File;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.Locale; import java.util.Locale;
import static com.earth2me.essentials.I18n.tl;
public class Worth implements IConf { public class Worth implements IConf {
private final EssentialsConfiguration config; private final EssentialsConfiguration config;
@ -78,7 +77,7 @@ public class Worth implements IConf {
*/ */
public int getAmount(final IEssentials ess, final User user, final ItemStack is, final String[] args, final boolean isBulkSell) throws Exception { public int getAmount(final IEssentials ess, final User user, final ItemStack is, final String[] args, final boolean isBulkSell) throws Exception {
if (is == null || is.getType() == Material.AIR) { if (is == null || is.getType() == Material.AIR) {
throw new Exception(tl("itemSellAir")); throw new TranslatableException("itemSellAir");
} }
int amount = 0; int amount = 0;
@ -98,7 +97,7 @@ public class Worth implements IConf {
final boolean requireStack = ess.getSettings().isTradeInStacks(is.getType()); final boolean requireStack = ess.getSettings().isTradeInStacks(is.getType());
if (requireStack && !stack) { if (requireStack && !stack) {
throw new Exception(tl("itemMustBeStacked")); throw new TranslatableException("itemMustBeStacked");
} }
int max = 0; int max = 0;
@ -121,9 +120,9 @@ public class Worth implements IConf {
} }
if (amount > max || amount < 1) { if (amount > max || amount < 1) {
if (!isBulkSell) { if (!isBulkSell) {
user.sendMessage(tl("itemNotEnough2")); user.sendTl("itemNotEnough2");
user.sendMessage(tl("itemNotEnough3")); user.sendTl("itemNotEnough3");
throw new Exception(tl("itemNotEnough1")); throw new TranslatableException("itemNotEnough1");
} else { } else {
return amount; return amount;
} }

View File

@ -1,16 +1,16 @@
package com.earth2me.essentials.api; package com.earth2me.essentials.api;
import static com.earth2me.essentials.I18n.tl; import net.ess3.api.TranslatableException;
/** /**
* @deprecated This exception is unused. Use {@link net.ess3.api.InvalidWorldException} instead. * @deprecated This exception is unused. Use {@link net.ess3.api.InvalidWorldException} instead.
*/ */
@Deprecated @Deprecated
public class InvalidWorldException extends Exception { public class InvalidWorldException extends TranslatableException {
private final String world; private final String world;
public InvalidWorldException(final String world) { public InvalidWorldException(final String world) {
super(tl("invalidWorld")); super("invalidWorld");
this.world = world; this.world = world;
} }

View File

@ -1,18 +1,18 @@
package com.earth2me.essentials.api; package com.earth2me.essentials.api;
import java.util.UUID; import net.ess3.api.TranslatableException;
import static com.earth2me.essentials.I18n.tl; import java.util.UUID;
/** /**
* Thrown when the requested user does not exist. * Thrown when the requested user does not exist.
*/ */
public class UserDoesNotExistException extends Exception { public class UserDoesNotExistException extends TranslatableException {
public UserDoesNotExistException(final String name) { public UserDoesNotExistException(final String name) {
super(tl("userDoesNotExist", name)); super("userDoesNotExist", name);
} }
public UserDoesNotExistException(final UUID uuid) { public UserDoesNotExistException(final UUID uuid) {
super(tl("uuidDoesNotExist", uuid.toString())); super("uuidDoesNotExist", uuid.toString());
} }
} }

View File

@ -3,14 +3,13 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.DateUtil; import com.earth2me.essentials.utils.DateUtil;
import net.ess3.api.TranslatableException;
import net.ess3.api.events.AfkStatusChangeEvent; import net.ess3.api.events.AfkStatusChangeEvent;
import org.bukkit.Server; import org.bukkit.Server;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandafk extends EssentialsCommand { public class Commandafk extends EssentialsCommand {
public Commandafk() { public Commandafk() {
super("afk"); super("afk");
@ -50,17 +49,23 @@ public class Commandafk extends EssentialsCommand {
if (sender.isMuted()) { if (sender.isMuted()) {
final String dateDiff = sender.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(sender.getMuteTimeout()) : null; final String dateDiff = sender.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(sender.getMuteTimeout()) : null;
if (dateDiff == null) { if (dateDiff == null) {
throw new Exception(sender.hasMuteReason() ? tl("voiceSilencedReason", sender.getMuteReason()) : tl("voiceSilenced")); if (sender.hasMuteReason()) {
throw new TranslatableException("voiceSilencedReason", sender.getMuteReason());
} else {
throw new TranslatableException("voiceSilenced");
}
}
if (sender.hasMuteReason()) {
throw new TranslatableException("voiceSilencedReasonTime", dateDiff, sender.getMuteReason());
} else {
throw new TranslatableException("voiceSilencedTime", dateDiff);
} }
throw new Exception(sender.hasMuteReason() ? tl("voiceSilencedReasonTime", dateDiff, sender.getMuteReason()) : tl("voiceSilencedTime", dateDiff));
} }
if (!sender.isAuthorized("essentials.afk.message")) { if (!sender.isAuthorized("essentials.afk.message")) {
throw new Exception(tl("noPermToAFKMessage")); throw new TranslatableException("noPermToAFKMessage");
} }
} }
user.setDisplayNick(); user.setDisplayNick();
String msg = "";
String selfmsg = "";
final boolean currentStatus = user.isAfk(); final boolean currentStatus = user.isAfk();
final boolean afterStatus = user.toggleAfk(AfkStatusChangeEvent.Cause.COMMAND); final boolean afterStatus = user.toggleAfk(AfkStatusChangeEvent.Cause.COMMAND);
@ -68,37 +73,39 @@ public class Commandafk extends EssentialsCommand {
return; return;
} }
String tlKey = "";
String selfTlKey = "";
if (!afterStatus) { if (!afterStatus) {
if (!user.isHidden()) { if (!user.isHidden()) {
msg = tl("userIsNotAway", user.getDisplayName()); tlKey = "userIsNotAway";
selfmsg = tl("userIsNotAwaySelf", user.getDisplayName()); selfTlKey = "userIsNotAwaySelf";
} }
user.updateActivity(false, AfkStatusChangeEvent.Cause.COMMAND); user.updateActivity(false, AfkStatusChangeEvent.Cause.COMMAND);
} else { } else {
if (!user.isHidden()) { if (!user.isHidden()) {
if (message != null) { if (message != null) {
msg = tl("userIsAwayWithMessage", user.getDisplayName(), message); tlKey = "userIsAwayWithMessage";
selfmsg = tl("userIsAwaySelfWithMessage", user.getDisplayName(), message); selfTlKey = "userIsAwaySelfWithMessage";
} else { } else {
msg = tl("userIsAway", user.getDisplayName()); tlKey = "userIsAway";
selfmsg = tl("userIsAwaySelf", user.getDisplayName()); selfTlKey = "userIsAwaySelf";
} }
} }
user.setAfkMessage(message); user.setAfkMessage(message);
} }
if (!msg.isEmpty() && ess.getSettings().broadcastAfkMessage()) { if (!tlKey.isEmpty() && ess.getSettings().broadcastAfkMessage()) {
// exclude user from receiving general AFK announcement in favor of personal message // exclude user from receiving general AFK announcement in favor of personal message
ess.broadcastMessage(user, msg, u -> u == user); ess.broadcastTl(user, u -> u == user, tlKey, user.getDisplayName(), message);
} }
if (!selfmsg.isEmpty()) { if (!selfTlKey.isEmpty()) {
user.sendMessage(selfmsg); user.sendTl(selfTlKey, user.getDisplayName(), message);
} }
user.setDisplayNick(); // Set this again after toggling user.setDisplayNick(); // Set this again after toggling
} }
@Override @Override
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
if (args.length == 1 && sender.isAuthorized("essentials.afk.others", ess)) { if (args.length == 1 && sender.isAuthorized("essentials.afk.others")) {
return getPlayers(server, sender); return getPlayers(server, sender);
} else { } else {
return Collections.emptyList(); return Collections.emptyList();

View File

@ -3,8 +3,6 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import org.bukkit.Server; import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandanvil extends EssentialsCommand { public class Commandanvil extends EssentialsCommand {
public Commandanvil() { public Commandanvil() {
@ -14,7 +12,7 @@ public class Commandanvil extends EssentialsCommand {
@Override @Override
protected void run(Server server, User user, String commandLabel, String[] args) throws Exception { protected void run(Server server, User user, String commandLabel, String[] args) throws Exception {
if (ess.getContainerProvider() == null) { if (ess.getContainerProvider() == null) {
user.sendMessage(tl("unsupportedBrand")); user.sendTl("unsupportedBrand");
return; return;
} }

View File

@ -3,13 +3,12 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.Trade; import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import net.ess3.api.TranslatableException;
import org.bukkit.Server; import org.bukkit.Server;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandback extends EssentialsCommand { public class Commandback extends EssentialsCommand {
public Commandback() { public Commandback() {
super("back"); super("back");
@ -37,13 +36,13 @@ public class Commandback extends EssentialsCommand {
private void parseOthers(final Server server, final CommandSource sender, final String[] args, final String commandLabel) throws Exception { private void parseOthers(final Server server, final CommandSource sender, final String[] args, final String commandLabel) throws Exception {
final User player = getPlayer(server, args, 0, true, false); final User player = getPlayer(server, args, 0, true, false);
sender.sendMessage(tl("backOther", player.getName())); sender.sendTl("backOther", player.getName());
teleportBack(sender, player, commandLabel); teleportBack(sender, player, commandLabel);
} }
private void teleportBack(final CommandSource sender, final User user, final String commandLabel) throws Exception { private void teleportBack(final CommandSource sender, final User user, final String commandLabel) throws Exception {
if (user.getLastLocation() == null) { if (user.getLastLocation() == null) {
throw new Exception(tl("noLocationFound")); throw new TranslatableException("noLocationFound");
} }
final String lastWorldName = user.getLastLocation().getWorld().getName(); final String lastWorldName = user.getLastLocation().getWorld().getName();
@ -53,11 +52,11 @@ public class Commandback extends EssentialsCommand {
requester = ess.getUser(sender.getPlayer()); requester = ess.getUser(sender.getPlayer());
if (user.getWorld() != user.getLastLocation().getWorld() && this.ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + lastWorldName)) { if (user.getWorld() != user.getLastLocation().getWorld() && this.ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + lastWorldName)) {
throw new Exception(tl("noPerm", "essentials.worlds." + lastWorldName)); throw new TranslatableException("noPerm", "essentials.worlds." + lastWorldName);
} }
if (!requester.isAuthorized("essentials.back.into." + lastWorldName)) { if (!requester.isAuthorized("essentials.back.into." + lastWorldName)) {
throw new Exception(tl("noPerm", "essentials.back.into." + lastWorldName)); throw new TranslatableException("noPerm", "essentials.back.into." + lastWorldName);
} }
} }

View File

@ -2,10 +2,9 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.Backup; import com.earth2me.essentials.Backup;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import net.ess3.api.TranslatableException;
import org.bukkit.Server; import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandbackup extends EssentialsCommand { public class Commandbackup extends EssentialsCommand {
public Commandbackup() { public Commandbackup() {
super("backup"); super("backup");
@ -15,13 +14,13 @@ public class Commandbackup extends EssentialsCommand {
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
final Backup backup = ess.getBackup(); final Backup backup = ess.getBackup();
if (backup == null) { if (backup == null) {
throw new Exception(tl("backupDisabled")); throw new TranslatableException("backupDisabled");
} }
final String command = ess.getSettings().getBackupCommand(); final String command = ess.getSettings().getBackupCommand();
if (command == null || "".equals(command) || "save-all".equalsIgnoreCase(command)) { if (command == null || "".equals(command) || "save-all".equalsIgnoreCase(command)) {
throw new Exception(tl("backupDisabled")); throw new TranslatableException("backupDisabled");
} }
backup.run(); backup.run();
sender.sendMessage(tl("backupStarted")); sender.sendTl("backupStarted");
} }
} }

View File

@ -8,8 +8,6 @@ import org.bukkit.Server;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandbalance extends EssentialsCommand { public class Commandbalance extends EssentialsCommand {
public Commandbalance() { public Commandbalance() {
super("balance"); super("balance");
@ -22,16 +20,16 @@ public class Commandbalance extends EssentialsCommand {
} }
final User target = getPlayer(server, args, 0, false, true); final User target = getPlayer(server, args, 0, false, true);
sender.sendMessage(tl("balanceOther", target.isHidden() ? target.getName() : target.getDisplayName(), NumberUtil.displayCurrency(target.getMoney(), ess))); sender.sendTl("balanceOther", target.isHidden() ? target.getName() : target.getDisplayName(), NumberUtil.displayCurrency(target.getMoney(), ess));
} }
@Override @Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (args.length == 1 && user.isAuthorized("essentials.balance.others")) { if (args.length == 1 && user.isAuthorized("essentials.balance.others")) {
final User target = getPlayer(server, args, 0, true, true); final User target = getPlayer(server, args, 0, true, true);
user.sendMessage(tl("balanceOther", target.isHidden() ? target.getName() : target.getDisplayName(), NumberUtil.displayCurrency(target.getMoney(), ess))); user.sendTl("balanceOther", target.isHidden() ? target.getName() : target.getDisplayName(), NumberUtil.displayCurrency(target.getMoney(), ess));
} else if (args.length < 2) { } else if (args.length < 2) {
user.sendMessage(tl("balance", NumberUtil.displayCurrency(user.getMoney(), ess))); user.sendTl("balance", NumberUtil.displayCurrency(user.getMoney(), ess));
} else { } else {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
@ -39,7 +37,7 @@ public class Commandbalance extends EssentialsCommand {
@Override @Override
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
if (args.length == 1 && sender.isAuthorized("essentials.balance.others", ess)) { if (args.length == 1 && sender.isAuthorized("essentials.balance.others")) {
return getPlayers(server, sender); return getPlayers(server, sender);
} else { } else {
return Collections.emptyList(); return Collections.emptyList();

View File

@ -3,6 +3,7 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.textreader.SimpleTextInput; import com.earth2me.essentials.textreader.SimpleTextInput;
import com.earth2me.essentials.textreader.TextPager; import com.earth2me.essentials.textreader.TextPager;
import com.earth2me.essentials.utils.AdventureUtil;
import com.earth2me.essentials.utils.NumberUtil; import com.earth2me.essentials.utils.NumberUtil;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import net.essentialsx.api.v2.services.BalanceTop; import net.essentialsx.api.v2.services.BalanceTop;
@ -18,7 +19,7 @@ import java.util.Map;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tlLiteral;
public class Commandbalancetop extends EssentialsCommand { public class Commandbalancetop extends EssentialsCommand {
public static final int MINUSERS = 50; public static final int MINUSERS = 50;
@ -34,7 +35,7 @@ public class Commandbalancetop extends EssentialsCommand {
cal.setTimeInMillis(ess.getBalanceTop().getCacheAge()); cal.setTimeInMillis(ess.getBalanceTop().getCacheAge());
final DateFormat format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); final DateFormat format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
final Runnable runnable = () -> { final Runnable runnable = () -> {
sender.sendMessage(tl("balanceTop", format.format(cal.getTime()))); sender.sendTl("balanceTop", format.format(cal.getTime()));
new TextPager(cache).showPage(Integer.toString(page), null, "balancetop", sender); new TextPager(cache).showPage(Integer.toString(page), null, "balancetop", sender);
}; };
if (sender.getSender() instanceof BlockCommandSender) { if (sender.getSender() instanceof BlockCommandSender) {
@ -65,7 +66,7 @@ public class Commandbalancetop extends EssentialsCommand {
// If there are less than 50 users in our usermap, there is no need to display a warning as these calculations should be done quickly // If there are less than 50 users in our usermap, there is no need to display a warning as these calculations should be done quickly
if (ess.getUsers().getUserCount() > MINUSERS) { if (ess.getUsers().getUserCount() > MINUSERS) {
sender.sendMessage(tl("orderBalances", ess.getUsers().getUserCount())); sender.sendTl("orderBalances", ess.getUsers().getUserCount());
} }
ess.runTaskAsynchronously(new Viewer(sender, page, force)); ess.runTaskAsynchronously(new Viewer(sender, page, force));
@ -109,11 +110,11 @@ public class Commandbalancetop extends EssentialsCommand {
future.thenRun(() -> { future.thenRun(() -> {
if (fresh) { if (fresh) {
final SimpleTextInput newCache = new SimpleTextInput(); final SimpleTextInput newCache = new SimpleTextInput();
newCache.getLines().add(tl("serverTotal", NumberUtil.displayCurrency(ess.getBalanceTop().getBalanceTopTotal(), ess))); newCache.getLines().add(AdventureUtil.miniToLegacy(tlLiteral("serverTotal", NumberUtil.displayCurrency(ess.getBalanceTop().getBalanceTopTotal(), ess))));
int pos = 1; int pos = 1;
for (final Map.Entry<UUID, BalanceTop.Entry> entry : ess.getBalanceTop().getBalanceTopCache().entrySet()) { for (final Map.Entry<UUID, BalanceTop.Entry> entry : ess.getBalanceTop().getBalanceTopCache().entrySet()) {
if (ess.getSettings().showZeroBaltop() || entry.getValue().getBalance().compareTo(BigDecimal.ZERO) > 0) { if (ess.getSettings().showZeroBaltop() || entry.getValue().getBalance().compareTo(BigDecimal.ZERO) > 0) {
newCache.getLines().add(tl("balanceTopLine", pos, entry.getValue().getDisplayName(), NumberUtil.displayCurrency(entry.getValue().getBalance(), ess))); newCache.getLines().add(AdventureUtil.miniToLegacy(tlLiteral("balanceTopLine", pos, entry.getValue().getDisplayName(), NumberUtil.displayCurrency(entry.getValue().getBalance(), ess))));
} }
pos++; pos++;
} }

View File

@ -4,7 +4,9 @@ import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.Console; import com.earth2me.essentials.Console;
import com.earth2me.essentials.OfflinePlayerStub; import com.earth2me.essentials.OfflinePlayerStub;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.AdventureUtil;
import com.earth2me.essentials.utils.FormatUtil; import com.earth2me.essentials.utils.FormatUtil;
import net.ess3.api.TranslatableException;
import org.bukkit.BanList; import org.bukkit.BanList;
import org.bukkit.Server; import org.bukkit.Server;
@ -12,7 +14,7 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.logging.Level; import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tlLiteral;
public class Commandban extends EssentialsCommand { public class Commandban extends EssentialsCommand {
public Commandban() { public Commandban() {
@ -34,10 +36,10 @@ public class Commandban extends EssentialsCommand {
} }
if (!user.getBase().isOnline()) { if (!user.getBase().isOnline()) {
if (sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.ban.offline")) { if (sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.ban.offline")) {
throw new Exception(tl("banExemptOffline")); throw new TranslatableException("banExemptOffline");
} }
} else if (user.isAuthorized("essentials.ban.exempt") && sender.isPlayer()) { } else if (user.isAuthorized("essentials.ban.exempt") && sender.isPlayer()) {
throw new Exception(tl("banExempt")); throw new TranslatableException("banExempt");
} }
final String senderName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.NAME; final String senderName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.NAME;
@ -46,21 +48,21 @@ public class Commandban extends EssentialsCommand {
if (args.length > 1) { if (args.length > 1) {
banReason = FormatUtil.replaceFormat(getFinalArg(args, 1).replace("\\n", "\n").replace("|", "\n")); banReason = FormatUtil.replaceFormat(getFinalArg(args, 1).replace("\\n", "\n").replace("|", "\n"));
} else { } else {
banReason = tl("defaultBanReason"); banReason = tlLiteral("defaultBanReason");
} }
ess.getServer().getBanList(BanList.Type.NAME).addBan(user.getName(), banReason, null, senderName); ess.getServer().getBanList(BanList.Type.NAME).addBan(user.getName(), banReason, null, senderName);
final String banDisplay = tl("banFormat", banReason, senderDisplayName); final String banDisplay = tlLiteral("banFormat", banReason, senderDisplayName);
user.getBase().kickPlayer(banDisplay); user.getBase().kickPlayer(AdventureUtil.miniToLegacy(banDisplay));
ess.getLogger().log(Level.INFO, tl("playerBanned", senderDisplayName, user.getName(), banDisplay)); ess.getLogger().log(Level.INFO, AdventureUtil.miniToLegacy(tlLiteral("playerBanned", senderDisplayName, user.getName(), banDisplay)));
if (nomatch) { if (nomatch) {
sender.sendMessage(tl("userUnknown", user.getName())); sender.sendTl("userUnknown", user.getName());
} }
ess.broadcastMessage("essentials.ban.notify", tl("playerBanned", senderDisplayName, user.getName(), banReason)); ess.broadcastTl(null, u -> !u.isAuthorized("essentials.ban.notify"), "playerBanned", senderDisplayName, user.getName(), banReason);
} }
@Override @Override

View File

@ -3,6 +3,7 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.Console; import com.earth2me.essentials.Console;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.AdventureUtil;
import com.earth2me.essentials.utils.FormatUtil; import com.earth2me.essentials.utils.FormatUtil;
import org.bukkit.BanList; import org.bukkit.BanList;
import org.bukkit.Server; import org.bukkit.Server;
@ -12,7 +13,7 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.logging.Level; import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tlLiteral;
public class Commandbanip extends EssentialsCommand { public class Commandbanip extends EssentialsCommand {
public Commandbanip() { public Commandbanip() {
@ -48,13 +49,13 @@ public class Commandbanip extends EssentialsCommand {
if (args.length > 1) { if (args.length > 1) {
banReason = FormatUtil.replaceFormat(getFinalArg(args, 1).replace("\\n", "\n").replace("|", "\n")); banReason = FormatUtil.replaceFormat(getFinalArg(args, 1).replace("\\n", "\n").replace("|", "\n"));
} else { } else {
banReason = tl("defaultBanReason"); banReason = tlLiteral("defaultBanReason");
} }
final String banDisplay = tl("banFormat", banReason, senderDisplayName); final String banDisplay = AdventureUtil.miniToLegacy(tlLiteral("banFormat", banReason, senderDisplayName));
ess.getServer().getBanList(BanList.Type.IP).addBan(ipAddress, banReason, null, senderName); ess.getServer().getBanList(BanList.Type.IP).addBan(ipAddress, banReason, null, senderName);
ess.getLogger().log(Level.INFO, tl("playerBanIpAddress", senderDisplayName, ipAddress, banReason)); ess.getLogger().log(Level.INFO, AdventureUtil.miniToLegacy(tlLiteral("playerBanIpAddress", senderDisplayName, ipAddress, banReason)));
for (final Player player : ess.getServer().getOnlinePlayers()) { for (final Player player : ess.getServer().getOnlinePlayers()) {
if (player.getAddress().getAddress().getHostAddress().equalsIgnoreCase(ipAddress)) { if (player.getAddress().getAddress().getHostAddress().equalsIgnoreCase(ipAddress)) {
@ -62,7 +63,7 @@ public class Commandbanip extends EssentialsCommand {
} }
} }
ess.broadcastMessage("essentials.banip.notify", tl("playerBanIpAddress", senderDisplayName, ipAddress, banReason)); ess.broadcastTl(null, u -> !u.isAuthorized("essentials.banip.notify"), "playerBanIpAddress", senderDisplayName, ipAddress, banReason);
} }
@Override @Override

View File

@ -7,8 +7,6 @@ import org.bukkit.Location;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import static com.earth2me.essentials.I18n.tl;
public class Commandbeezooka extends EssentialsCommand { public class Commandbeezooka extends EssentialsCommand {
public Commandbeezooka() { public Commandbeezooka() {
@ -18,7 +16,7 @@ public class Commandbeezooka extends EssentialsCommand {
@Override @Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_15_R01)) { if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_15_R01)) {
user.sendMessage(tl("unsupportedFeature")); user.sendTl("unsupportedFeature");
return; return;
} }

View File

@ -3,6 +3,7 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.LocationUtil; import com.earth2me.essentials.utils.LocationUtil;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import net.ess3.api.TranslatableException;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.TreeType; import org.bukkit.TreeType;
@ -10,8 +11,6 @@ import org.bukkit.TreeType;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandbigtree extends EssentialsCommand { public class Commandbigtree extends EssentialsCommand {
public Commandbigtree() { public Commandbigtree() {
super("bigtree"); super("bigtree");
@ -34,13 +33,13 @@ public class Commandbigtree extends EssentialsCommand {
final Location loc = LocationUtil.getTarget(user.getBase(), ess.getSettings().getMaxTreeCommandRange()).add(0, 1, 0); final Location loc = LocationUtil.getTarget(user.getBase(), ess.getSettings().getMaxTreeCommandRange()).add(0, 1, 0);
if (loc.getBlock().getType().isSolid()) { if (loc.getBlock().getType().isSolid()) {
throw new Exception(tl("bigTreeFailure")); throw new TranslatableException("bigTreeFailure");
} }
final boolean success = user.getWorld().generateTree(loc, tree); final boolean success = user.getWorld().generateTree(loc, tree);
if (success) { if (success) {
user.sendMessage(tl("bigTreeSuccess")); user.sendTl("bigTreeSuccess");
} else { } else {
throw new Exception(tl("bigTreeFailure")); throw new TranslatableException("bigTreeFailure");
} }
} }

View File

@ -1,10 +1,11 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.FormatUtil;
import com.earth2me.essentials.craftbukkit.Inventories; import com.earth2me.essentials.craftbukkit.Inventories;
import com.earth2me.essentials.utils.EnumUtil; import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.FormatUtil;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import net.ess3.api.TranslatableException;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
@ -13,8 +14,6 @@ import org.bukkit.inventory.meta.BookMeta;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandbook extends EssentialsCommand { public class Commandbook extends EssentialsCommand {
private static final Material WRITABLE_BOOK = EnumUtil.getMaterial("WRITABLE_BOOK", "BOOK_AND_QUILL"); private static final Material WRITABLE_BOOK = EnumUtil.getMaterial("WRITABLE_BOOK", "BOOK_AND_QUILL");
@ -35,27 +34,27 @@ public class Commandbook extends EssentialsCommand {
final String newAuthor = FormatUtil.formatString(user, "essentials.book.author", getFinalArg(args, 1)).trim(); final String newAuthor = FormatUtil.formatString(user, "essentials.book.author", getFinalArg(args, 1)).trim();
bmeta.setAuthor(newAuthor); bmeta.setAuthor(newAuthor);
item.setItemMeta(bmeta); item.setItemMeta(bmeta);
user.sendMessage(tl("bookAuthorSet", newAuthor)); user.sendTl("bookAuthorSet", newAuthor);
} else { } else {
throw new Exception(tl("denyChangeAuthor")); throw new TranslatableException("denyChangeAuthor");
} }
} else if (args.length > 1 && args[0].equalsIgnoreCase("title")) { } else if (args.length > 1 && args[0].equalsIgnoreCase("title")) {
if (user.isAuthorized("essentials.book.title") && (isAuthor(bmeta, player) || user.isAuthorized("essentials.book.others"))) { if (user.isAuthorized("essentials.book.title") && (isAuthor(bmeta, player) || user.isAuthorized("essentials.book.others"))) {
final String newTitle = FormatUtil.formatString(user, "essentials.book.title", getFinalArg(args, 1)).trim(); final String newTitle = FormatUtil.formatString(user, "essentials.book.title", getFinalArg(args, 1)).trim();
bmeta.setTitle(newTitle); bmeta.setTitle(newTitle);
item.setItemMeta(bmeta); item.setItemMeta(bmeta);
user.sendMessage(tl("bookTitleSet", newTitle)); user.sendTl("bookTitleSet", newTitle);
} else { } else {
throw new Exception(tl("denyChangeTitle")); throw new TranslatableException("denyChangeTitle");
} }
} else { } else {
if (isAuthor(bmeta, player) || user.isAuthorized("essentials.book.others")) { if (isAuthor(bmeta, player) || user.isAuthorized("essentials.book.others")) {
final ItemStack newItem = new ItemStack(WRITABLE_BOOK, item.getAmount()); final ItemStack newItem = new ItemStack(WRITABLE_BOOK, item.getAmount());
newItem.setItemMeta(bmeta); newItem.setItemMeta(bmeta);
Inventories.setItemInMainHand(user.getBase(), newItem); Inventories.setItemInMainHand(user.getBase(), newItem);
user.sendMessage(tl("editBookContents")); user.sendTl("editBookContents");
} else { } else {
throw new Exception(tl("denyBookEdit")); throw new TranslatableException("denyBookEdit");
} }
} }
} else if (item.getType() == WRITABLE_BOOK) { } else if (item.getType() == WRITABLE_BOOK) {
@ -66,9 +65,9 @@ public class Commandbook extends EssentialsCommand {
final ItemStack newItem = new ItemStack(Material.WRITTEN_BOOK, item.getAmount()); final ItemStack newItem = new ItemStack(Material.WRITTEN_BOOK, item.getAmount());
newItem.setItemMeta(bmeta); newItem.setItemMeta(bmeta);
Inventories.setItemInMainHand(user.getBase(), newItem); Inventories.setItemInMainHand(user.getBase(), newItem);
user.sendMessage(tl("bookLocked")); user.sendTl("bookLocked");
} else { } else {
throw new Exception(tl("holdBook")); throw new TranslatableException("holdBook");
} }
} }

View File

@ -9,8 +9,6 @@ import org.bukkit.event.player.PlayerTeleportEvent;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import static com.earth2me.essentials.I18n.tl;
public class Commandbottom extends EssentialsCommand { public class Commandbottom extends EssentialsCommand {
public Commandbottom() { public Commandbottom() {
@ -28,7 +26,7 @@ public class Commandbottom extends EssentialsCommand {
final CompletableFuture<Boolean> future = getNewExceptionFuture(user.getSource(), commandLabel); final CompletableFuture<Boolean> future = getNewExceptionFuture(user.getSource(), commandLabel);
future.thenAccept(success -> { future.thenAccept(success -> {
if (success) { if (success) {
user.sendMessage(tl("teleportBottom", safe.getWorld().getName(), safe.getBlockX(), safe.getBlockY(), safe.getBlockZ())); user.sendTl("teleportBottom", safe.getWorld().getName(), safe.getBlockX(), safe.getBlockY(), safe.getBlockZ());
} }
}); });
user.getAsyncTeleport().teleport(safe, new Trade(this.getName(), ess), PlayerTeleportEvent.TeleportCause.COMMAND, future); user.getAsyncTeleport().teleport(safe, new Trade(this.getName(), ess), PlayerTeleportEvent.TeleportCause.COMMAND, future);

View File

@ -1,13 +1,12 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import net.ess3.api.TranslatableException;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockBreakEvent;
import static com.earth2me.essentials.I18n.tl;
public class Commandbreak extends EssentialsCommand { public class Commandbreak extends EssentialsCommand {
public Commandbreak() { public Commandbreak() {
super("break"); super("break");
@ -22,7 +21,7 @@ public class Commandbreak extends EssentialsCommand {
throw new NoChargeException(); throw new NoChargeException();
} }
if (block.getType() == Material.BEDROCK && !user.isAuthorized("essentials.break.bedrock")) { if (block.getType() == Material.BEDROCK && !user.isAuthorized("essentials.break.bedrock")) {
throw new Exception(tl("noBreakBedrock")); throw new TranslatableException("noBreakBedrock");
} }
//final List<ItemStack> list = (List<ItemStack>)block.getDrops(); //final List<ItemStack> list = (List<ItemStack>)block.getDrops();
//final BlockBreakEvent event = new BlockBreakEvent(block, user.getBase(), list); //final BlockBreakEvent event = new BlockBreakEvent(block, user.getBase(), list);

View File

@ -4,8 +4,6 @@ import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.utils.FormatUtil; import com.earth2me.essentials.utils.FormatUtil;
import org.bukkit.Server; import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandbroadcast extends EssentialsCommand { public class Commandbroadcast extends EssentialsCommand {
public Commandbroadcast() { public Commandbroadcast() {
super("broadcast"); super("broadcast");
@ -17,6 +15,6 @@ public class Commandbroadcast extends EssentialsCommand {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
ess.broadcastMessage(tl("broadcast", FormatUtil.replaceFormat(getFinalArg(args, 0)).replace("\\n", "\n"), sender.getDisplayName())); ess.broadcastTl("broadcast", FormatUtil.replaceFormat(getFinalArg(args, 0)).replace("\\n", "\n"), sender.getDisplayName());
} }
} }

View File

@ -2,21 +2,15 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.textreader.IText; import com.earth2me.essentials.utils.AdventureUtil;
import com.earth2me.essentials.textreader.KeywordReplacer;
import com.earth2me.essentials.textreader.SimpleTextInput;
import com.earth2me.essentials.utils.FormatUtil;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import net.ess3.api.TranslatableException;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.entity.Player;
import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandbroadcastworld extends EssentialsCommand { public class Commandbroadcastworld extends EssentialsCommand {
public Commandbroadcastworld() { public Commandbroadcastworld() {
@ -50,7 +44,7 @@ public class Commandbroadcastworld extends EssentialsCommand {
final World world = ess.getWorld(args[0]); final World world = ess.getWorld(args[0]);
if (world == null) { if (world == null) {
throw new Exception(tl("invalidWorld")); throw new TranslatableException("invalidWorld");
} }
sendBroadcast(world, sender.getSender().getName(), getFinalArg(args, 1)); sendBroadcast(world, sender.getSender().getName(), getFinalArg(args, 1));
} }
@ -59,22 +53,7 @@ public class Commandbroadcastworld extends EssentialsCommand {
if (message.isEmpty()) { if (message.isEmpty()) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
sendToWorld(world, tl("broadcast", FormatUtil.replaceFormat(message).replace("\\n", "\n"), name)); ess.broadcastTl(null, u -> u.getBase().getWorld().equals(world), true, "broadcast", message, AdventureUtil.parsed(AdventureUtil.legacyToMini(name)));
}
private void sendToWorld(final World world, final String message) {
IText broadcast = new SimpleTextInput(message);
final Collection<Player> players = ess.getOnlinePlayers();
for (final Player player : players) {
if (player.getWorld().equals(world)) {
final User user = ess.getUser(player);
broadcast = new KeywordReplacer(broadcast, new CommandSource(player), ess, false);
for (final String messageText : broadcast.getLines()) {
user.sendMessage(messageText);
}
}
}
} }
@Override @Override

View File

@ -7,8 +7,6 @@ import org.bukkit.Server;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandburn extends EssentialsCommand { public class Commandburn extends EssentialsCommand {
public Commandburn() { public Commandburn() {
super("burn"); super("burn");
@ -22,7 +20,7 @@ public class Commandburn extends EssentialsCommand {
final User user = getPlayer(server, sender, args, 0); final User user = getPlayer(server, sender, args, 0);
user.getBase().setFireTicks(Integer.parseInt(args[1]) * 20); user.getBase().setFireTicks(Integer.parseInt(args[1]) * 20);
sender.sendMessage(tl("burnMsg", user.getDisplayName(), Integer.parseInt(args[1]))); sender.sendTl("burnMsg", user.getDisplayName(), Integer.parseInt(args[1]));
} }
@Override @Override

View File

@ -3,8 +3,6 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import org.bukkit.Server; import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandcartographytable extends EssentialsCommand { public class Commandcartographytable extends EssentialsCommand {
public Commandcartographytable() { public Commandcartographytable() {
@ -14,7 +12,7 @@ public class Commandcartographytable extends EssentialsCommand {
@Override @Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (ess.getContainerProvider() == null) { if (ess.getContainerProvider() == null) {
user.sendMessage(tl("unsupportedBrand")); user.sendTl("unsupportedBrand");
return; return;
} }

View File

@ -19,8 +19,6 @@ import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Set; import java.util.Set;
import static com.earth2me.essentials.I18n.tl;
public class Commandclearinventory extends EssentialsCommand { public class Commandclearinventory extends EssentialsCommand {
private static final int EXTENDED_CAP = 8; private static final int EXTENDED_CAP = 8;
@ -55,7 +53,7 @@ public class Commandclearinventory extends EssentialsCommand {
} }
if (allowAll && args.length > 0 && args[0].contentEquals("*")) { if (allowAll && args.length > 0 && args[0].contentEquals("*")) {
sender.sendMessage(tl("inventoryClearingFromAll")); sender.sendTl("inventoryClearingFromAll");
offset = 1; offset = 1;
players = ess.getOnlinePlayers(); players = ess.getOnlinePlayers();
} else if (allowOthers && args.length > 0 && args[0].trim().length() > 2) { } else if (allowOthers && args.length > 0 && args[0].trim().length() > 2) {
@ -72,7 +70,7 @@ public class Commandclearinventory extends EssentialsCommand {
if (senderUser != null && senderUser.isPromptingClearConfirm()) { if (senderUser != null && senderUser.isPromptingClearConfirm()) {
if (!formattedCommand.equals(previousClearCommand)) { if (!formattedCommand.equals(previousClearCommand)) {
senderUser.setConfirmingClearCommand(formattedCommand); senderUser.setConfirmingClearCommand(formattedCommand);
senderUser.sendMessage(tl("confirmClear", formattedCommand)); senderUser.sendTl("confirmClear", formattedCommand);
return; return;
} }
} }
@ -115,7 +113,7 @@ public class Commandclearinventory extends EssentialsCommand {
if (type != ClearHandlerType.SPECIFIC_ITEM) { if (type != ClearHandlerType.SPECIFIC_ITEM) {
final boolean armor = type == ClearHandlerType.ALL_INCLUDING_ARMOR; final boolean armor = type == ClearHandlerType.ALL_INCLUDING_ARMOR;
if (showExtended) { if (showExtended) {
sender.sendMessage(tl(armor ? "inventoryClearingAllArmor" : "inventoryClearingAllItems", player.getDisplayName())); sender.sendTl(armor ? "inventoryClearingAllArmor" : "inventoryClearingAllItems", player.getDisplayName());
} }
Inventories.removeItems(player, item -> true, armor); Inventories.removeItems(player, item -> true, armor);
} else { } else {
@ -130,15 +128,15 @@ public class Commandclearinventory extends EssentialsCommand {
if (amount == -1) { if (amount == -1) {
final int removedAmount = Inventories.removeItemSimilar(player, stack, true); final int removedAmount = Inventories.removeItemSimilar(player, stack, true);
if (removedAmount > 0 || showExtended) { if (removedAmount > 0 || showExtended) {
sender.sendMessage(tl("inventoryClearingStack", removedAmount, stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName())); sender.sendTl("inventoryClearingStack", removedAmount, stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName());
} }
} else { } else {
stack.setAmount(amount < 0 ? 1 : amount); stack.setAmount(amount < 0 ? 1 : amount);
if (Inventories.removeItemAmount(player, stack, amount)) { if (Inventories.removeItemAmount(player, stack, amount)) {
sender.sendMessage(tl("inventoryClearingStack", amount, stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName())); sender.sendTl("inventoryClearingStack", amount, stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName());
} else { } else {
if (showExtended) { if (showExtended) {
sender.sendMessage(tl("inventoryClearFail", player.getDisplayName(), amount, stack.getType().toString().toLowerCase(Locale.ENGLISH))); sender.sendTl("inventoryClearFail", player.getDisplayName(), amount, stack.getType().toString().toLowerCase(Locale.ENGLISH));
} }
} }
} }

View File

@ -3,8 +3,6 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import org.bukkit.Server; import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandclearinventoryconfirmtoggle extends EssentialsCommand { public class Commandclearinventoryconfirmtoggle extends EssentialsCommand {
public Commandclearinventoryconfirmtoggle() { public Commandclearinventoryconfirmtoggle() {
@ -21,9 +19,9 @@ public class Commandclearinventoryconfirmtoggle extends EssentialsCommand {
} }
user.setPromptingClearConfirm(confirmingClear); user.setPromptingClearConfirm(confirmingClear);
if (confirmingClear) { if (confirmingClear) {
user.sendMessage(tl("clearInventoryConfirmToggleOn")); user.sendTl("clearInventoryConfirmToggleOn");
} else { } else {
user.sendMessage(tl("clearInventoryConfirmToggleOff")); user.sendTl("clearInventoryConfirmToggleOff");
} }
user.setConfirmingClearCommand(null); user.setConfirmingClearCommand(null);
} }

View File

@ -3,8 +3,6 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import org.bukkit.Server; import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandcompass extends EssentialsCommand { public class Commandcompass extends EssentialsCommand {
public Commandcompass() { public Commandcompass() {
super("compass"); super("compass");
@ -15,24 +13,24 @@ public class Commandcompass extends EssentialsCommand {
final int bearing = (int) (user.getLocation().getYaw() + 180 + 360) % 360; final int bearing = (int) (user.getLocation().getYaw() + 180 + 360) % 360;
final String dir; final String dir;
if (bearing < 23) { if (bearing < 23) {
dir = tl("north"); dir = user.playerTl("north");
} else if (bearing < 68) { } else if (bearing < 68) {
dir = tl("northEast"); dir = user.playerTl("northEast");
} else if (bearing < 113) { } else if (bearing < 113) {
dir = tl("east"); dir = user.playerTl("east");
} else if (bearing < 158) { } else if (bearing < 158) {
dir = tl("southEast"); dir = user.playerTl("southEast");
} else if (bearing < 203) { } else if (bearing < 203) {
dir = tl("south"); dir = user.playerTl("south");
} else if (bearing < 248) { } else if (bearing < 248) {
dir = tl("southWest"); dir = user.playerTl("southWest");
} else if (bearing < 293) { } else if (bearing < 293) {
dir = tl("west"); dir = user.playerTl("west");
} else if (bearing < 338) { } else if (bearing < 338) {
dir = tl("northWest"); dir = user.playerTl("northWest");
} else { } else {
dir = tl("north"); dir = user.playerTl("north");
} }
user.sendMessage(tl("compassBearing", dir, bearing)); user.sendTl("compassBearing", dir, bearing);
} }
} }

View File

@ -23,8 +23,6 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static com.earth2me.essentials.I18n.tl;
public class Commandcondense extends EssentialsCommand { public class Commandcondense extends EssentialsCommand {
private final Map<ItemStack, SimpleRecipe> condenseList = new HashMap<>(); private final Map<ItemStack, SimpleRecipe> condenseList = new HashMap<>();
@ -58,9 +56,9 @@ public class Commandcondense extends EssentialsCommand {
user.getBase().updateInventory(); user.getBase().updateInventory();
if (didConvert) { if (didConvert) {
user.sendMessage(tl("itemsConverted")); user.sendTl("itemsConverted");
} else { } else {
user.sendMessage(tl("itemsNotConverted")); user.sendTl("itemsNotConverted");
throw new NoChargeException(); throw new NoChargeException();
} }
} }

View File

@ -5,6 +5,7 @@ import com.earth2me.essentials.User;
import com.earth2me.essentials.craftbukkit.Inventories; import com.earth2me.essentials.craftbukkit.Inventories;
import com.earth2me.essentials.utils.DateUtil; import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.PasteUtil; import com.earth2me.essentials.utils.PasteUtil;
import net.ess3.api.TranslatableException;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
@ -21,7 +22,7 @@ import java.util.List;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.logging.Level; import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tlLiteral;
public class Commandcreatekit extends EssentialsCommand { public class Commandcreatekit extends EssentialsCommand {
public Commandcreatekit() { public Commandcreatekit() {
@ -44,7 +45,7 @@ public class Commandcreatekit extends EssentialsCommand {
boolean useSerializationProvider = ess.getSettings().isUseBetterKits(); boolean useSerializationProvider = ess.getSettings().isUseBetterKits();
if (useSerializationProvider && ess.getSerializationProvider() == null) { if (useSerializationProvider && ess.getSerializationProvider() == null) {
ess.showError(user.getSource(), new Exception(tl("createKitUnsupported")), commandLabel); ess.showError(user.getSource(), new TranslatableException("createKitUnsupported"), commandLabel);
useSerializationProvider = false; useSerializationProvider = false;
} }
@ -62,7 +63,7 @@ public class Commandcreatekit extends EssentialsCommand {
// Some users might want to directly write to config knowing the consequences. *shrug* // Some users might want to directly write to config knowing the consequences. *shrug*
if (!ess.getSettings().isPastebinCreateKit()) { if (!ess.getSettings().isPastebinCreateKit()) {
ess.getKits().addKit(kitname, list, delay); ess.getKits().addKit(kitname, list, delay);
user.sendMessage(tl("createdKit", kitname, list.size(), delay)); user.sendTl("createdKit", kitname, list.size(), delay);
} else { } else {
uploadPaste(user.getSource(), kitname, delay, list); uploadPaste(user.getSource(), kitname, delay, list);
} }
@ -86,10 +87,10 @@ public class Commandcreatekit extends EssentialsCommand {
final CompletableFuture<PasteUtil.PasteResult> future = PasteUtil.createPaste(Collections.singletonList(new PasteUtil.PasteFile("kit_" + kitName + ".yml", fileContents))); final CompletableFuture<PasteUtil.PasteResult> future = PasteUtil.createPaste(Collections.singletonList(new PasteUtil.PasteFile("kit_" + kitName + ".yml", fileContents)));
future.thenAccept(result -> { future.thenAccept(result -> {
if (result != null) { if (result != null) {
final String separator = tl("createKitSeparator"); final String separator = tlLiteral("createKitSeparator");
final String delayFormat = delay <= 0 ? "0" : DateUtil.formatDateDiff(System.currentTimeMillis() + (delay * 1000)); final String delayFormat = delay <= 0 ? "0" : DateUtil.formatDateDiff(System.currentTimeMillis() + (delay * 1000));
sender.sendMessage(separator); sender.sendMessage(separator);
sender.sendMessage(tl("createKitSuccess", kitName, delayFormat, result.getPasteUrl())); sender.sendTl("createKitSuccess", kitName, delayFormat, result.getPasteUrl());
sender.sendMessage(separator); sender.sendMessage(separator);
if (ess.getSettings().isDebug()) { if (ess.getSettings().isDebug()) {
ess.getLogger().info(sender.getSender().getName() + " created a kit: " + result.getPasteUrl()); ess.getLogger().info(sender.getSender().getName() + " created a kit: " + result.getPasteUrl());
@ -97,12 +98,12 @@ public class Commandcreatekit extends EssentialsCommand {
} }
}); });
future.exceptionally(throwable -> { future.exceptionally(throwable -> {
sender.sendMessage(tl("createKitFailed", kitName)); sender.sendTl("createKitFailed", kitName);
ess.getLogger().log(Level.SEVERE, "Error creating kit: ", throwable); ess.getLogger().log(Level.SEVERE, "Error creating kit: ", throwable);
return null; return null;
}); });
} catch (Exception e) { } catch (Exception e) {
sender.sendMessage(tl("createKitFailed", kitName)); sender.sendTl("createKitFailed", kitName);
ess.getLogger().log(Level.SEVERE, "Error creating kit: ", e); ess.getLogger().log(Level.SEVERE, "Error creating kit: ", e);
} }
}); });

View File

@ -3,6 +3,7 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.IUser; import com.earth2me.essentials.IUser;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import net.ess3.api.TranslatableException;
import net.essentialsx.api.v2.events.HomeModifyEvent; import net.essentialsx.api.v2.events.HomeModifyEvent;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Server; import org.bukkit.Server;
@ -12,8 +13,6 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import static com.earth2me.essentials.I18n.tl;
public class Commanddelhome extends EssentialsCommand { public class Commanddelhome extends EssentialsCommand {
public Commanddelhome() { public Commanddelhome() {
super("delhome"); super("delhome");
@ -47,10 +46,10 @@ public class Commanddelhome extends EssentialsCommand {
} }
if (name.equals("bed")) { if (name.equals("bed")) {
throw new Exception(tl("invalidHomeName")); throw new TranslatableException("invalidHomeName");
} }
final HomeModifyEvent event = new HomeModifyEvent(sender.getUser(ess), user, name, user.getHome(name), false); final HomeModifyEvent event = new HomeModifyEvent(sender.getUser(), user, name, user.getHome(name), false);
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) { if (event.isCancelled()) {
if (ess.getSettings().isDebug()) { if (ess.getSettings().isDebug()) {
@ -60,13 +59,13 @@ public class Commanddelhome extends EssentialsCommand {
} }
user.delHome(name); user.delHome(name);
sender.sendMessage(tl("deleteHome", name)); sender.sendTl("deleteHome", name);
} }
@Override @Override
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
final IUser user = sender.getUser(ess); final IUser user = sender.getUser();
final boolean canDelOthers = sender.isAuthorized("essentials.delhome.others", ess); final boolean canDelOthers = sender.isAuthorized("essentials.delhome.others");
if (args.length == 1) { if (args.length == 1) {
final List<String> homes = user == null ? new ArrayList<>() : user.getHomes(); final List<String> homes = user == null ? new ArrayList<>() : user.getHomes();
if (canDelOthers) { if (canDelOthers) {

View File

@ -1,14 +1,13 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import net.ess3.api.TranslatableException;
import org.bukkit.Server; import org.bukkit.Server;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commanddeljail extends EssentialsCommand { public class Commanddeljail extends EssentialsCommand {
public Commanddeljail() { public Commanddeljail() {
super("deljail"); super("deljail");
@ -21,11 +20,11 @@ public class Commanddeljail extends EssentialsCommand {
} }
if (ess.getJails().getJail(args[0]) == null) { if (ess.getJails().getJail(args[0]) == null) {
throw new Exception(tl("jailNotExist")); throw new TranslatableException("jailNotExist");
} }
ess.getJails().removeJail(args[0]); ess.getJails().removeJail(args[0]);
sender.sendMessage(tl("deleteJail", args[0])); sender.sendTl("deleteJail", args[0]);
} }
@Override @Override

View File

@ -8,8 +8,6 @@ import org.bukkit.Server;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commanddelkit extends EssentialsCommand { public class Commanddelkit extends EssentialsCommand {
public Commanddelkit() { public Commanddelkit() {
super("delkit"); super("delkit");
@ -19,7 +17,7 @@ public class Commanddelkit extends EssentialsCommand {
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (args.length == 0) { if (args.length == 0) {
final String kitList = ess.getKits().listKits(ess, null); final String kitList = ess.getKits().listKits(ess, null);
sender.sendMessage(kitList.length() > 0 ? tl("kits", kitList) : tl("noKits")); sender.sendTl(kitList.length() > 0 ? "kits" : "noKits", kitList);
throw new NoChargeException(); throw new NoChargeException();
} else { } else {
final String kitName = ess.getKits().matchKit(args[0]); final String kitName = ess.getKits().matchKit(args[0]);
@ -30,7 +28,7 @@ public class Commanddelkit extends EssentialsCommand {
} }
ess.getKits().removeKit(kitName); ess.getKits().removeKit(kitName);
sender.sendMessage(tl("deleteKit", kitName)); sender.sendTl("deleteKit", kitName);
} }
} }

View File

@ -1,6 +1,7 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import net.ess3.api.TranslatableException;
import net.essentialsx.api.v2.events.WarpModifyEvent; import net.essentialsx.api.v2.events.WarpModifyEvent;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
@ -10,8 +11,6 @@ import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commanddelwarp extends EssentialsCommand { public class Commanddelwarp extends EssentialsCommand {
public Commanddelwarp() { public Commanddelwarp() {
super("delwarp"); super("delwarp");
@ -31,15 +30,15 @@ public class Commanddelwarp extends EssentialsCommand {
// World is unloaded/deleted // World is unloaded/deleted
location = null; location = null;
} }
final WarpModifyEvent event = new WarpModifyEvent(sender.getUser(this.ess), args[0], location, null, WarpModifyEvent.WarpModifyCause.DELETE); final WarpModifyEvent event = new WarpModifyEvent(sender.getUser(), args[0], location, null, WarpModifyEvent.WarpModifyCause.DELETE);
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) { if (event.isCancelled()) {
return; return;
} }
ess.getWarps().removeWarp(args[0]); ess.getWarps().removeWarp(args[0]);
sender.sendMessage(tl("deleteWarp", args[0])); sender.sendTl("deleteWarp", args[0]);
} else { } else {
throw new Exception(tl("warpNotExist")); throw new TranslatableException("warpNotExist");
} }
} }

View File

@ -3,8 +3,6 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import org.bukkit.Server; import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commanddepth extends EssentialsCommand { public class Commanddepth extends EssentialsCommand {
public Commanddepth() { public Commanddepth() {
super("depth"); super("depth");
@ -14,11 +12,11 @@ public class Commanddepth extends EssentialsCommand {
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
final int depth = user.getLocation().getBlockY() - user.getWorld().getSeaLevel(); final int depth = user.getLocation().getBlockY() - user.getWorld().getSeaLevel();
if (depth > 0) { if (depth > 0) {
user.sendMessage(tl("depthAboveSea", depth)); user.sendTl("depthAboveSea", depth);
} else if (depth < 0) { } else if (depth < 0) {
user.sendMessage(tl("depthBelowSea", -depth)); user.sendTl("depthBelowSea", -depth);
} else { } else {
user.sendMessage(tl("depth")); user.sendTl("depth");
} }
} }
} }

View File

@ -3,8 +3,6 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import org.bukkit.Server; import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commanddisposal extends EssentialsCommand { public class Commanddisposal extends EssentialsCommand {
public Commanddisposal() { public Commanddisposal() {
@ -13,8 +11,8 @@ public class Commanddisposal extends EssentialsCommand {
@Override @Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
user.sendMessage(tl("openingDisposal")); user.sendTl("openingDisposal");
user.getBase().openInventory(ess.getServer().createInventory(user.getBase(), 36, tl("disposal"))); user.getBase().openInventory(ess.getServer().createInventory(user.getBase(), 36, user.playerTl("disposal")));
} }
} }

View File

@ -6,6 +6,7 @@ import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.NumberUtil; import com.earth2me.essentials.utils.NumberUtil;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import net.ess3.api.MaxMoneyException; import net.ess3.api.MaxMoneyException;
import net.ess3.api.TranslatableException;
import net.ess3.api.events.UserBalanceUpdateEvent; import net.ess3.api.events.UserBalanceUpdateEvent;
import org.bukkit.Server; import org.bukkit.Server;
@ -14,8 +15,6 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import static com.earth2me.essentials.I18n.tl;
public class Commandeco extends EssentialsLoopCommand { public class Commandeco extends EssentialsLoopCommand {
public Commandeco() { public Commandeco() {
@ -54,7 +53,7 @@ public class Commandeco extends EssentialsLoopCommand {
if (player.getMoney().subtract(userAmount).compareTo(ess.getSettings().getMinMoney()) >= 0) { if (player.getMoney().subtract(userAmount).compareTo(ess.getSettings().getMinMoney()) >= 0) {
player.takeMoney(userAmount, sender, UserBalanceUpdateEvent.Cause.COMMAND_ECO); player.takeMoney(userAmount, sender, UserBalanceUpdateEvent.Cause.COMMAND_ECO);
} else { } else {
ess.showError(sender, new Exception(tl("minimumBalanceError", NumberUtil.displayCurrency(ess.getSettings().getMinMoney(), ess))), commandLabel); ess.showError(sender, new TranslatableException("minimumBalanceError", NumberUtil.displayCurrency(ess.getSettings().getMinMoney(), ess)), commandLabel);
} }
break; break;
} }
@ -65,8 +64,8 @@ public class Commandeco extends EssentialsLoopCommand {
final boolean underMin = userAmount.compareTo(minBal) < 0; final boolean underMin = userAmount.compareTo(minBal) < 0;
final boolean aboveMax = userAmount.compareTo(maxBal) > 0; final boolean aboveMax = userAmount.compareTo(maxBal) > 0;
player.setMoney(underMin ? minBal : aboveMax ? maxBal : userAmount, UserBalanceUpdateEvent.Cause.COMMAND_ECO); player.setMoney(underMin ? minBal : aboveMax ? maxBal : userAmount, UserBalanceUpdateEvent.Cause.COMMAND_ECO);
player.sendMessage(tl("setBal", NumberUtil.displayCurrency(player.getMoney(), ess))); player.sendTl("setBal", NumberUtil.displayCurrency(player.getMoney(), ess));
sender.sendMessage(tl("setBalOthers", player.getDisplayName(), NumberUtil.displayCurrency(player.getMoney(), ess))); sender.sendTl("setBalOthers", player.getDisplayName(), NumberUtil.displayCurrency(player.getMoney(), ess));
break; break;
} }
} }

View File

@ -5,6 +5,7 @@ import com.earth2me.essentials.utils.FormatUtil;
import com.earth2me.essentials.utils.NumberUtil; import com.earth2me.essentials.utils.NumberUtil;
import com.earth2me.essentials.utils.VersionUtil; import com.earth2me.essentials.utils.VersionUtil;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import net.ess3.api.TranslatableException;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.Server; import org.bukkit.Server;
@ -23,8 +24,6 @@ import org.bukkit.util.Vector;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandeditsign extends EssentialsCommand { public class Commandeditsign extends EssentialsCommand {
public Commandeditsign() { public Commandeditsign() {
super("editsign"); super("editsign");
@ -38,7 +37,7 @@ public class Commandeditsign extends EssentialsCommand {
final Block target = user.getTargetBlock(5); //5 is a good number final Block target = user.getTargetBlock(5); //5 is a good number
if (!(target.getState() instanceof Sign)) { if (!(target.getState() instanceof Sign)) {
throw new Exception(tl("editsignCommandTarget")); throw new TranslatableException("editsignCommandTarget");
} }
final ModifiableSign sign = wrapSign((Sign) target.getState(), user); final ModifiableSign sign = wrapSign((Sign) target.getState(), user);
try { try {
@ -47,14 +46,14 @@ public class Commandeditsign extends EssentialsCommand {
final int line = Integer.parseInt(args[1]) - 1; final int line = Integer.parseInt(args[1]) - 1;
final String text = FormatUtil.formatString(user, "essentials.editsign", getFinalArg(args, 2)).trim(); final String text = FormatUtil.formatString(user, "essentials.editsign", getFinalArg(args, 2)).trim();
if (ChatColor.stripColor(text).length() > 15 && !user.isAuthorized("essentials.editsign.unlimited")) { if (ChatColor.stripColor(text).length() > 15 && !user.isAuthorized("essentials.editsign.unlimited")) {
throw new Exception(tl("editsignCommandLimit")); throw new TranslatableException("editsignCommandLimit");
} }
existingLines[line] = text; existingLines[line] = text;
if (callSignEvent(sign, user.getBase(), existingLines)) { if (callSignEvent(sign, user.getBase(), existingLines)) {
return; return;
} }
user.sendMessage(tl("editsignCommandSetSuccess", line + 1, text)); user.sendTl("editsignCommandSetSuccess", line + 1, text);
} else if (args[0].equalsIgnoreCase("clear")) { } else if (args[0].equalsIgnoreCase("clear")) {
if (args.length == 1) { if (args.length == 1) {
final String[] existingLines = sign.getLines(); final String[] existingLines = sign.getLines();
@ -66,7 +65,7 @@ public class Commandeditsign extends EssentialsCommand {
return; return;
} }
user.sendMessage(tl("editsignCommandClear")); user.sendTl("editsignCommandClear");
} else { } else {
final String[] existingLines = sign.getLines(); final String[] existingLines = sign.getLines();
final int line = Integer.parseInt(args[1]) - 1; final int line = Integer.parseInt(args[1]) - 1;
@ -76,7 +75,7 @@ public class Commandeditsign extends EssentialsCommand {
return; return;
} }
user.sendMessage(tl("editsignCommandClearLine", line + 1)); user.sendTl("editsignCommandClearLine", line + 1);
} }
} else if (args[0].equalsIgnoreCase("copy")) { } else if (args[0].equalsIgnoreCase("copy")) {
final int line = args.length == 1 ? -1 : Integer.parseInt(args[1]) - 1; final int line = args.length == 1 ? -1 : Integer.parseInt(args[1]) - 1;
@ -86,11 +85,11 @@ public class Commandeditsign extends EssentialsCommand {
// We use unformat here to prevent players from copying signs with colors that they do not have permission to use. // We use unformat here to prevent players from copying signs with colors that they do not have permission to use.
user.getSignCopy().set(i, FormatUtil.unformatString(user, "essentials.editsign", sign.getLine(i))); user.getSignCopy().set(i, FormatUtil.unformatString(user, "essentials.editsign", sign.getLine(i)));
} }
user.sendMessage(tl("editsignCopy", commandLabel)); user.sendTl("editsignCopy", commandLabel);
} else { } else {
// We use unformat here to prevent players from copying signs with colors that they do not have permission to use. // We use unformat here to prevent players from copying signs with colors that they do not have permission to use.
user.getSignCopy().set(line, FormatUtil.unformatString(user, "essentials.editsign", sign.getLine(line))); user.getSignCopy().set(line, FormatUtil.unformatString(user, "essentials.editsign", sign.getLine(line)));
user.sendMessage(tl("editsignCopyLine", line + 1, commandLabel)); user.sendTl("editsignCopyLine", line + 1, commandLabel);
} }
} else if (args[0].equalsIgnoreCase("paste")) { } else if (args[0].equalsIgnoreCase("paste")) {
@ -101,10 +100,10 @@ public class Commandeditsign extends EssentialsCommand {
for (int i = 0; i < 4; i++) { for (int i = 0; i < 4; i++) {
existingLines[i] = FormatUtil.formatString(user, "essentials.editsign", user.getSignCopy().get(i)); existingLines[i] = FormatUtil.formatString(user, "essentials.editsign", user.getSignCopy().get(i));
} }
user.sendMessage(tl("editsignPaste", commandLabel)); user.sendTl("editsignPaste", commandLabel);
} else { } else {
existingLines[line] = FormatUtil.formatString(user, "essentials.editsign", user.getSignCopy().get(line)); existingLines[line] = FormatUtil.formatString(user, "essentials.editsign", user.getSignCopy().get(line));
user.sendMessage(tl("editsignPasteLine", line + 1, commandLabel)); user.sendTl("editsignPasteLine", line + 1, commandLabel);
} }
callSignEvent(sign, user.getBase(), existingLines); callSignEvent(sign, user.getBase(), existingLines);
@ -112,7 +111,7 @@ public class Commandeditsign extends EssentialsCommand {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
} catch (final IndexOutOfBoundsException e) { } catch (final IndexOutOfBoundsException e) {
throw new Exception(tl("editsignCommandNoLine"), e); throw new TranslatableException(e, "editsignCommandNoLine");
} }
} }

View File

@ -5,6 +5,7 @@ import com.earth2me.essentials.MetaItemStack;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.StringUtil; import com.earth2me.essentials.utils.StringUtil;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import net.ess3.api.TranslatableException;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.enchantments.Enchantment; import org.bukkit.enchantments.Enchantment;
@ -18,8 +19,6 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.TreeSet; import java.util.TreeSet;
import static com.earth2me.essentials.I18n.tl;
public class Commandenchant extends EssentialsCommand { public class Commandenchant extends EssentialsCommand {
public Commandenchant() { public Commandenchant() {
super("enchant"); super("enchant");
@ -30,7 +29,7 @@ public class Commandenchant extends EssentialsCommand {
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
final ItemStack stack = user.getItemInHand(); final ItemStack stack = user.getItemInHand();
if (stack == null || stack.getType() == Material.AIR) { if (stack == null || stack.getType() == Material.AIR) {
throw new Exception(tl("nothingInHand")); throw new TranslatableException("nothingInHand");
} }
if (args.length == 0) { if (args.length == 0) {
@ -41,7 +40,7 @@ public class Commandenchant extends EssentialsCommand {
usableEnchants.add(entry.getKey()); usableEnchants.add(entry.getKey());
} }
} }
throw new NotEnoughArgumentsException(tl("enchantments", StringUtil.joinList(usableEnchants.toArray()))); throw new NotEnoughArgumentsException(user.playerTl("enchantments", StringUtil.joinList(usableEnchants.toArray())));
} }
int level = 1; int level = 1;
@ -60,9 +59,9 @@ public class Commandenchant extends EssentialsCommand {
user.getBase().updateInventory(); user.getBase().updateInventory();
final String enchantName = enchantment.getName().toLowerCase(Locale.ENGLISH).replace('_', ' '); final String enchantName = enchantment.getName().toLowerCase(Locale.ENGLISH).replace('_', ' ');
if (level == 0) { if (level == 0) {
user.sendMessage(tl("enchantmentRemoved", enchantName)); user.sendTl("enchantmentRemoved", enchantName);
} else { } else {
user.sendMessage(tl("enchantmentApplied", enchantName)); user.sendTl("enchantmentApplied", enchantName);
} }
} }

View File

@ -7,6 +7,7 @@ import com.earth2me.essentials.craftbukkit.Inventories;
import com.earth2me.essentials.economy.EconomyLayer; import com.earth2me.essentials.economy.EconomyLayer;
import com.earth2me.essentials.economy.EconomyLayers; import com.earth2me.essentials.economy.EconomyLayers;
import com.earth2me.essentials.userstorage.ModernUserMap; import com.earth2me.essentials.userstorage.ModernUserMap;
import com.earth2me.essentials.utils.AdventureUtil;
import com.earth2me.essentials.utils.CommandMapUtil; import com.earth2me.essentials.utils.CommandMapUtil;
import com.earth2me.essentials.utils.DateUtil; import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.EnumUtil; import com.earth2me.essentials.utils.EnumUtil;
@ -20,8 +21,10 @@ import com.google.gson.JsonArray;
import com.google.gson.JsonNull; import com.google.gson.JsonNull;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive; import com.google.gson.JsonPrimitive;
import net.ess3.api.TranslatableException;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.Server; import org.bukkit.Server;
@ -59,7 +62,7 @@ import java.util.function.Supplier;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tlLiteral;
// This command has 4 undocumented behaviours #EasterEgg // This command has 4 undocumented behaviours #EasterEgg
public class Commandessentials extends EssentialsCommand { public class Commandessentials extends EssentialsCommand {
@ -177,7 +180,7 @@ public class Commandessentials extends EssentialsCommand {
} }
public void runItemTest(Server server, CommandSource sender, String commandLabel, String[] args) { public void runItemTest(Server server, CommandSource sender, String commandLabel, String[] args) {
if (!sender.isAuthorized("essentials.itemtest", ess) || args.length < 2 || !sender.isPlayer()) { if (!sender.isAuthorized("essentials.itemtest") || args.length < 2 || !sender.isPlayer()) {
return; return;
} }
@ -234,11 +237,11 @@ public class Commandessentials extends EssentialsCommand {
// Lists commands that are being handed over to other plugins. // Lists commands that are being handed over to other plugins.
private void runCommands(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { private void runCommands(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
if (ess.getAlternativeCommandsHandler().disabledCommands().size() == 0) { if (ess.getAlternativeCommandsHandler().disabledCommands().size() == 0) {
sender.sendMessage(tl("blockListEmpty")); sender.sendTl("blockListEmpty");
return; return;
} }
sender.sendMessage(tl("blockList")); sender.sendTl("blockList");
for (final Map.Entry<String, String> entry : ess.getAlternativeCommandsHandler().disabledCommands().entrySet()) { for (final Map.Entry<String, String> entry : ess.getAlternativeCommandsHandler().disabledCommands().entrySet()) {
sender.sendMessage(entry.getKey() + " => " + entry.getValue()); sender.sendMessage(entry.getKey() + " => " + entry.getValue());
} }
@ -246,7 +249,7 @@ public class Commandessentials extends EssentialsCommand {
// Generates a paste of useful information // Generates a paste of useful information
private void runDump(Server server, CommandSource sender, String commandLabel, String[] args) { private void runDump(Server server, CommandSource sender, String commandLabel, String[] args) {
sender.sendMessage(tl("dumpCreating")); sender.sendTl("dumpCreating");
final JsonObject dump = new JsonObject(); final JsonObject dump = new JsonObject();
@ -378,7 +381,7 @@ public class Commandessentials extends EssentialsCommand {
try { try {
files.add(new PasteUtil.PasteFile("config.yml", new String(Files.readAllBytes(ess.getSettings().getConfigFile().toPath()), StandardCharsets.UTF_8))); files.add(new PasteUtil.PasteFile("config.yml", new String(Files.readAllBytes(ess.getSettings().getConfigFile().toPath()), StandardCharsets.UTF_8)));
} catch (IOException e) { } catch (IOException e) {
sender.sendMessage(tl("dumpErrorUpload", "config.yml", e.getMessage())); sender.sendTl("dumpErrorUpload", "config.yml", e.getMessage());
} }
} }
@ -388,7 +391,7 @@ public class Commandessentials extends EssentialsCommand {
new String(Files.readAllBytes(essDiscord.getDataFolder().toPath().resolve("config.yml")), StandardCharsets.UTF_8) new String(Files.readAllBytes(essDiscord.getDataFolder().toPath().resolve("config.yml")), StandardCharsets.UTF_8)
.replaceAll("[A-Za-z\\d]{24}\\.[\\w-]{6}\\.[\\w-]{27}", "<censored token>"))); .replaceAll("[A-Za-z\\d]{24}\\.[\\w-]{6}\\.[\\w-]{27}", "<censored token>")));
} catch (IOException e) { } catch (IOException e) {
sender.sendMessage(tl("dumpErrorUpload", "discord-config.yml", e.getMessage())); sender.sendTl("dumpErrorUpload", "discord-config.yml", e.getMessage());
} }
if (essDiscordLink != null) { if (essDiscordLink != null) {
@ -396,7 +399,7 @@ public class Commandessentials extends EssentialsCommand {
files.add(new PasteUtil.PasteFile("discord-link-config.yml", files.add(new PasteUtil.PasteFile("discord-link-config.yml",
new String(Files.readAllBytes(essDiscordLink.getDataFolder().toPath().resolve("config.yml")), StandardCharsets.UTF_8))); new String(Files.readAllBytes(essDiscordLink.getDataFolder().toPath().resolve("config.yml")), StandardCharsets.UTF_8)));
} catch (IOException e) { } catch (IOException e) {
sender.sendMessage(tl("dumpErrorUpload", "discord-link-config.yml", e.getMessage())); sender.sendTl("dumpErrorUpload", "discord-link-config.yml", e.getMessage());
} }
} }
} }
@ -405,7 +408,7 @@ public class Commandessentials extends EssentialsCommand {
try { try {
files.add(new PasteUtil.PasteFile("kits.yml", new String(Files.readAllBytes(ess.getKits().getFile().toPath()), StandardCharsets.UTF_8))); files.add(new PasteUtil.PasteFile("kits.yml", new String(Files.readAllBytes(ess.getKits().getFile().toPath()), StandardCharsets.UTF_8)));
} catch (IOException e) { } catch (IOException e) {
sender.sendMessage(tl("dumpErrorUpload", "kits.yml", e.getMessage())); sender.sendTl("dumpErrorUpload", "kits.yml", e.getMessage());
} }
} }
@ -415,7 +418,7 @@ public class Commandessentials extends EssentialsCommand {
.replaceAll("(?m)^\\[\\d\\d:\\d\\d:\\d\\d] \\[.+/(?:DEBUG|TRACE)]: .+\\s(?:[A-Za-z.]+:.+\\s(?:\\t.+\\s)*)?\\s*(?:\"[A-Za-z]+\" : .+[\\s}\\]]+)*", "") .replaceAll("(?m)^\\[\\d\\d:\\d\\d:\\d\\d] \\[.+/(?:DEBUG|TRACE)]: .+\\s(?:[A-Za-z.]+:.+\\s(?:\\t.+\\s)*)?\\s*(?:\"[A-Za-z]+\" : .+[\\s}\\]]+)*", "")
.replaceAll("(?:[0-9]{1,3}\\.){3}[0-9]{1,3}", "<censored ip address>"))); .replaceAll("(?:[0-9]{1,3}\\.){3}[0-9]{1,3}", "<censored ip address>")));
} catch (IOException e) { } catch (IOException e) {
sender.sendMessage(tl("dumpErrorUpload", "latest.log", e.getMessage())); sender.sendTl("dumpErrorUpload", "latest.log", e.getMessage());
} }
} }
@ -423,7 +426,7 @@ public class Commandessentials extends EssentialsCommand {
try { try {
files.add(new PasteUtil.PasteFile("worth.yml", new String(Files.readAllBytes(ess.getWorth().getFile().toPath()), StandardCharsets.UTF_8))); files.add(new PasteUtil.PasteFile("worth.yml", new String(Files.readAllBytes(ess.getWorth().getFile().toPath()), StandardCharsets.UTF_8)));
} catch (IOException e) { } catch (IOException e) {
sender.sendMessage(tl("dumpErrorUpload", "worth.yml", e.getMessage())); sender.sendTl("dumpErrorUpload", "worth.yml", e.getMessage());
} }
} }
@ -431,7 +434,7 @@ public class Commandessentials extends EssentialsCommand {
try { try {
files.add(new PasteUtil.PasteFile("tpr.yml", new String(Files.readAllBytes(ess.getRandomTeleport().getFile().toPath()), StandardCharsets.UTF_8))); files.add(new PasteUtil.PasteFile("tpr.yml", new String(Files.readAllBytes(ess.getRandomTeleport().getFile().toPath()), StandardCharsets.UTF_8)));
} catch (IOException e) { } catch (IOException e) {
sender.sendMessage(tl("dumpErrorUpload", "tpr.yml", e.getMessage())); sender.sendTl("dumpErrorUpload", "tpr.yml", e.getMessage());
} }
} }
@ -439,7 +442,7 @@ public class Commandessentials extends EssentialsCommand {
try { try {
files.add(new PasteUtil.PasteFile("spawn.yml", new String(Files.readAllBytes(ess.getDataFolder().toPath().resolve("spawn.yml")), StandardCharsets.UTF_8))); files.add(new PasteUtil.PasteFile("spawn.yml", new String(Files.readAllBytes(ess.getDataFolder().toPath().resolve("spawn.yml")), StandardCharsets.UTF_8)));
} catch (IOException e) { } catch (IOException e) {
sender.sendMessage(tl("dumpErrorUpload", "spawn.yml", e.getMessage())); sender.sendTl("dumpErrorUpload", "spawn.yml", e.getMessage());
} }
} }
@ -449,7 +452,7 @@ public class Commandessentials extends EssentialsCommand {
files.add(new PasteUtil.PasteFile("commandmap.json", CommandMapUtil.toJsonPretty(ess, knownCommandsCopy))); files.add(new PasteUtil.PasteFile("commandmap.json", CommandMapUtil.toJsonPretty(ess, knownCommandsCopy)));
files.add(new PasteUtil.PasteFile("commandoverride.json", disabledCommandsCopy.toString())); files.add(new PasteUtil.PasteFile("commandoverride.json", disabledCommandsCopy.toString()));
} catch (IOException e) { } catch (IOException e) {
sender.sendMessage(tl("dumpErrorUpload", "commands.yml", e.getMessage())); sender.sendTl("dumpErrorUpload", "commands.yml", e.getMessage());
} }
} }
@ -457,17 +460,17 @@ public class Commandessentials extends EssentialsCommand {
future.thenAccept(result -> { future.thenAccept(result -> {
if (result != null) { if (result != null) {
final String dumpUrl = "https://essentialsx.net/dump.html?id=" + result.getPasteId(); final String dumpUrl = "https://essentialsx.net/dump.html?id=" + result.getPasteId();
sender.sendMessage(tl("dumpUrl", dumpUrl)); sender.sendTl("dumpUrl", dumpUrl);
sender.sendMessage(tl("dumpDeleteKey", result.getDeletionKey())); sender.sendTl("dumpDeleteKey", result.getDeletionKey());
if (sender.isPlayer()) { if (sender.isPlayer()) {
ess.getLogger().info(tl("dumpConsoleUrl", dumpUrl)); ess.getLogger().info(AdventureUtil.miniToLegacy(tlLiteral("dumpConsoleUrl", dumpUrl)));
ess.getLogger().info(tl("dumpDeleteKey", result.getDeletionKey())); ess.getLogger().info(AdventureUtil.miniToLegacy(tlLiteral("dumpDeleteKey", result.getDeletionKey())));
} }
} }
files.clear(); files.clear();
}); });
future.exceptionally(throwable -> { future.exceptionally(throwable -> {
sender.sendMessage(tl("dumpError", throwable.getMessage())); sender.sendTl("dumpError", throwable.getMessage());
return null; return null;
}); });
}); });
@ -492,7 +495,7 @@ public class Commandessentials extends EssentialsCommand {
// Reloads all reloadable configs. // Reloads all reloadable configs.
private void runReload(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { private void runReload(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
ess.reload(); ess.reload();
sender.sendMessage(tl("essentialsReload", ess.getDescription().getVersion())); sender.sendTl("essentialsReload", ess.getDescription().getVersion());
} }
// Pop tarts. // Pop tarts.
@ -536,10 +539,10 @@ public class Commandessentials extends EssentialsCommand {
throw new Exception("/<command> cleanup <days> [money] [homes]"); throw new Exception("/<command> cleanup <days> [money] [homes]");
} }
sender.sendMessage(tl("cleaning")); sender.sendTl("cleaning");
final long daysArg = Long.parseLong(args[1]); final long daysArg = Long.parseLong(args[1]);
final double moneyArg = args.length >= 3 ? FloatUtil.parseDouble(args[2].replaceAll("[^0-9\\.]", "")) : 0; final double moneyArg = args.length >= 3 ? FloatUtil.parseDouble(args[2].replaceAll("[^0-9.]", "")) : 0;
final int homesArg = args.length >= 4 && NumberUtil.isInt(args[3]) ? Integer.parseInt(args[3]) : 0; final int homesArg = args.length >= 4 && NumberUtil.isInt(args[3]) ? Integer.parseInt(args[3]) : 0;
ess.runTaskAsynchronously(() -> { ess.runTaskAsynchronously(() -> {
@ -577,7 +580,7 @@ public class Commandessentials extends EssentialsCommand {
user.reset(); user.reset();
} }
sender.sendMessage(tl("cleaned")); sender.sendTl("cleaned");
}); });
} }
@ -592,7 +595,7 @@ public class Commandessentials extends EssentialsCommand {
switch (args[1]) { switch (args[1]) {
case "fix": case "fix":
sender.sendMessage(tl("fixingHomes")); sender.sendTl("fixingHomes");
ess.runTaskAsynchronously(() -> { ess.runTaskAsynchronously(() -> {
for (final UUID u : ess.getUsers().getAllUserUUIDs()) { for (final UUID u : ess.getUsers().getAllUserUUIDs()) {
final User user = ess.getUsers().loadUncachedUser(u); final User user = ess.getUsers().loadUncachedUser(u);
@ -609,15 +612,19 @@ public class Commandessentials extends EssentialsCommand {
} }
} }
} }
sender.sendMessage(tl("fixedHomes")); sender.sendTl("fixedHomes");
}); });
break; break;
case "delete": case "delete":
final boolean filterByWorld = args.length >= 3; final boolean filterByWorld = args.length >= 3;
if (filterByWorld && server.getWorld(args[2]) == null) { if (filterByWorld && server.getWorld(args[2]) == null) {
throw new Exception(tl("invalidWorld")); throw new TranslatableException("invalidWorld");
}
if (filterByWorld) {
sender.sendTl("deletingHomesWorld", args[2]);
} else {
sender.sendTl("deletingHomes");
} }
sender.sendMessage(filterByWorld ? tl("deletingHomesWorld", args[2]) : tl("deletingHomes"));
ess.runTaskAsynchronously(() -> { ess.runTaskAsynchronously(() -> {
for (final UUID u : ess.getUsers().getAllUserUUIDs()) { for (final UUID u : ess.getUsers().getAllUserUUIDs()) {
final User user = ess.getUsers().loadUncachedUser(u); final User user = ess.getUsers().loadUncachedUser(u);
@ -635,7 +642,12 @@ public class Commandessentials extends EssentialsCommand {
} }
} }
} }
sender.sendMessage(filterByWorld ? tl("deletedHomesWorld", args[2]) : tl("deletedHomes"));
if (filterByWorld) {
sender.sendTl("deletedHomesWorld", args[2]);
} else {
sender.sendTl("deletedHomes");
}
}); });
break; break;
default: default:
@ -645,21 +657,21 @@ public class Commandessentials extends EssentialsCommand {
// Gets information about cached users // Gets information about cached users
private void runUserMap(final CommandSource sender, final String[] args) { private void runUserMap(final CommandSource sender, final String[] args) {
if (!sender.isAuthorized("essentials.usermap", ess)) { if (!sender.isAuthorized("essentials.usermap")) {
return; return;
} }
final ModernUserMap userMap = (ModernUserMap) ess.getUsers(); final ModernUserMap userMap = (ModernUserMap) ess.getUsers();
sender.sendMessage(tl("usermapSize", userMap.getCachedCount(), userMap.getUserCount(), ess.getSettings().getMaxUserCacheCount())); sender.sendTl("usermapSize", userMap.getCachedCount(), userMap.getUserCount(), ess.getSettings().getMaxUserCacheCount());
if (args.length > 1) { if (args.length > 1) {
if (args[1].equals("full")) { if (args[1].equals("full")) {
for (final Map.Entry<String, UUID> entry : userMap.getNameCache().entrySet()) { for (final Map.Entry<String, UUID> entry : userMap.getNameCache().entrySet()) {
sender.sendMessage(tl("usermapEntry", entry.getKey(), entry.getValue().toString())); sender.sendTl("usermapEntry", entry.getKey(), entry.getValue().toString());
} }
} else if (args[1].equals("purge")) { } else if (args[1].equals("purge")) {
final boolean seppuku = args.length > 2 && args[2].equals("iknowwhatimdoing"); final boolean seppuku = args.length > 2 && args[2].equals("iknowwhatimdoing");
sender.sendMessage(tl("usermapPurge", String.valueOf(seppuku))); sender.sendTl("usermapPurge", String.valueOf(seppuku));
final Set<UUID> uuids = new HashSet<>(ess.getUsers().getAllUserUUIDs()); final Set<UUID> uuids = new HashSet<>(ess.getUsers().getAllUserUUIDs());
ess.runTaskAsynchronously(() -> { ess.runTaskAsynchronously(() -> {
@ -701,18 +713,18 @@ public class Commandessentials extends EssentialsCommand {
ess.getLogger().info("Found " + total + " orphaned userdata files."); ess.getLogger().info("Found " + total + " orphaned userdata files.");
}); });
} else if (args[1].equalsIgnoreCase("cache")) { } else if (args[1].equalsIgnoreCase("cache")) {
sender.sendMessage(tl("usermapKnown", ess.getUsers().getAllUserUUIDs().size(), ess.getUsers().getNameCache().size())); sender.sendTl("usermapKnown", ess.getUsers().getAllUserUUIDs().size(), ess.getUsers().getNameCache().size());
} else { } else {
try { try {
final UUID uuid = UUID.fromString(args[1]); final UUID uuid = UUID.fromString(args[1]);
for (final Map.Entry<String, UUID> entry : userMap.getNameCache().entrySet()) { for (final Map.Entry<String, UUID> entry : userMap.getNameCache().entrySet()) {
if (entry.getValue().equals(uuid)) { if (entry.getValue().equals(uuid)) {
sender.sendMessage(tl("usermapEntry", entry.getKey(), args[1])); sender.sendTl("usermapEntry", entry.getKey(), args[1]);
} }
} }
} catch (IllegalArgumentException ignored) { } catch (IllegalArgumentException ignored) {
final String sanitizedName = userMap.getSanitizedName(args[1]); final String sanitizedName = userMap.getSanitizedName(args[1]);
sender.sendMessage(tl("usermapEntry", sanitizedName, userMap.getNameCache().get(sanitizedName).toString())); sender.sendTl("usermapEntry", sanitizedName, userMap.getNameCache().get(sanitizedName).toString());
} }
} }
} }
@ -738,9 +750,9 @@ public class Commandessentials extends EssentialsCommand {
serverMessageKey = "versionOutputWarn"; serverMessageKey = "versionOutputWarn";
} }
sender.sendMessage(tl(serverMessageKey, "Server", server.getBukkitVersion() + " " + server.getVersion())); sender.sendTl(serverMessageKey, "Server", server.getBukkitVersion() + " " + server.getVersion());
sender.sendMessage(tl(serverMessageKey, "Brand", server.getName())); sender.sendTl(serverMessageKey, "Brand", server.getName());
sender.sendMessage(tl("versionOutputFine", "EssentialsX", essVer)); sender.sendTl("versionOutputFine", "EssentialsX", essVer);
for (final Plugin plugin : pm.getPlugins()) { for (final Plugin plugin : pm.getPlugins()) {
final PluginDescriptionFile desc = plugin.getDescription(); final PluginDescriptionFile desc = plugin.getDescription();
@ -753,22 +765,22 @@ public class Commandessentials extends EssentialsCommand {
if (!version.equalsIgnoreCase(essVer)) { if (!version.equalsIgnoreCase(essVer)) {
isMismatched = true; isMismatched = true;
sender.sendMessage(tl("versionOutputWarn", name, version)); sender.sendTl("versionOutputWarn", name, version);
} else { } else {
sender.sendMessage(tl("versionOutputFine", name, version)); sender.sendTl("versionOutputFine", name, version);
} }
} else { } else {
sender.sendMessage(tl("versionOutputUnsupported", name, version)); sender.sendTl("versionOutputUnsupported", name, version);
isUnsupported = true; isUnsupported = true;
} }
} }
if (versionPlugins.contains(name)) { if (versionPlugins.contains(name)) {
if (warnPlugins.contains(name)) { if (warnPlugins.contains(name)) {
sender.sendMessage(tl("versionOutputUnsupported", name, version)); sender.sendTl("versionOutputUnsupported", name, version);
isUnsupported = true; isUnsupported = true;
} else { } else {
sender.sendMessage(tl("versionOutputFine", name, version)); sender.sendTl("versionOutputFine", name, version);
} }
} }
@ -784,48 +796,48 @@ public class Commandessentials extends EssentialsCommand {
} else { } else {
layer = "None"; layer = "None";
} }
sender.sendMessage(tl("versionOutputEconLayer", layer)); sender.sendTl("versionOutputEconLayer", layer);
if (isMismatched) { if (isMismatched) {
sender.sendMessage(tl("versionMismatchAll")); sender.sendTl("versionMismatchAll");
} }
if (!isVaultInstalled) { if (!isVaultInstalled) {
sender.sendMessage(tl("versionOutputVaultMissing")); sender.sendTl("versionOutputVaultMissing");
} }
if (isUnsupported) { if (isUnsupported) {
sender.sendMessage(tl("versionOutputUnsupportedPlugins")); sender.sendTl("versionOutputUnsupportedPlugins");
} }
switch (supportStatus) { switch (supportStatus) {
case NMS_CLEANROOM: case NMS_CLEANROOM:
sender.sendMessage(ChatColor.DARK_RED + tl("serverUnsupportedCleanroom")); sender.sendComponent(sender.tlComponent("serverUnsupportedCleanroom").color(NamedTextColor.DARK_RED));
break; break;
case DANGEROUS_FORK: case DANGEROUS_FORK:
sender.sendMessage(ChatColor.DARK_RED + tl("serverUnsupportedDangerous")); sender.sendComponent(sender.tlComponent("serverUnsupportedDangerous").color(NamedTextColor.DARK_RED));
break; break;
case STUPID_PLUGIN: case STUPID_PLUGIN:
sender.sendMessage(ChatColor.DARK_RED + tl("serverUnsupportedDumbPlugins")); sender.sendComponent(sender.tlComponent("serverUnsupportedDumbPlugins").color(NamedTextColor.DARK_RED));
break; break;
case UNSTABLE: case UNSTABLE:
sender.sendMessage(ChatColor.DARK_RED + tl("serverUnsupportedMods")); sender.sendComponent(sender.tlComponent("serverUnsupportedMods").color(NamedTextColor.DARK_RED));
break; break;
case OUTDATED: case OUTDATED:
sender.sendMessage(ChatColor.RED + tl("serverUnsupported")); sender.sendComponent(sender.tlComponent("serverUnsupported").color(NamedTextColor.RED));
break; break;
case LIMITED: case LIMITED:
sender.sendMessage(ChatColor.RED + tl("serverUnsupportedLimitedApi")); sender.sendComponent(sender.tlComponent("serverUnsupportedLimitedApi").color(NamedTextColor.RED));
break; break;
} }
if (VersionUtil.getSupportStatusClass() != null) { if (VersionUtil.getSupportStatusClass() != null) {
sender.sendMessage(ChatColor.RED + tl("serverUnsupportedClass", VersionUtil.getSupportStatusClass())); sender.sendComponent(sender.tlComponent("serverUnsupportedClass").color(NamedTextColor.RED));
} }
sender.sendMessage(tl("versionFetching")); sender.sendTl("versionFetching");
ess.runTaskAsynchronously(() -> { ess.runTaskAsynchronously(() -> {
for (String str : ess.getUpdateChecker().getVersionMessages(true, true)) { for (final Component component : ess.getUpdateChecker().getVersionMessages(true, true, sender)) {
sender.sendMessage(str); sender.sendComponent(component);
} }
}); });
} }

View File

@ -13,8 +13,6 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import static com.earth2me.essentials.I18n.tl;
public class Commandexp extends EssentialsLoopCommand { public class Commandexp extends EssentialsLoopCommand {
public Commandexp() { public Commandexp() {
super("exp"); super("exp");
@ -22,7 +20,7 @@ public class Commandexp extends EssentialsLoopCommand {
@Override @Override
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
final IUser user = sender.getUser(ess); final IUser user = sender.getUser();
if (args.length == 0 || (args.length < 2 && user == null)) { if (args.length == 0 || (args.length < 2 && user == null)) {
if (user == null) { if (user == null) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
@ -39,7 +37,7 @@ public class Commandexp extends EssentialsLoopCommand {
} }
if (!cmd.hasPermission(user)) { if (!cmd.hasPermission(user)) {
user.sendMessage(tl("noAccessSubCommand", "/" + commandLabel + " " + cmd.name().toLowerCase(Locale.ENGLISH))); user.sendTl("noAccessSubCommand", "/" + commandLabel + " " + cmd.name().toLowerCase(Locale.ENGLISH));
return; return;
} }
@ -99,7 +97,7 @@ public class Commandexp extends EssentialsLoopCommand {
} }
private void showExp(final CommandSource sender, final IUser target) { private void showExp(final CommandSource sender, final IUser target) {
sender.sendMessage(tl("exp", target.getDisplayName(), SetExpFix.getTotalExperience(target.getBase()), target.getBase().getLevel(), SetExpFix.getExpUntilNextLevel(target.getBase()))); sender.sendTl("exp", target.getDisplayName(), SetExpFix.getTotalExperience(target.getBase()), target.getBase().getLevel(), SetExpFix.getExpUntilNextLevel(target.getBase()));
} }
//TODO: Limit who can give negative exp? //TODO: Limit who can give negative exp?
@ -131,7 +129,7 @@ public class Commandexp extends EssentialsLoopCommand {
amount = 0L; amount = 0L;
} }
SetExpFix.setTotalExperience(target.getBase(), (int) amount); SetExpFix.setTotalExperience(target.getBase(), (int) amount);
sender.sendMessage(tl("expSet", target.getDisplayName(), amount)); sender.sendTl("expSet", target.getDisplayName(), amount);
} }
@Override @Override

View File

@ -8,8 +8,6 @@ import org.bukkit.entity.Player;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandext extends EssentialsLoopCommand { public class Commandext extends EssentialsLoopCommand {
public Commandext() { public Commandext() {
super("ext"); super("ext");
@ -32,13 +30,13 @@ public class Commandext extends EssentialsLoopCommand {
} }
extPlayer(user.getBase()); extPlayer(user.getBase());
user.sendMessage(tl("extinguish")); user.sendTl("extinguish");
} }
@Override @Override
protected void updatePlayer(final Server server, final CommandSource sender, final User player, final String[] args) { protected void updatePlayer(final Server server, final CommandSource sender, final User player, final String[] args) {
extPlayer(player.getBase()); extPlayer(player.getBase());
sender.sendMessage(tl("extinguishOthers", player.getDisplayName())); sender.sendTl("extinguishOthers", player.getDisplayName());
} }
private void extPlayer(final Player player) { private void extPlayer(final Player player) {

View File

@ -9,8 +9,6 @@ import org.bukkit.event.entity.FoodLevelChangeEvent;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandfeed extends EssentialsLoopCommand { public class Commandfeed extends EssentialsLoopCommand {
public Commandfeed() { public Commandfeed() {
super("feed"); super("feed");
@ -28,7 +26,7 @@ public class Commandfeed extends EssentialsLoopCommand {
} }
feedPlayer(user.getBase()); feedPlayer(user.getBase());
user.sendMessage(tl("feed")); user.sendTl("feed");
} }
@Override @Override
@ -44,7 +42,7 @@ public class Commandfeed extends EssentialsLoopCommand {
protected void updatePlayer(final Server server, final CommandSource sender, final User player, final String[] args) throws PlayerExemptException { protected void updatePlayer(final Server server, final CommandSource sender, final User player, final String[] args) throws PlayerExemptException {
try { try {
feedPlayer(player.getBase()); feedPlayer(player.getBase());
sender.sendMessage(tl("feedOther", player.getDisplayName())); sender.sendTl("feedOther", player.getDisplayName());
} catch (final QuietAbortException e) { } catch (final QuietAbortException e) {
//Handle Quietly //Handle Quietly
} }
@ -66,7 +64,7 @@ public class Commandfeed extends EssentialsLoopCommand {
@Override @Override
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
if (args.length == 1 && sender.isAuthorized("essentials.feed.others", ess)) { if (args.length == 1 && sender.isAuthorized("essentials.feed.others")) {
return getPlayers(server, sender); return getPlayers(server, sender);
} else { } else {
return Collections.emptyList(); return Collections.emptyList();

View File

@ -5,6 +5,7 @@ import com.earth2me.essentials.utils.FloatUtil;
import com.earth2me.essentials.utils.VersionUtil; import com.earth2me.essentials.utils.VersionUtil;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import net.ess3.api.TranslatableException;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.entity.Arrow; import org.bukkit.entity.Arrow;
import org.bukkit.entity.DragonFireball; import org.bukkit.entity.DragonFireball;
@ -27,8 +28,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static com.earth2me.essentials.I18n.tl;
public class Commandfireball extends EssentialsCommand { public class Commandfireball extends EssentialsCommand {
public static final String FIREBALL_META_KEY = "ess_fireball_proj"; public static final String FIREBALL_META_KEY = "ess_fireball_proj";
@ -78,7 +77,7 @@ public class Commandfireball extends EssentialsCommand {
} }
if (!user.isAuthorized("essentials.fireball." + type)) { if (!user.isAuthorized("essentials.fireball." + type)) {
throw new Exception(tl("noPerm", "essentials.fireball." + type)); throw new TranslatableException("noPerm", "essentials.fireball." + type);
} }
final Vector direction = user.getBase().getEyeLocation().getDirection().multiply(speed); final Vector direction = user.getBase().getEyeLocation().getDirection().multiply(speed);

View File

@ -5,6 +5,7 @@ import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.MaterialUtil; import com.earth2me.essentials.utils.MaterialUtil;
import com.earth2me.essentials.utils.NumberUtil; import com.earth2me.essentials.utils.NumberUtil;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import net.ess3.api.TranslatableException;
import org.bukkit.DyeColor; import org.bukkit.DyeColor;
import org.bukkit.FireworkEffect; import org.bukkit.FireworkEffect;
import org.bukkit.Server; import org.bukkit.Server;
@ -17,8 +18,6 @@ import org.bukkit.util.Vector;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static com.earth2me.essentials.I18n.tl;
//This command has quite a complicated syntax, in theory it has 4 seperate syntaxes which are all variable: //This command has quite a complicated syntax, in theory it has 4 seperate syntaxes which are all variable:
// //
//1: /firework clear - This clears all of the effects on a firework stack //1: /firework clear - This clears all of the effects on a firework stack
@ -49,21 +48,21 @@ public class Commandfirework extends EssentialsCommand {
final ItemStack stack = user.getItemInHand(); final ItemStack stack = user.getItemInHand();
if (!MaterialUtil.isFirework(stack.getType())) { if (!MaterialUtil.isFirework(stack.getType())) {
throw new Exception(tl("holdFirework")); throw new TranslatableException("holdFirework");
} }
if (args[0].equalsIgnoreCase("clear")) { if (args[0].equalsIgnoreCase("clear")) {
final FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta(); final FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta();
fmeta.clearEffects(); fmeta.clearEffects();
stack.setItemMeta(fmeta); stack.setItemMeta(fmeta);
user.sendMessage(tl("fireworkEffectsCleared")); user.sendTl("fireworkEffectsCleared");
} else if (args.length > 1 && (args[0].equalsIgnoreCase("power") || args[0].equalsIgnoreCase("p"))) { } else if (args.length > 1 && (args[0].equalsIgnoreCase("power") || args[0].equalsIgnoreCase("p"))) {
final FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta(); final FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta();
try { try {
final int power = Integer.parseInt(args[1]); final int power = Integer.parseInt(args[1]);
fmeta.setPower(power > 3 ? 4 : power); fmeta.setPower(power > 3 ? 4 : power);
} catch (final NumberFormatException e) { } catch (final NumberFormatException e) {
throw new Exception(tl("invalidFireworkFormat", args[1], args[0])); throw new TranslatableException("invalidFireworkFormat", args[1], args[0]);
} }
stack.setItemMeta(fmeta); stack.setItemMeta(fmeta);
} else if ((args[0].equalsIgnoreCase("fire") || args[0].equalsIgnoreCase("f")) && user.isAuthorized("essentials.firework.fire")) { } else if ((args[0].equalsIgnoreCase("fire") || args[0].equalsIgnoreCase("f")) && user.isAuthorized("essentials.firework.fire")) {
@ -75,7 +74,7 @@ public class Commandfirework extends EssentialsCommand {
amount = Integer.parseInt(args[1]); amount = Integer.parseInt(args[1]);
if (amount > serverLimit) { if (amount > serverLimit) {
amount = serverLimit; amount = serverLimit;
user.sendMessage(tl("mobSpawnLimit")); user.sendTl("mobSpawnLimit");
} }
} else { } else {
direction = true; direction = true;
@ -99,7 +98,7 @@ public class Commandfirework extends EssentialsCommand {
try { try {
mStack.addFireworkMeta(user.getSource(), true, arg, ess); mStack.addFireworkMeta(user.getSource(), true, arg, ess);
} catch (final Exception e) { } catch (final Exception e) {
user.sendMessage(tl("fireworkSyntax")); user.sendTl("fireworkSyntax");
throw e; throw e;
} }
} }
@ -108,13 +107,13 @@ public class Commandfirework extends EssentialsCommand {
final FireworkMeta fmeta = (FireworkMeta) mStack.getItemStack().getItemMeta(); final FireworkMeta fmeta = (FireworkMeta) mStack.getItemStack().getItemMeta();
final FireworkEffect effect = mStack.getFireworkBuilder().build(); final FireworkEffect effect = mStack.getFireworkBuilder().build();
if (fmeta.getEffects().size() > 0 && !user.isAuthorized("essentials.firework.multiple")) { if (fmeta.getEffects().size() > 0 && !user.isAuthorized("essentials.firework.multiple")) {
throw new Exception(tl("multipleCharges")); throw new TranslatableException("multipleCharges");
} }
fmeta.addEffect(effect); fmeta.addEffect(effect);
stack.setItemMeta(fmeta); stack.setItemMeta(fmeta);
} else { } else {
user.sendMessage(tl("fireworkSyntax")); user.sendTl("fireworkSyntax");
throw new Exception(tl("fireworkColor")); throw new TranslatableException("fireworkColor");
} }
} }
} }

View File

@ -2,11 +2,10 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.CommonPlaceholders;
import net.ess3.api.events.FlyStatusChangeEvent; import net.ess3.api.events.FlyStatusChangeEvent;
import org.bukkit.Server; import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandfly extends EssentialsToggleCommand { public class Commandfly extends EssentialsToggleCommand {
public Commandfly() { public Commandfly() {
super("fly", "essentials.fly.others"); super("fly", "essentials.fly.others");
@ -39,9 +38,9 @@ public class Commandfly extends EssentialsToggleCommand {
user.getBase().setFlying(false); user.getBase().setFlying(false);
} }
user.sendMessage(tl("flyMode", tl(enabled ? "enabled" : "disabled"), user.getDisplayName())); user.sendTl("flyMode", CommonPlaceholders.enableDisable(user.getSource(), enabled), user.getDisplayName());
if (!sender.isPlayer() || !sender.getPlayer().equals(user.getBase())) { if (!sender.isPlayer() || !sender.getPlayer().equals(user.getBase())) {
sender.sendMessage(tl("flyMode", tl(enabled ? "enabled" : "disabled"), user.getDisplayName())); sender.sendTl("flyMode", CommonPlaceholders.enableDisable(user.getSource(), enabled), user.getDisplayName());
} }
} }
} }

View File

@ -11,8 +11,6 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import static com.earth2me.essentials.I18n.tl;
public class Commandgamemode extends EssentialsLoopCommand { public class Commandgamemode extends EssentialsLoopCommand {
private final List<String> STANDARD_OPTIONS = ImmutableList.of("creative", "survival", "adventure", "spectator", "toggle"); private final List<String> STANDARD_OPTIONS = ImmutableList.of("creative", "survival", "adventure", "spectator", "toggle");
@ -57,26 +55,26 @@ public class Commandgamemode extends EssentialsLoopCommand {
} }
if (isProhibitedChange(user, gameMode)) { if (isProhibitedChange(user, gameMode)) {
user.sendMessage(tl("cantGamemode", gameMode.name())); user.sendTl("cantGamemode", gameMode.name());
return; return;
} }
user.getBase().setGameMode(gameMode); user.getBase().setGameMode(gameMode);
user.sendMessage(tl("gameMode", tl(user.getBase().getGameMode().toString().toLowerCase(Locale.ENGLISH)), user.getDisplayName())); user.sendTl("gameMode", user.playerTl(user.getBase().getGameMode().toString().toLowerCase(Locale.ENGLISH)), user.getDisplayName());
} }
private void setUserGamemode(final CommandSource sender, final GameMode gameMode, final User user) throws NotEnoughArgumentsException { private void setUserGamemode(final CommandSource sender, final GameMode gameMode, final User user) throws NotEnoughArgumentsException {
if (gameMode == null) { if (gameMode == null) {
throw new NotEnoughArgumentsException(tl("gameModeInvalid")); throw new NotEnoughArgumentsException(sender.tl("gameModeInvalid"));
} }
if (sender.isPlayer() && isProhibitedChange(sender.getUser(ess), gameMode)) { if (sender.isPlayer() && isProhibitedChange(sender.getUser(), gameMode)) {
sender.sendMessage(tl("cantGamemode", gameMode.name())); sender.sendTl("cantGamemode", gameMode.name());
return; return;
} }
user.getBase().setGameMode(gameMode); user.getBase().setGameMode(gameMode);
sender.sendMessage(tl("gameMode", tl(gameMode.toString().toLowerCase(Locale.ENGLISH)), user.getDisplayName())); sender.sendTl("gameMode", sender.tl(gameMode.toString().toLowerCase(Locale.ENGLISH)), user.getDisplayName());
} }
// essentials.gamemode will let them change to any but essentials.gamemode.survival would only let them change to survival. // essentials.gamemode will let them change to any but essentials.gamemode.survival would only let them change to survival.

View File

@ -12,8 +12,6 @@ import java.lang.management.ManagementFactory;
import java.util.List; import java.util.List;
import java.util.logging.Level; import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tl;
public class Commandgc extends EssentialsCommand { public class Commandgc extends EssentialsCommand {
public Commandgc() { public Commandgc() {
super("gc"); super("gc");
@ -31,11 +29,11 @@ public class Commandgc extends EssentialsCommand {
color = ChatColor.RED; color = ChatColor.RED;
} }
sender.sendMessage(tl("uptime", DateUtil.formatDateDiff(ManagementFactory.getRuntimeMXBean().getStartTime()))); sender.sendTl("uptime", DateUtil.formatDateDiff(ManagementFactory.getRuntimeMXBean().getStartTime()));
sender.sendMessage(tl("tps", "" + color + NumberUtil.formatDouble(tps))); sender.sendTl("tps", "" + color + NumberUtil.formatDouble(tps));
sender.sendMessage(tl("gcmax", Runtime.getRuntime().maxMemory() / 1024 / 1024)); sender.sendTl("gcmax", Runtime.getRuntime().maxMemory() / 1024 / 1024);
sender.sendMessage(tl("gctotal", Runtime.getRuntime().totalMemory() / 1024 / 1024)); sender.sendTl("gctotal", Runtime.getRuntime().totalMemory() / 1024 / 1024);
sender.sendMessage(tl("gcfree", Runtime.getRuntime().freeMemory() / 1024 / 1024)); sender.sendTl("gcfree", Runtime.getRuntime().freeMemory() / 1024 / 1024);
final List<World> worlds = server.getWorlds(); final List<World> worlds = server.getWorlds();
for (final World w : worlds) { for (final World w : worlds) {
@ -59,7 +57,7 @@ public class Commandgc extends EssentialsCommand {
ess.getLogger().log(Level.SEVERE, "Corrupted chunk data on world " + w, ex); ess.getLogger().log(Level.SEVERE, "Corrupted chunk data on world " + w, ex);
} }
sender.sendMessage(tl("gcWorld", worldType, w.getName(), w.getLoadedChunks().length, w.getEntities().size(), tileEntities)); sender.sendTl("gcWorld", worldType, w.getName(), w.getLoadedChunks().length, w.getEntities().size(), tileEntities);
} }
} }
} }

View File

@ -8,8 +8,6 @@ import org.bukkit.Server;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandgetpos extends EssentialsCommand { public class Commandgetpos extends EssentialsCommand {
public Commandgetpos() { public Commandgetpos() {
super("getpos"); super("getpos");
@ -35,20 +33,20 @@ public class Commandgetpos extends EssentialsCommand {
} }
private void outputPosition(final CommandSource sender, final Location coords, final Location distance) { private void outputPosition(final CommandSource sender, final Location coords, final Location distance) {
sender.sendMessage(tl("currentWorld", coords.getWorld().getName())); sender.sendTl("currentWorld", coords.getWorld().getName());
sender.sendMessage(tl("posX", coords.getBlockX())); sender.sendTl("posX", coords.getBlockX());
sender.sendMessage(tl("posY", coords.getBlockY())); sender.sendTl("posY", coords.getBlockY());
sender.sendMessage(tl("posZ", coords.getBlockZ())); sender.sendTl("posZ", coords.getBlockZ());
sender.sendMessage(tl("posYaw", (coords.getYaw() + 360) % 360)); sender.sendTl("posYaw", (coords.getYaw() + 360) % 360);
sender.sendMessage(tl("posPitch", coords.getPitch())); sender.sendTl("posPitch", coords.getPitch());
if (distance != null && coords.getWorld().equals(distance.getWorld())) { if (distance != null && coords.getWorld().equals(distance.getWorld())) {
sender.sendMessage(tl("distance", coords.distance(distance))); sender.sendTl("distance", coords.distance(distance));
} }
} }
@Override @Override
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
if (args.length == 1 && sender.isAuthorized("essentials.getpos.others", ess)) { if (args.length == 1 && sender.isAuthorized("essentials.getpos.others")) {
return getPlayers(server, sender); return getPlayers(server, sender);
} else { } else {
return Collections.emptyList(); return Collections.emptyList();

View File

@ -7,6 +7,7 @@ import com.earth2me.essentials.craftbukkit.Inventories;
import com.earth2me.essentials.utils.NumberUtil; import com.earth2me.essentials.utils.NumberUtil;
import com.earth2me.essentials.utils.VersionUtil; import com.earth2me.essentials.utils.VersionUtil;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import net.ess3.api.TranslatableException;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.World; import org.bukkit.World;
@ -17,8 +18,6 @@ import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import static com.earth2me.essentials.I18n.tl;
public class Commandgive extends EssentialsLoopCommand { public class Commandgive extends EssentialsLoopCommand {
public Commandgive() { public Commandgive() {
super("give"); super("give");
@ -34,7 +33,7 @@ public class Commandgive extends EssentialsLoopCommand {
final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", "");
if (sender.isPlayer() && !ess.getUser(sender.getPlayer()).canSpawnItem(stack.getType())) { if (sender.isPlayer() && !ess.getUser(sender.getPlayer()).canSpawnItem(stack.getType())) {
throw new Exception(tl("cantSpawnItem", itemname)); throw new TranslatableException("cantSpawnItem", itemname);
} }
try { try {
@ -45,7 +44,7 @@ public class Commandgive extends EssentialsLoopCommand {
stack.setAmount(Integer.parseInt(args[2])); stack.setAmount(Integer.parseInt(args[2]));
} else if (ess.getSettings().getDefaultStackSize() > 0) { } else if (ess.getSettings().getDefaultStackSize() > 0) {
stack.setAmount(ess.getSettings().getDefaultStackSize()); stack.setAmount(ess.getSettings().getDefaultStackSize());
} else if (ess.getSettings().getOversizedStackSize() > 0 && sender.isAuthorized("essentials.oversizedstacks", ess)) { } else if (ess.getSettings().getOversizedStackSize() > 0 && sender.isAuthorized("essentials.oversizedstacks")) {
stack.setAmount(ess.getSettings().getOversizedStackSize()); stack.setAmount(ess.getSettings().getOversizedStackSize());
} }
} catch (final NumberFormatException e) { } catch (final NumberFormatException e) {
@ -54,7 +53,7 @@ public class Commandgive extends EssentialsLoopCommand {
final MetaItemStack metaStack = new MetaItemStack(stack); final MetaItemStack metaStack = new MetaItemStack(stack);
if (!metaStack.canSpawn(ess)) { if (!metaStack.canSpawn(ess)) {
throw new Exception(tl("unableToSpawnItem", itemname)); throw new TranslatableException("unableToSpawnItem", itemname);
} }
if (args.length > 3) { if (args.length > 3) {
@ -73,14 +72,14 @@ public class Commandgive extends EssentialsLoopCommand {
} }
if (stack.getType() == Material.AIR) { if (stack.getType() == Material.AIR) {
throw new Exception(tl("cantSpawnItem", "Air")); throw new TranslatableException("cantSpawnItem", "Air");
} }
final String itemName = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' '); final String itemName = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' ');
final boolean isDropItemsIfFull = ess.getSettings().isDropItemsIfFull(); final boolean isDropItemsIfFull = ess.getSettings().isDropItemsIfFull();
final ItemStack finalStack = stack; final ItemStack finalStack = stack;
loopOnlinePlayersConsumer(server, sender, false, true, args[0], player -> { loopOnlinePlayersConsumer(server, sender, false, true, args[0], player -> {
sender.sendMessage(tl("giveSpawn", finalStack.getAmount(), itemName, player.getDisplayName())); sender.sendTl("giveSpawn", finalStack.getAmount(), itemName, player.getDisplayName());
final Map<Integer, ItemStack> leftovers = Inventories.addItem(player.getBase(), player.isAuthorized("essentials.oversizedstacks") ? ess.getSettings().getOversizedStackSize() : 0, finalStack); final Map<Integer, ItemStack> leftovers = Inventories.addItem(player.getBase(), player.isAuthorized("essentials.oversizedstacks") ? ess.getSettings().getOversizedStackSize() : 0, finalStack);
@ -89,7 +88,7 @@ public class Commandgive extends EssentialsLoopCommand {
final World w = player.getWorld(); final World w = player.getWorld();
w.dropItemNaturally(player.getLocation(), item); w.dropItemNaturally(player.getLocation(), item);
} else { } else {
sender.sendMessage(tl("giveSpawnFailure", item.getAmount(), itemName, player.getDisplayName())); sender.sendTl("giveSpawnFailure", item.getAmount(), itemName, player.getDisplayName());
} }
} }

View File

@ -2,11 +2,10 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.CommonPlaceholders;
import net.ess3.api.events.GodStatusChangeEvent; import net.ess3.api.events.GodStatusChangeEvent;
import org.bukkit.Server; import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandgod extends EssentialsToggleCommand { public class Commandgod extends EssentialsToggleCommand {
public Commandgod() { public Commandgod() {
super("god", "essentials.god.others"); super("god", "essentials.god.others");
@ -38,9 +37,9 @@ public class Commandgod extends EssentialsToggleCommand {
user.getBase().setFoodLevel(20); user.getBase().setFoodLevel(20);
} }
user.sendMessage(tl("godMode", enabled ? tl("enabled") : tl("disabled"))); user.sendTl("godMode", CommonPlaceholders.enableDisable(user.getSource(), enabled));
if (!sender.isPlayer() || !sender.getPlayer().equals(user.getBase())) { if (!sender.isPlayer() || !sender.getPlayer().equals(user.getBase())) {
sender.sendMessage(tl("godMode", tl(enabled ? "godEnabledFor" : "godDisabledFor", user.getDisplayName()))); sender.sendTl("godMode", CommonPlaceholders.enableDisable(user.getSource(), enabled));
} }
} }
} }

View File

@ -3,8 +3,6 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import org.bukkit.Server; import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandgrindstone extends EssentialsCommand { public class Commandgrindstone extends EssentialsCommand {
public Commandgrindstone() { public Commandgrindstone() {
@ -14,7 +12,7 @@ public class Commandgrindstone extends EssentialsCommand {
@Override @Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (ess.getContainerProvider() == null) { if (ess.getContainerProvider() == null) {
user.sendMessage(tl("unsupportedBrand")); user.sendTl("unsupportedBrand");
return; return;
} }

View File

@ -14,8 +14,6 @@ import org.bukkit.inventory.PlayerInventory;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandhat extends EssentialsCommand { public class Commandhat extends EssentialsCommand {
// The prefix for hat prevention commands // The prefix for hat prevention commands
@ -30,45 +28,45 @@ public class Commandhat extends EssentialsCommand {
if (args.length == 0 || (!args[0].contains("rem") && !args[0].contains("off") && !args[0].equalsIgnoreCase("0"))) { if (args.length == 0 || (!args[0].contains("rem") && !args[0].contains("off") && !args[0].equalsIgnoreCase("0"))) {
final ItemStack hand = Inventories.getItemInMainHand(user.getBase()); final ItemStack hand = Inventories.getItemInMainHand(user.getBase());
if (hand == null || hand.getType() == Material.AIR) { if (hand == null || hand.getType() == Material.AIR) {
user.sendMessage(tl("hatFail")); user.sendTl("hatFail");
return; return;
} }
final TriState wildcard = user.isAuthorizedExact(PERM_PREFIX + "*"); final TriState wildcard = user.isAuthorizedExact(PERM_PREFIX + "*");
final TriState material = user.isAuthorizedExact(PERM_PREFIX + hand.getType().name().toLowerCase()); final TriState material = user.isAuthorizedExact(PERM_PREFIX + hand.getType().name().toLowerCase());
if ((wildcard == TriState.TRUE && material != TriState.FALSE) || ((wildcard != TriState.TRUE) && material == TriState.TRUE)) { if ((wildcard == TriState.TRUE && material != TriState.FALSE) || ((wildcard != TriState.TRUE) && material == TriState.TRUE)) {
user.sendMessage(tl("hatFail")); user.sendTl("hatFail");
return; return;
} }
if (hand.getType().getMaxDurability() != 0) { if (hand.getType().getMaxDurability() != 0) {
user.sendMessage(tl("hatArmor")); user.sendTl("hatArmor");
return; return;
} }
final PlayerInventory inv = user.getBase().getInventory(); final PlayerInventory inv = user.getBase().getInventory();
final ItemStack head = inv.getHelmet(); final ItemStack head = inv.getHelmet();
if (VersionUtil.getServerBukkitVersion().isHigherThan(VersionUtil.v1_9_4_R01) && head != null && head.getEnchantments().containsKey(Enchantment.BINDING_CURSE) && !user.isAuthorized("essentials.hat.ignore-binding")) { if (VersionUtil.getServerBukkitVersion().isHigherThan(VersionUtil.v1_9_4_R01) && head != null && head.getEnchantments().containsKey(Enchantment.BINDING_CURSE) && !user.isAuthorized("essentials.hat.ignore-binding")) {
user.sendMessage(tl("hatCurse")); user.sendTl("hatCurse");
return; return;
} }
inv.setHelmet(hand); inv.setHelmet(hand);
Inventories.setItemInMainHand(user.getBase(), head); Inventories.setItemInMainHand(user.getBase(), head);
user.sendMessage(tl("hatPlaced")); user.sendTl("hatPlaced");
return; return;
} }
final PlayerInventory inv = user.getBase().getInventory(); final PlayerInventory inv = user.getBase().getInventory();
final ItemStack head = inv.getHelmet(); final ItemStack head = inv.getHelmet();
if (head == null || head.getType() == Material.AIR) { if (head == null || head.getType() == Material.AIR) {
user.sendMessage(tl("hatEmpty")); user.sendTl("hatEmpty");
} else if (VersionUtil.getServerBukkitVersion().isHigherThan(VersionUtil.v1_9_4_R01) && head.getEnchantments().containsKey(Enchantment.BINDING_CURSE) && !user.isAuthorized("essentials.hat.ignore-binding")) { } else if (VersionUtil.getServerBukkitVersion().isHigherThan(VersionUtil.v1_9_4_R01) && head.getEnchantments().containsKey(Enchantment.BINDING_CURSE) && !user.isAuthorized("essentials.hat.ignore-binding")) {
user.sendMessage(tl("hatCurse")); user.sendTl("hatCurse");
} else { } else {
final ItemStack air = new ItemStack(Material.AIR); final ItemStack air = new ItemStack(Material.AIR);
inv.setHelmet(air); inv.setHelmet(air);
Inventories.addItem(user.getBase(), head); Inventories.addItem(user.getBase(), head);
user.sendMessage(tl("hatRemoved")); user.sendTl("hatRemoved");
} }
} }

View File

@ -11,8 +11,6 @@ import org.bukkit.potion.PotionEffect;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandheal extends EssentialsLoopCommand { public class Commandheal extends EssentialsLoopCommand {
public Commandheal() { public Commandheal() {
super("heal"); super("heal");
@ -47,7 +45,7 @@ public class Commandheal extends EssentialsLoopCommand {
final Player player = user.getBase(); final Player player = user.getBase();
if (player.getHealth() == 0) { if (player.getHealth() == 0) {
throw new PlayerExemptException(tl("healDead")); throw new PlayerExemptException("healDead");
} }
final double amount = player.getMaxHealth() - player.getHealth(); final double amount = player.getMaxHealth() - player.getHealth();
@ -65,13 +63,13 @@ public class Commandheal extends EssentialsLoopCommand {
player.setHealth(newAmount); player.setHealth(newAmount);
player.setFoodLevel(20); player.setFoodLevel(20);
player.setFireTicks(0); player.setFireTicks(0);
user.sendMessage(tl("heal")); user.sendTl("heal");
if (ess.getSettings().isRemovingEffectsOnHeal()) { if (ess.getSettings().isRemovingEffectsOnHeal()) {
for (final PotionEffect effect : player.getActivePotionEffects()) { for (final PotionEffect effect : player.getActivePotionEffects()) {
player.removePotionEffect(effect.getType()); player.removePotionEffect(effect.getType());
} }
} }
sender.sendMessage(tl("healOther", user.getDisplayName())); sender.sendTl("healOther", user.getDisplayName());
} catch (final QuietAbortException e) { } catch (final QuietAbortException e) {
//Handle Quietly //Handle Quietly
} }
@ -79,7 +77,7 @@ public class Commandheal extends EssentialsLoopCommand {
@Override @Override
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
if (args.length == 1 && sender.isAuthorized("essentials.heal.others", ess)) { if (args.length == 1 && sender.isAuthorized("essentials.heal.others")) {
return getPlayers(server, sender); return getPlayers(server, sender);
} else { } else {
return Collections.emptyList(); return Collections.emptyList();

View File

@ -7,6 +7,7 @@ import com.earth2me.essentials.textreader.IText;
import com.earth2me.essentials.textreader.KeywordReplacer; import com.earth2me.essentials.textreader.KeywordReplacer;
import com.earth2me.essentials.textreader.TextInput; import com.earth2me.essentials.textreader.TextInput;
import com.earth2me.essentials.textreader.TextPager; import com.earth2me.essentials.textreader.TextPager;
import com.earth2me.essentials.utils.AdventureUtil;
import com.earth2me.essentials.utils.NumberUtil; import com.earth2me.essentials.utils.NumberUtil;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.command.Command; import org.bukkit.command.Command;
@ -18,8 +19,6 @@ import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import static com.earth2me.essentials.I18n.tl;
public class Commandhelp extends EssentialsCommand { public class Commandhelp extends EssentialsCommand {
public Commandhelp() { public Commandhelp() {
super("help"); super("help");
@ -38,15 +37,15 @@ public class Commandhelp extends EssentialsCommand {
final String cmd = pageStr.substring(1); final String cmd = pageStr.substring(1);
for (final Map.Entry<String, Command> knownCmd : ess.getKnownCommandsProvider().getKnownCommands().entrySet()) { for (final Map.Entry<String, Command> knownCmd : ess.getKnownCommandsProvider().getKnownCommands().entrySet()) {
if (knownCmd.getKey().equalsIgnoreCase(cmd)) { if (knownCmd.getKey().equalsIgnoreCase(cmd)) {
user.sendMessage(tl("commandHelpLine1", cmd)); user.sendTl("commandHelpLine1", cmd);
user.sendMessage(tl("commandHelpLine2", knownCmd.getValue().getDescription())); user.sendTl("commandHelpLine2", knownCmd.getValue().getDescription());
user.sendMessage(tl("commandHelpLine4", knownCmd.getValue().getAliases().toString())); user.sendTl("commandHelpLine4", knownCmd.getValue().getAliases().toString());
user.sendMessage(tl("commandHelpLine3")); user.sendTl("commandHelpLine3");
final boolean isEssCommand = knownCmd.getValue() instanceof PluginIdentifiableCommand && ((PluginIdentifiableCommand) knownCmd.getValue()).getPlugin().equals(ess); final boolean isEssCommand = knownCmd.getValue() instanceof PluginIdentifiableCommand && ((PluginIdentifiableCommand) knownCmd.getValue()).getPlugin().equals(ess);
final IEssentialsCommand essCommand = isEssCommand ? ess.getCommandMap().get(knownCmd.getValue().getName()) : null; final IEssentialsCommand essCommand = isEssCommand ? ess.getCommandMap().get(knownCmd.getValue().getName()) : null;
if (essCommand != null && !essCommand.getUsageStrings().isEmpty()) { if (essCommand != null && !essCommand.getUsageStrings().isEmpty()) {
for (Map.Entry<String, String> usage : essCommand.getUsageStrings().entrySet()) { for (Map.Entry<String, String> usage : essCommand.getUsageStrings().entrySet()) {
user.sendMessage(tl("commandHelpLineUsage", usage.getKey().replace("<command>", cmd), usage.getValue())); user.sendTl("commandHelpLineUsage", AdventureUtil.parsed(usage.getKey().replace("<command>", cmd)), AdventureUtil.parsed(usage.getValue()));
} }
} else { } else {
user.sendMessage(knownCmd.getValue().getUsage()); user.sendMessage(knownCmd.getValue().getUsage());
@ -77,7 +76,7 @@ public class Commandhelp extends EssentialsCommand {
@Override @Override
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
sender.sendMessage(tl("helpConsole")); sender.sendTl("helpConsole");
} }
@Override @Override

View File

@ -4,6 +4,7 @@ import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.Console; import com.earth2me.essentials.Console;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.messaging.IMessageRecipient; import com.earth2me.essentials.messaging.IMessageRecipient;
import com.earth2me.essentials.utils.AdventureUtil;
import com.earth2me.essentials.utils.FormatUtil; import com.earth2me.essentials.utils.FormatUtil;
import net.ess3.api.IUser; import net.ess3.api.IUser;
import net.essentialsx.api.v2.events.HelpopMessageSendEvent; import net.essentialsx.api.v2.events.HelpopMessageSendEvent;
@ -14,7 +15,7 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.logging.Level; import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tlLiteral;
public class Commandhelpop extends EssentialsCommand { public class Commandhelpop extends EssentialsCommand {
public Commandhelpop() { public Commandhelpop() {
@ -24,25 +25,21 @@ public class Commandhelpop extends EssentialsCommand {
@Override @Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
user.setDisplayNick(); user.setDisplayNick();
final String message = sendMessage(server, user, args); sendMessage(user, args);
if (!user.isAuthorized("essentials.helpop.receive")) {
user.sendMessage(message);
}
} }
@Override @Override
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
sendMessage(server, Console.getInstance(), args); sendMessage(Console.getInstance(), args);
} }
private String sendMessage(final Server server, final IMessageRecipient from, final String[] args) throws Exception { private void sendMessage(final IMessageRecipient from, final String[] args) throws Exception {
if (args.length < 1) { if (args.length < 1) {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
final String message = FormatUtil.stripFormat(getFinalArg(args, 0)); final String message = FormatUtil.stripFormat(getFinalArg(args, 0));
final String finalMessage = tl("helpOp", from.getDisplayName(), message); ess.getLogger().log(Level.INFO, AdventureUtil.miniToLegacy(tlLiteral("helpOp", from.getDisplayName(), message)));
ess.getLogger().log(Level.INFO, finalMessage);
final List<IUser> recipients = new ArrayList<>(); final List<IUser> recipients = new ArrayList<>();
for (IUser user : ess.getOnlineUsers()) { for (IUser user : ess.getOnlineUsers()) {
@ -55,10 +52,8 @@ public class Commandhelpop extends EssentialsCommand {
ess.getServer().getPluginManager().callEvent(sendEvent); ess.getServer().getPluginManager().callEvent(sendEvent);
for (IUser recipient : sendEvent.getRecipients()) { for (IUser recipient : sendEvent.getRecipients()) {
recipient.sendMessage(finalMessage); recipient.sendTl("helpOp", from.getDisplayName(), message);
} }
return finalMessage;
} }
@Override @Override

View File

@ -3,8 +3,10 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.OfflinePlayerStub; import com.earth2me.essentials.OfflinePlayerStub;
import com.earth2me.essentials.Trade; import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.AdventureUtil;
import com.earth2me.essentials.utils.StringUtil; import com.earth2me.essentials.utils.StringUtil;
import io.papermc.lib.PaperLib; import io.papermc.lib.PaperLib;
import net.ess3.api.TranslatableException;
import net.ess3.api.events.UserTeleportHomeEvent; import net.ess3.api.events.UserTeleportHomeEvent;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Server; import org.bukkit.Server;
@ -15,8 +17,6 @@ import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import static com.earth2me.essentials.I18n.tl;
public class Commandhome extends EssentialsCommand { public class Commandhome extends EssentialsCommand {
public Commandhome() { public Commandhome() {
super("home"); super("home");
@ -43,7 +43,7 @@ public class Commandhome extends EssentialsCommand {
try { try {
if ("bed".equalsIgnoreCase(homeName) && user.isAuthorized("essentials.home.bed")) { if ("bed".equalsIgnoreCase(homeName) && user.isAuthorized("essentials.home.bed")) {
if (!player.getBase().isOnline() || player.getBase() instanceof OfflinePlayerStub) { if (!player.getBase().isOnline() || player.getBase() instanceof OfflinePlayerStub) {
throw new Exception(tl("bedOffline")); throw new TranslatableException("bedOffline");
} }
PaperLib.getBedSpawnLocationAsync(player.getBase(), true).thenAccept(location -> { PaperLib.getBedSpawnLocationAsync(player.getBase(), true).thenAccept(location -> {
final CompletableFuture<Boolean> future = getNewExceptionFuture(user.getSource(), commandLabel); final CompletableFuture<Boolean> future = getNewExceptionFuture(user.getSource(), commandLabel);
@ -55,12 +55,12 @@ public class Commandhome extends EssentialsCommand {
} }
future.thenAccept(success -> { future.thenAccept(success -> {
if (success) { if (success) {
user.sendMessage(tl("teleportHome", "bed")); user.sendTl("teleportHome", "bed");
} }
}); });
user.getAsyncTeleport().teleport(location, charge, TeleportCause.COMMAND, future); user.getAsyncTeleport().teleport(location, charge, TeleportCause.COMMAND, future);
} else { } else {
showError(user.getBase(), new Exception(tl("bedMissing")), commandLabel); showError(user.getBase(), new TranslatableException("bedMissing"), commandLabel);
} }
}); });
throw new NoChargeException(); throw new NoChargeException();
@ -79,10 +79,10 @@ public class Commandhome extends EssentialsCommand {
user.getAsyncTeleport().respawn(charge, TeleportCause.COMMAND, getNewExceptionFuture(user.getSource(), commandLabel)); user.getAsyncTeleport().respawn(charge, TeleportCause.COMMAND, getNewExceptionFuture(user.getSource(), commandLabel));
} }
} else { } else {
showError(user.getBase(), new Exception(tl("noHomeSetPlayer")), commandLabel); showError(user.getBase(), new TranslatableException("noHomeSetPlayer"), commandLabel);
} }
} else if (homes.isEmpty() || !finalPlayer.hasValidHomes()) { } else if (homes.isEmpty() || !finalPlayer.hasValidHomes()) {
showError(user.getBase(), new Exception(tl("noHomeSetPlayer")), commandLabel); showError(user.getBase(), new TranslatableException("noHomeSetPlayer"), commandLabel);
} else if (homes.size() == 1 && finalPlayer.equals(user)) { } else if (homes.size() == 1 && finalPlayer.equals(user)) {
try { try {
goHome(user, finalPlayer, homes.get(0), charge, getNewExceptionFuture(user.getSource(), commandLabel)); goHome(user, finalPlayer, homes.get(0), charge, getNewExceptionFuture(user.getSource(), commandLabel));
@ -93,12 +93,12 @@ public class Commandhome extends EssentialsCommand {
final int count = homes.size(); final int count = homes.size();
if (user.isAuthorized("essentials.home.bed")) { if (user.isAuthorized("essentials.home.bed")) {
if (bed != null) { if (bed != null) {
homes.add(tl("bed")); homes.add(user.playerTl("bed"));
} else { } else {
homes.add(tl("bedNull")); homes.add(user.playerTl("bedNull"));
} }
} }
user.sendMessage(tl("homes", StringUtil.joinList(homes), count, getHomeLimit(finalPlayer))); user.sendTl("homes", AdventureUtil.parsed(StringUtil.joinList(homes)), count, getHomeLimit(finalPlayer));
} }
}); });
if (!player.getBase().isOnline() || player.getBase() instanceof OfflinePlayerStub) { if (!player.getBase().isOnline() || player.getBase() instanceof OfflinePlayerStub) {
@ -129,7 +129,7 @@ public class Commandhome extends EssentialsCommand {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
if (user.getWorld() != loc.getWorld() && ess.getSettings().isWorldHomePermissions() && !user.isAuthorized("essentials.worlds." + loc.getWorld().getName())) { if (user.getWorld() != loc.getWorld() && ess.getSettings().isWorldHomePermissions() && !user.isAuthorized("essentials.worlds." + loc.getWorld().getName())) {
throw new Exception(tl("noPerm", "essentials.worlds." + loc.getWorld().getName())); throw new TranslatableException("noPerm", "essentials.worlds." + loc.getWorld().getName());
} }
final UserTeleportHomeEvent event = new UserTeleportHomeEvent(user, home, loc, UserTeleportHomeEvent.HomeType.HOME); final UserTeleportHomeEvent event = new UserTeleportHomeEvent(user, home, loc, UserTeleportHomeEvent.HomeType.HOME);
user.getServer().getPluginManager().callEvent(event); user.getServer().getPluginManager().callEvent(event);
@ -137,7 +137,7 @@ public class Commandhome extends EssentialsCommand {
user.getAsyncTeleport().teleport(loc, charge, TeleportCause.COMMAND, future); user.getAsyncTeleport().teleport(loc, charge, TeleportCause.COMMAND, future);
future.thenAccept(success -> { future.thenAccept(success -> {
if (success) { if (success) {
user.sendMessage(tl("teleportHome", home)); user.sendTl("teleportHome", home);
} }
}); });
} }

View File

@ -11,8 +11,6 @@ import org.bukkit.Server;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandice extends EssentialsLoopCommand { public class Commandice extends EssentialsLoopCommand {
public Commandice() { public Commandice() {
super("ice"); super("ice");
@ -21,7 +19,7 @@ public class Commandice extends EssentialsLoopCommand {
@Override @Override
protected void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception { protected void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception {
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_17_R01)) { if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_17_R01)) {
sender.sendMessage(tl("unsupportedFeature")); sender.sendTl("unsupportedFeature");
return; return;
} }
@ -29,28 +27,28 @@ public class Commandice extends EssentialsLoopCommand {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }
if (args.length > 0 && sender.isAuthorized("essentials.ice.others", ess)) { if (args.length > 0 && sender.isAuthorized("essentials.ice.others")) {
loopOnlinePlayers(server, sender, false, true, args[0], null); loopOnlinePlayers(server, sender, false, true, args[0], null);
return; return;
} }
//noinspection ConstantConditions //noinspection ConstantConditions
freezePlayer(sender.getUser(ess)); freezePlayer(sender.getUser());
} }
@Override @Override
protected void updatePlayer(Server server, CommandSource sender, User user, String[] args) throws NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException { protected void updatePlayer(Server server, CommandSource sender, User user, String[] args) throws NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException {
freezePlayer(user); freezePlayer(user);
sender.sendMessage(tl("iceOther", user.getDisplayName())); sender.sendTl("iceOther", user.getDisplayName());
} }
private void freezePlayer(final IUser user) { private void freezePlayer(final IUser user) {
user.getBase().setFreezeTicks(user.getBase().getMaxFreezeTicks()); user.getBase().setFreezeTicks(user.getBase().getMaxFreezeTicks());
user.sendMessage(tl("ice")); user.sendTl("ice");
} }
@Override @Override
protected List<String> getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { protected List<String> getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) {
if (args.length == 1 && sender.isAuthorized("essentials.ice.others", ess)) { if (args.length == 1 && sender.isAuthorized("essentials.ice.others")) {
return getPlayers(server, sender); return getPlayers(server, sender);
} else { } else {
return Collections.emptyList(); return Collections.emptyList();

View File

@ -7,8 +7,6 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import static com.earth2me.essentials.I18n.tl;
public class Commandignore extends EssentialsCommand { public class Commandignore extends EssentialsCommand {
public Commandignore() { public Commandignore() {
super("ignore"); super("ignore");
@ -25,7 +23,7 @@ public class Commandignore extends EssentialsCommand {
} }
} }
final String ignoredList = sb.toString().trim(); final String ignoredList = sb.toString().trim();
user.sendMessage(ignoredList.length() > 0 ? tl("ignoredList", ignoredList) : tl("noIgnored")); user.sendTl(ignoredList.length() > 0 ? "ignoredList" : "noIgnored", ignoredList);
return; return;
} }
@ -40,15 +38,15 @@ public class Commandignore extends EssentialsCommand {
} }
if (player.isIgnoreExempt()) { if (player.isIgnoreExempt()) {
user.sendMessage(tl("ignoreExempt")); user.sendTl("ignoreExempt");
} else if (user.isIgnoredPlayer(player)) { } else if (user.isIgnoredPlayer(player)) {
user.setIgnoredPlayer(player, false); user.setIgnoredPlayer(player, false);
user.sendMessage(tl("unignorePlayer", player.getName())); user.sendTl("unignorePlayer", player.getName());
} else if (user.getUUID().equals(player.getUUID())) { } else if (user.getUUID().equals(player.getUUID())) {
user.sendMessage(tl("ignoreYourself")); user.sendTl("ignoreYourself");
} else { } else {
user.setIgnoredPlayer(player, true); user.setIgnoredPlayer(player, true);
user.sendMessage(tl("ignorePlayer", player.getName())); user.sendTl("ignorePlayer", player.getName());
} }
} }

View File

@ -8,8 +8,6 @@ import org.bukkit.inventory.Inventory;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandinvsee extends EssentialsCommand { public class Commandinvsee extends EssentialsCommand {
public Commandinvsee() { public Commandinvsee() {
super("invsee"); super("invsee");
@ -24,14 +22,14 @@ public class Commandinvsee extends EssentialsCommand {
final User invUser = getPlayer(server, user, args, 0); final User invUser = getPlayer(server, user, args, 0);
if (user == invUser) { if (user == invUser) {
user.sendMessage(tl("invseeNoSelf")); user.sendTl("invseeNoSelf");
throw new NoChargeException(); throw new NoChargeException();
} }
final Inventory inv; final Inventory inv;
if (args.length > 1 && user.isAuthorized("essentials.invsee.equip")) { if (args.length > 1 && user.isAuthorized("essentials.invsee.equip")) {
inv = server.createInventory(invUser.getBase(), 9, "Equipped"); inv = server.createInventory(invUser.getBase(), 9, user.playerTl("equipped"));
inv.setContents(invUser.getBase().getInventory().getArmorContents()); inv.setContents(invUser.getBase().getInventory().getArmorContents());
if (VersionUtil.getServerBukkitVersion().isHigherThanOrEqualTo(VersionUtil.v1_9_4_R01)) { if (VersionUtil.getServerBukkitVersion().isHigherThanOrEqualTo(VersionUtil.v1_9_4_R01)) {
inv.setItem(4, invUser.getBase().getInventory().getItemInOffHand()); inv.setItem(4, invUser.getBase().getInventory().getItemInOffHand());

View File

@ -4,6 +4,7 @@ import com.earth2me.essentials.MetaItemStack;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.craftbukkit.Inventories; import com.earth2me.essentials.craftbukkit.Inventories;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import net.ess3.api.TranslatableException;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
@ -12,8 +13,6 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import static com.earth2me.essentials.I18n.tl;
public class Commanditem extends EssentialsCommand { public class Commanditem extends EssentialsCommand {
public Commanditem() { public Commanditem() {
super("item"); super("item");
@ -29,7 +28,7 @@ public class Commanditem extends EssentialsCommand {
final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", "");
if (!user.canSpawnItem(stack.getType())) { if (!user.canSpawnItem(stack.getType())) {
throw new Exception(tl("cantSpawnItem", itemname)); throw new TranslatableException("cantSpawnItem", itemname);
} }
try { try {
@ -46,7 +45,7 @@ public class Commanditem extends EssentialsCommand {
final MetaItemStack metaStack = new MetaItemStack(stack); final MetaItemStack metaStack = new MetaItemStack(stack);
if (!metaStack.canSpawn(ess)) { if (!metaStack.canSpawn(ess)) {
throw new Exception(tl("unableToSpawnItem", itemname)); throw new TranslatableException("unableToSpawnItem", itemname);
} }
if (args.length > 2) { if (args.length > 2) {
@ -58,11 +57,11 @@ public class Commanditem extends EssentialsCommand {
} }
if (stack.getType() == Material.AIR) { if (stack.getType() == Material.AIR) {
throw new Exception(tl("cantSpawnItem", "Air")); throw new TranslatableException("cantSpawnItem", "Air");
} }
final String displayName = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' '); final String displayName = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' ');
user.sendMessage(tl("itemSpawn", stack.getAmount(), displayName)); user.sendTl("itemSpawn", stack.getAmount(), displayName);
Inventories.addItem(user.getBase(), user.isAuthorized("essentials.oversizedstacks") ? ess.getSettings().getOversizedStackSize() : 0, stack); Inventories.addItem(user.getBase(), user.isAuthorized("essentials.oversizedstacks") ? ess.getSettings().getOversizedStackSize() : 0, stack);
user.getBase().updateInventory(); user.getBase().updateInventory();
} }

View File

@ -12,8 +12,6 @@ import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commanditemdb extends EssentialsCommand { public class Commanditemdb extends EssentialsCommand {
public Commanditemdb() { public Commanditemdb() {
super("itemdb"); super("itemdb");
@ -41,18 +39,18 @@ public class Commanditemdb extends EssentialsCommand {
itemId = itemStack.getType().getId() + ":" + itemStack.getDurability(); itemId = itemStack.getType().getId() + ":" + itemStack.getDurability();
} }
sender.sendMessage(tl("itemType", itemStack.getType().toString(), itemId)); sender.sendTl("itemType", itemStack.getType().toString(), itemId);
// Don't send IDs twice // Don't send IDs twice
if (!tl("itemType").contains("{1}") && !itemId.equals("none")) { if (!sender.tl("itemType").contains("{1}") && !itemId.equals("none")) {
sender.sendMessage(tl("itemId", itemId)); sender.sendTl("itemId", itemId);
} }
if (itemHeld && itemStack.getType() != Material.AIR) { if (itemHeld && itemStack.getType() != Material.AIR) {
final int maxuses = itemStack.getType().getMaxDurability(); final int maxuses = itemStack.getType().getMaxDurability();
final int durability = (maxuses + 1) - MaterialUtil.getDamage(itemStack); final int durability = (maxuses + 1) - MaterialUtil.getDamage(itemStack);
if (maxuses != 0) { if (maxuses != 0) {
sender.sendMessage(tl("durability", Integer.toString(durability))); sender.sendTl("durability", Integer.toString(durability));
} }
} }
@ -68,7 +66,7 @@ public class Commanditemdb extends EssentialsCommand {
nameList = nameList.subList(0, 14); nameList = nameList.subList(0, 14);
} }
final String itemNameList = StringUtil.joinList(", ", nameList); final String itemNameList = StringUtil.joinList(", ", nameList);
sender.sendMessage(tl("itemNames", itemNameList)); sender.sendTl("itemNames", itemNameList);
} }
@Override @Override

View File

@ -6,6 +6,7 @@ import com.earth2me.essentials.utils.FormatUtil;
import com.earth2me.essentials.utils.MaterialUtil; import com.earth2me.essentials.utils.MaterialUtil;
import com.earth2me.essentials.utils.NumberUtil; import com.earth2me.essentials.utils.NumberUtil;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import net.ess3.api.TranslatableException;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
@ -15,8 +16,6 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import static com.earth2me.essentials.I18n.tl;
public class Commanditemlore extends EssentialsCommand { public class Commanditemlore extends EssentialsCommand {
public Commanditemlore() { public Commanditemlore() {
@ -27,7 +26,7 @@ public class Commanditemlore extends EssentialsCommand {
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
final ItemStack item = Inventories.getItemInHand(user.getBase()); final ItemStack item = Inventories.getItemInHand(user.getBase());
if (item == null || MaterialUtil.isAir(item.getType())) { if (item == null || MaterialUtil.isAir(item.getType())) {
throw new Exception(tl("itemloreInvalidItem")); throw new TranslatableException("itemloreInvalidItem");
} }
if (args.length == 0) { if (args.length == 0) {
@ -38,7 +37,7 @@ public class Commanditemlore extends EssentialsCommand {
final int loreSize = im.hasLore() ? im.getLore().size() : 0; final int loreSize = im.hasLore() ? im.getLore().size() : 0;
if (args[0].equalsIgnoreCase("add") && args.length > 1) { if (args[0].equalsIgnoreCase("add") && args.length > 1) {
if (loreSize >= ess.getSettings().getMaxItemLore() && !user.isAuthorized("essentials.itemlore.bypass")) { if (loreSize >= ess.getSettings().getMaxItemLore() && !user.isAuthorized("essentials.itemlore.bypass")) {
throw new Exception(tl("itemloreMaxLore")); throw new TranslatableException("itemloreMaxLore");
} }
final String line = FormatUtil.formatString(user, "essentials.itemlore", getFinalArg(args, 1)).trim(); final String line = FormatUtil.formatString(user, "essentials.itemlore", getFinalArg(args, 1)).trim();
@ -46,14 +45,14 @@ public class Commanditemlore extends EssentialsCommand {
lore.add(line); lore.add(line);
im.setLore(lore); im.setLore(lore);
item.setItemMeta(im); item.setItemMeta(im);
user.sendMessage(tl("itemloreSuccess", line)); user.sendTl("itemloreSuccess", line);
} else if (args[0].equalsIgnoreCase("clear")) { } else if (args[0].equalsIgnoreCase("clear")) {
im.setLore(new ArrayList<>()); im.setLore(new ArrayList<>());
item.setItemMeta(im); item.setItemMeta(im);
user.sendMessage(tl("itemloreClear")); user.sendTl("itemloreClear");
} else if (args[0].equalsIgnoreCase("set") && args.length > 2 && NumberUtil.isInt(args[1])) { } else if (args[0].equalsIgnoreCase("set") && args.length > 2 && NumberUtil.isInt(args[1])) {
if (!im.hasLore()) { if (!im.hasLore()) {
throw new Exception(tl("itemloreNoLore")); throw new TranslatableException("itemloreNoLore");
} }
final int line = Integer.parseInt(args[1]); final int line = Integer.parseInt(args[1]);
@ -62,11 +61,11 @@ public class Commanditemlore extends EssentialsCommand {
try { try {
lore.set(line - 1, newLine); lore.set(line - 1, newLine);
} catch (final Exception e) { } catch (final Exception e) {
throw new Exception(tl("itemloreNoLine", line), e); throw new TranslatableException(e, "itemloreNoLine", line);
} }
im.setLore(lore); im.setLore(lore);
item.setItemMeta(im); item.setItemMeta(im);
user.sendMessage(tl("itemloreSuccessLore", line, newLine)); user.sendTl("itemloreSuccessLore", line, newLine);
} else { } else {
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
} }

View File

@ -13,8 +13,6 @@ import org.bukkit.inventory.meta.ItemMeta;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commanditemname extends EssentialsCommand { public class Commanditemname extends EssentialsCommand {
public static final String PERM_PREFIX = "essentials.itemname.prevent-type."; public static final String PERM_PREFIX = "essentials.itemname.prevent-type.";
@ -26,14 +24,14 @@ public class Commanditemname extends EssentialsCommand {
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
final ItemStack item = Inventories.getItemInHand(user.getBase()); final ItemStack item = Inventories.getItemInHand(user.getBase());
if (item == null || MaterialUtil.isAir(item.getType())) { if (item == null || MaterialUtil.isAir(item.getType())) {
user.sendMessage(tl("itemnameInvalidItem")); user.sendTl("itemnameInvalidItem");
return; return;
} }
final TriState wildcard = user.isAuthorizedExact(PERM_PREFIX + "*"); final TriState wildcard = user.isAuthorizedExact(PERM_PREFIX + "*");
final TriState material = user.isAuthorizedExact(PERM_PREFIX + item.getType().name().toLowerCase()); final TriState material = user.isAuthorizedExact(PERM_PREFIX + item.getType().name().toLowerCase());
if ((wildcard == TriState.TRUE && material != TriState.FALSE) || ((wildcard != TriState.TRUE) && material == TriState.TRUE)) { if ((wildcard == TriState.TRUE && material != TriState.FALSE) || ((wildcard != TriState.TRUE) && material == TriState.TRUE)) {
user.sendMessage(tl("itemnameInvalidItem")); user.sendTl("itemnameInvalidItem");
return; return;
} }
@ -45,7 +43,7 @@ public class Commanditemname extends EssentialsCommand {
final ItemMeta im = item.getItemMeta(); final ItemMeta im = item.getItemMeta();
im.setDisplayName(name); im.setDisplayName(name);
item.setItemMeta(im); item.setItemMeta(im);
user.sendMessage(name == null ? tl("itemnameClear") : tl("itemnameSuccess", name)); user.sendTl(name == null ? "itemnameClear" : "itemnameSuccess", name);
} }
@Override @Override

View File

@ -4,8 +4,6 @@ import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.utils.StringUtil; import com.earth2me.essentials.utils.StringUtil;
import org.bukkit.Server; import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandjails extends EssentialsCommand { public class Commandjails extends EssentialsCommand {
public Commandjails() { public Commandjails() {
super("jails"); super("jails");
@ -14,9 +12,9 @@ public class Commandjails extends EssentialsCommand {
@Override @Override
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (ess.getJails().getCount() == 0) { if (ess.getJails().getCount() == 0) {
sender.sendMessage(tl("noJailsDefined")); sender.sendTl("noJailsDefined");
} else { } else {
sender.sendMessage(tl("jailList", StringUtil.joinList(" ", ess.getJails().getList()))); sender.sendTl("jailList", StringUtil.joinList(" ", ess.getJails().getList()));
} }
} }
} }

View File

@ -4,6 +4,7 @@ import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.LocationUtil; import com.earth2me.essentials.utils.LocationUtil;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import net.ess3.api.TranslatableException;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
@ -11,8 +12,6 @@ import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static com.earth2me.essentials.I18n.tl;
// This method contains an undocumented sub command #EasterEgg // This method contains an undocumented sub command #EasterEgg
public class Commandjump extends EssentialsCommand { public class Commandjump extends EssentialsCommand {
public Commandjump() { public Commandjump() {
@ -24,10 +23,10 @@ public class Commandjump extends EssentialsCommand {
if (args.length > 0 && args[0].contains("lock") && user.isAuthorized("essentials.jump.lock")) { if (args.length > 0 && args[0].contains("lock") && user.isAuthorized("essentials.jump.lock")) {
if (user.isFlyClickJump()) { if (user.isFlyClickJump()) {
user.setRightClickJump(false); user.setRightClickJump(false);
user.sendMessage(tl("jumpEasterDisable")); user.sendTl("jumpEasterDisable");
} else { } else {
user.setRightClickJump(true); user.setRightClickJump(true);
user.sendMessage(tl("jumpEasterEnable")); user.sendTl("jumpEasterEnable");
} }
return; return;
} }
@ -41,7 +40,7 @@ public class Commandjump extends EssentialsCommand {
loc.setPitch(cloc.getPitch()); loc.setPitch(cloc.getPitch());
loc.setY(loc.getY() + 1); loc.setY(loc.getY() + 1);
} catch (final NullPointerException ex) { } catch (final NullPointerException ex) {
throw new Exception(tl("jumpError"), ex); throw new TranslatableException(ex, "jumpError");
} }
final Trade charge = new Trade(this.getName(), ess); final Trade charge = new Trade(this.getName(), ess);

View File

@ -3,7 +3,9 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.Console; import com.earth2me.essentials.Console;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.AdventureUtil;
import com.earth2me.essentials.utils.FormatUtil; import com.earth2me.essentials.utils.FormatUtil;
import net.ess3.api.TranslatableException;
import net.essentialsx.api.v2.events.UserKickEvent; import net.essentialsx.api.v2.events.UserKickEvent;
import org.bukkit.Server; import org.bukkit.Server;
@ -11,7 +13,7 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.logging.Level; import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tlLiteral;
public class Commandkick extends EssentialsCommand { public class Commandkick extends EssentialsCommand {
public Commandkick() { public Commandkick() {
@ -33,11 +35,11 @@ public class Commandkick extends EssentialsCommand {
} }
if (target.isAuthorized("essentials.kick.exempt")) { if (target.isAuthorized("essentials.kick.exempt")) {
throw new Exception(tl("kickExempt")); throw new TranslatableException("kickExempt");
} }
} }
String kickReason = args.length > 1 ? getFinalArg(args, 1) : tl("kickDefault"); String kickReason = args.length > 1 ? getFinalArg(args, 1) : AdventureUtil.miniToLegacy(tlLiteral("kickDefault"));
kickReason = FormatUtil.replaceFormat(kickReason.replace("\\n", "\n").replace("|", "\n")); kickReason = FormatUtil.replaceFormat(kickReason.replace("\\n", "\n").replace("|", "\n"));
final UserKickEvent event = new UserKickEvent(user, target, kickReason); final UserKickEvent event = new UserKickEvent(user, target, kickReason);
@ -51,8 +53,10 @@ public class Commandkick extends EssentialsCommand {
target.getBase().kickPlayer(kickReason); target.getBase().kickPlayer(kickReason);
final String senderDisplayName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.DISPLAY_NAME; final String senderDisplayName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.DISPLAY_NAME;
ess.getLogger().log(Level.INFO, tl("playerKicked", senderDisplayName, target.getName(), kickReason)); final String tlKey = "playerKicked";
ess.broadcastMessage("essentials.kick.notify", tl("playerKicked", senderDisplayName, target.getName(), kickReason)); final Object[] objects = {senderDisplayName, target.getName(), kickReason};
ess.getLogger().log(Level.INFO, AdventureUtil.miniToLegacy(tlLiteral(tlKey, objects)));
ess.broadcastTl(null, "essentials.kick.notify", tlKey, objects);
} }
@Override @Override

View File

@ -1,11 +1,12 @@
package com.earth2me.essentials.commands; package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.utils.AdventureUtil;
import com.earth2me.essentials.utils.FormatUtil; import com.earth2me.essentials.utils.FormatUtil;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import static com.earth2me.essentials.I18n.tl; import static com.earth2me.essentials.I18n.tlLiteral;
public class Commandkickall extends EssentialsCommand { public class Commandkickall extends EssentialsCommand {
public Commandkickall() { public Commandkickall() {
@ -14,7 +15,7 @@ public class Commandkickall extends EssentialsCommand {
@Override @Override
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
String kickReason = args.length > 0 ? getFinalArg(args, 0) : tl("kickDefault"); String kickReason = args.length > 0 ? getFinalArg(args, 0) : AdventureUtil.miniToLegacy(tlLiteral("kickDefault"));
kickReason = FormatUtil.replaceFormat(kickReason.replace("\\n", "\n").replace("|", "\n")); kickReason = FormatUtil.replaceFormat(kickReason.replace("\\n", "\n").replace("|", "\n"));
for (final Player onlinePlayer : ess.getOnlinePlayers()) { for (final Player onlinePlayer : ess.getOnlinePlayers()) {
@ -24,6 +25,6 @@ public class Commandkickall extends EssentialsCommand {
} }
} }
} }
sender.sendMessage(tl("kickedAll")); sender.sendTl("kickedAll");
} }
} }

View File

@ -9,8 +9,6 @@ import org.bukkit.event.entity.EntityDamageEvent;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandkill extends EssentialsLoopCommand { public class Commandkill extends EssentialsLoopCommand {
public Commandkill() { public Commandkill() {
super("kill"); super("kill");
@ -29,7 +27,7 @@ public class Commandkill extends EssentialsLoopCommand {
protected void updatePlayer(final Server server, final CommandSource sender, final User user, final String[] args) throws PlayerExemptException { protected void updatePlayer(final Server server, final CommandSource sender, final User user, final String[] args) throws PlayerExemptException {
final Player matchPlayer = user.getBase(); final Player matchPlayer = user.getBase();
if (sender.isPlayer() && user.isAuthorized("essentials.kill.exempt") && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.kill.force")) { if (sender.isPlayer() && user.isAuthorized("essentials.kill.exempt") && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.kill.force")) {
throw new PlayerExemptException(tl("killExempt", matchPlayer.getDisplayName())); throw new PlayerExemptException("killExempt", matchPlayer.getDisplayName());
} }
final EntityDamageEvent ede = new EntityDamageEvent(matchPlayer, sender.isPlayer() && sender.getPlayer().getName().equals(matchPlayer.getName()) ? EntityDamageEvent.DamageCause.SUICIDE : EntityDamageEvent.DamageCause.CUSTOM, Float.MAX_VALUE); final EntityDamageEvent ede = new EntityDamageEvent(matchPlayer, sender.isPlayer() && sender.getPlayer().getName().equals(matchPlayer.getName()) ? EntityDamageEvent.DamageCause.SUICIDE : EntityDamageEvent.DamageCause.CUSTOM, Float.MAX_VALUE);
server.getPluginManager().callEvent(ede); server.getPluginManager().callEvent(ede);
@ -38,7 +36,7 @@ public class Commandkill extends EssentialsLoopCommand {
} }
ede.getEntity().setLastDamageCause(ede); ede.getEntity().setLastDamageCause(ede);
matchPlayer.setHealth(0); matchPlayer.setHealth(0);
sender.sendMessage(tl("kill", matchPlayer.getDisplayName())); sender.sendTl("kill", matchPlayer.getDisplayName());
} }
@Override @Override

View File

@ -3,7 +3,9 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.Kit; import com.earth2me.essentials.Kit;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.AdventureUtil;
import com.earth2me.essentials.utils.StringUtil; import com.earth2me.essentials.utils.StringUtil;
import net.ess3.api.TranslatableException;
import org.bukkit.Server; import org.bukkit.Server;
import java.util.ArrayList; import java.util.ArrayList;
@ -12,8 +14,6 @@ import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.logging.Level; import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tl;
public class Commandkit extends EssentialsCommand { public class Commandkit extends EssentialsCommand {
public Commandkit() { public Commandkit() {
super("kit"); super("kit");
@ -23,7 +23,7 @@ public class Commandkit extends EssentialsCommand {
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (args.length < 1) { if (args.length < 1) {
final String kitList = ess.getKits().listKits(ess, user); final String kitList = ess.getKits().listKits(ess, user);
user.sendMessage(kitList.length() > 0 ? tl("kits", kitList) : tl("noKits")); user.sendTl(kitList.length() > 0 ? "kits" : "noKits", AdventureUtil.parsed(kitList));
throw new NoChargeException(); throw new NoChargeException();
} else if (args.length > 1 && user.isAuthorized("essentials.kit.others")) { } else if (args.length > 1 && user.isAuthorized("essentials.kit.others")) {
giveKits(getPlayer(server, user, args, 1), user, StringUtil.sanitizeString(args[0].toLowerCase(Locale.ENGLISH)).trim()); giveKits(getPlayer(server, user, args, 1), user, StringUtil.sanitizeString(args[0].toLowerCase(Locale.ENGLISH)).trim());
@ -36,7 +36,7 @@ public class Commandkit extends EssentialsCommand {
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (args.length < 2) { if (args.length < 2) {
final String kitList = ess.getKits().listKits(ess, null); final String kitList = ess.getKits().listKits(ess, null);
sender.sendMessage(kitList.length() > 0 ? tl("kits", kitList) : tl("noKits")); sender.sendTl(kitList.length() > 0 ? "kits" : "noKits", AdventureUtil.parsed(kitList));
throw new NoChargeException(); throw new NoChargeException();
} else { } else {
final User userTo = getPlayer(server, args, 1, true, false); final User userTo = getPlayer(server, args, 1, true, false);
@ -44,22 +44,22 @@ public class Commandkit extends EssentialsCommand {
for (final String kitName : args[0].toLowerCase(Locale.ENGLISH).split(",")) { for (final String kitName : args[0].toLowerCase(Locale.ENGLISH).split(",")) {
new Kit(kitName, ess).expandItems(userTo); new Kit(kitName, ess).expandItems(userTo);
sender.sendMessage(tl("kitGiveTo", kitName, userTo.getDisplayName())); sender.sendTl("kitGiveTo", kitName, userTo.getDisplayName());
userTo.sendMessage(tl("kitReceive", kitName)); userTo.sendTl("kitReceive", kitName);
} }
} }
} }
private void giveKits(final User userTo, final User userFrom, final String kitNames) throws Exception { private void giveKits(final User userTo, final User userFrom, final String kitNames) throws Exception {
if (kitNames.isEmpty()) { if (kitNames.isEmpty()) {
throw new Exception(tl("kitNotFound")); throw new TranslatableException("kitNotFound");
} }
final List<Kit> kits = new ArrayList<>(); final List<Kit> kits = new ArrayList<>();
for (final String kitName : kitNames.split(",")) { for (final String kitName : kitNames.split(",")) {
if (kitName.isEmpty()) { if (kitName.isEmpty()) {
throw new Exception(tl("kitNotFound")); throw new TranslatableException("kitNotFound");
} }
final Kit kit = new Kit(kitName, ess); final Kit kit = new Kit(kitName, ess);
@ -80,10 +80,10 @@ public class Commandkit extends EssentialsCommand {
kit.chargeUser(userTo); kit.chargeUser(userTo);
if (!userFrom.equals(userTo)) { if (!userFrom.equals(userTo)) {
userFrom.sendMessage(tl("kitGiveTo", kit.getName(), userTo.getDisplayName())); userFrom.sendTl("kitGiveTo", kit.getName(), userTo.getDisplayName());
} }
userTo.sendMessage(tl("kitReceive", kit.getName())); userTo.sendTl("kitReceive", kit.getName());
} catch (final NoChargeException ex) { } catch (final NoChargeException ex) {
if (ess.getSettings().isDebug()) { if (ess.getSettings().isDebug()) {

View File

@ -2,14 +2,13 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import net.ess3.api.TranslatableException;
import org.bukkit.Server; import org.bukkit.Server;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandkitreset extends EssentialsCommand { public class Commandkitreset extends EssentialsCommand {
public Commandkitreset() { public Commandkitreset() {
super("kitreset"); super("kitreset");
@ -23,7 +22,7 @@ public class Commandkitreset extends EssentialsCommand {
final String kitName = args[0]; final String kitName = args[0];
if (ess.getKits().getKit(kitName) == null) { if (ess.getKits().getKit(kitName) == null) {
throw new Exception(tl("kitNotFound")); throw new TranslatableException("kitNotFound");
} }
User target = user; User target = user;
@ -33,9 +32,9 @@ public class Commandkitreset extends EssentialsCommand {
target.setKitTimestamp(kitName, 0); target.setKitTimestamp(kitName, 0);
if (user.equals(target)) { if (user.equals(target)) {
user.sendMessage(tl("kitReset", kitName)); user.sendTl("kitReset", kitName);
} else { } else {
user.sendMessage(tl("kitResetOther", kitName, target.getDisplayName())); user.sendTl("kitResetOther", kitName, target.getDisplayName());
} }
} }
@ -47,19 +46,19 @@ public class Commandkitreset extends EssentialsCommand {
final String kitName = args[0]; final String kitName = args[0];
if (ess.getKits().getKit(kitName) == null) { if (ess.getKits().getKit(kitName) == null) {
throw new Exception(tl("kitNotFound")); throw new TranslatableException("kitNotFound");
} }
final User target = getPlayer(server, sender, args, 1); final User target = getPlayer(server, sender, args, 1);
target.setKitTimestamp(kitName, 0); target.setKitTimestamp(kitName, 0);
sender.sendMessage(tl("kitResetOther", kitName, target.getDisplayName())); sender.sendTl("kitResetOther", kitName, target.getDisplayName());
} }
@Override @Override
protected List<String> getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) { protected List<String> getTabCompleteOptions(Server server, CommandSource sender, String commandLabel, String[] args) {
if (args.length == 1) { if (args.length == 1) {
return new ArrayList<>(ess.getKits().getKitKeys()); return new ArrayList<>(ess.getKits().getKitKeys());
} else if (args.length == 2 && sender.isAuthorized("essentials.kitreset.others", ess)) { } else if (args.length == 2 && sender.isAuthorized("essentials.kitreset.others")) {
return getPlayers(server, sender); return getPlayers(server, sender);
} else { } else {
return Collections.emptyList(); return Collections.emptyList();

View File

@ -9,8 +9,6 @@ import org.bukkit.entity.LightningStrike;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandlightning extends EssentialsLoopCommand { public class Commandlightning extends EssentialsLoopCommand {
public Commandlightning() { public Commandlightning() {
super("lightning"); super("lightning");
@ -18,9 +16,9 @@ public class Commandlightning extends EssentialsLoopCommand {
@Override @Override
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (args.length == 0 || !sender.isAuthorized("essentials.lightning.others", ess)) { if (args.length == 0 || !sender.isAuthorized("essentials.lightning.others")) {
if (sender.isPlayer()) { if (sender.isPlayer()) {
sender.getPlayer().getWorld().strikeLightning(sender.getUser(ess).getTargetBlock(600).getLocation()); sender.getPlayer().getWorld().strikeLightning(sender.getUser().getTargetBlock(600).getLocation());
return; return;
} }
throw new NotEnoughArgumentsException(); throw new NotEnoughArgumentsException();
@ -35,14 +33,14 @@ public class Commandlightning extends EssentialsLoopCommand {
} }
final int finalPower = power; final int finalPower = power;
loopOnlinePlayersConsumer(server, sender, false, true, args[0], player -> { loopOnlinePlayersConsumer(server, sender, false, true, args[0], player -> {
sender.sendMessage(tl("lightningUse", player.getDisplayName())); sender.sendTl("lightningUse", player.getDisplayName());
final LightningStrike strike = player.getBase().getWorld().strikeLightningEffect(player.getBase().getLocation()); final LightningStrike strike = player.getBase().getWorld().strikeLightningEffect(player.getBase().getLocation());
if (!player.isGodModeEnabled()) { if (!player.isGodModeEnabled()) {
player.getBase().damage(finalPower, strike); player.getBase().damage(finalPower, strike);
} }
if (ess.getSettings().warnOnSmite()) { if (ess.getSettings().warnOnSmite()) {
player.sendMessage(tl("lightningSmited")); player.sendTl("lightningSmited");
} }
}); });
loopOnlinePlayers(server, sender, true, true, args[0], null); loopOnlinePlayers(server, sender, true, true, args[0], null);

View File

@ -3,6 +3,7 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.PlayerList; import com.earth2me.essentials.PlayerList;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.AdventureUtil;
import org.bukkit.Server; import org.bukkit.Server;
import java.util.ArrayList; import java.util.ArrayList;
@ -23,11 +24,11 @@ public class Commandlist extends EssentialsCommand {
user = ess.getUser(sender.getPlayer()); user = ess.getUser(sender.getPlayer());
showHidden = user.isAuthorized("essentials.list.hidden") || user.canInteractVanished(); showHidden = user.isAuthorized("essentials.list.hidden") || user.canInteractVanished();
} }
sender.sendMessage(PlayerList.listSummary(ess, user, showHidden)); sender.sendComponent(AdventureUtil.miniMessage().deserialize(PlayerList.listSummary(ess, user, showHidden)));
final Map<String, List<User>> playerList = PlayerList.getPlayerLists(ess, user, showHidden); final Map<String, List<User>> playerList = PlayerList.getPlayerLists(ess, user, showHidden);
if (args.length > 0) { if (args.length > 0) {
sender.sendMessage(PlayerList.listGroupUsers(ess, playerList, args[0].toLowerCase())); sender.sendComponent(AdventureUtil.miniMessage().deserialize(PlayerList.listGroupUsers(ess, playerList, args[0].toLowerCase())));
} else { } else {
sendGroupedList(sender, commandLabel, playerList); sendGroupedList(sender, commandLabel, playerList);
} }
@ -35,15 +36,15 @@ public class Commandlist extends EssentialsCommand {
// Output the standard /list output, when no group is specified // Output the standard /list output, when no group is specified
private void sendGroupedList(final CommandSource sender, final String commandLabel, final Map<String, List<User>> playerList) { private void sendGroupedList(final CommandSource sender, final String commandLabel, final Map<String, List<User>> playerList) {
for (final String str : PlayerList.prepareGroupedList(ess, commandLabel, playerList)) { for (final String str : PlayerList.prepareGroupedList(ess, sender, commandLabel, playerList)) {
sender.sendMessage(str); sender.sendComponent(AdventureUtil.miniMessage().deserialize(str));
} }
} }
@Override @Override
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
if (args.length == 1) { if (args.length == 1) {
return new ArrayList<>(PlayerList.getPlayerLists(ess, sender.getUser(ess), false).keySet()); return new ArrayList<>(PlayerList.getPlayerLists(ess, sender.getUser(), false).keySet());
} else { } else {
return Collections.emptyList(); return Collections.emptyList();
} }

View File

@ -3,8 +3,6 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import org.bukkit.Server; import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandloom extends EssentialsCommand { public class Commandloom extends EssentialsCommand {
public Commandloom() { public Commandloom() {
@ -14,7 +12,7 @@ public class Commandloom extends EssentialsCommand {
@Override @Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (ess.getContainerProvider() == null) { if (ess.getContainerProvider() == null) {
user.sendMessage(tl("unsupportedBrand")); user.sendTl("unsupportedBrand");
return; return;
} }

Some files were not shown because too many files have changed in this diff Show More