We're going on an Adventure! (#4717)

https://user-images.githubusercontent.com/10731363/147530817-f9adc58e-18a5-49ed-84c6-106e51d6948f.mp4
Add support for chat components throughout EssentialsX using the Adventure library.  
Translations have been converted to the MiniMessage format, and custom message files will be migrated on startup.  
This also introduces new options to allow players to see messages in their own language and for server owners to change the main message colours without editing message files.

Closes #2029
Closes #2391

---------

Co-authored-by: MD <1917406+mdcfe@users.noreply.github.com>
Co-authored-by: pop4959 <pop4959@gmail.com>
This commit is contained in:
Josh Roy 2024-02-03 15:38:14 -05:00 committed by GitHub
parent 8234dedb22
commit 388d571da9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
326 changed files with 25766 additions and 25181 deletions

View File

@ -6,18 +6,21 @@ dependencies {
compileOnly('com.github.milkbowl:VaultAPI:1.7') {
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 'org.bstats:bstats-bukkit:2.2.1'
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.1'
// Providers
api project(':providers:BaseProviders')
api project(':providers:PaperProvider')
api project(path: ':providers:PaperProvider', configuration: 'shadow')
api(project(':providers:NMSReflectionProvider')) {
exclude group: "org.bukkit", module: "bukkit"
}
@ -43,8 +46,25 @@ shadowJar {
include (dependency('org.yaml:snakeyaml'))
include (dependency('io.leangen.geantyref:geantyref'))
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:PaperProvider'))
include (project(path: ':providers:PaperProvider', configuration: 'shadow'))
include (project(':providers:NMSReflectionProvider'))
include (project(':providers:1_8Provider'))
include (project(':providers:1_12Provider'))
@ -55,8 +75,13 @@ shadowJar {
relocate 'org.yaml.snakeyaml', 'com.earth2me.essentials.libs.snakeyaml'
relocate 'io.leangen.geantyref', 'com.earth2me.essentials.libs.geantyref'
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 {
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.IUser;
import net.ess3.api.InvalidWorldException;
import net.ess3.api.TranslatableException;
import net.ess3.api.events.UserWarpEvent;
import net.ess3.api.events.teleport.PreTeleportEvent;
import net.ess3.api.events.teleport.TeleportWarmupEvent;
@ -23,8 +24,6 @@ import java.util.GregorianCalendar;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import static com.earth2me.essentials.I18n.tl;
public class AsyncTeleport implements IAsyncTeleport {
private final IUser teleportOwner;
private final IEssentials ess;
@ -73,7 +72,7 @@ public class AsyncTeleport implements IAsyncTeleport {
time.setTimeInMillis(lastTime);
time.add(Calendar.SECOND, (int) cooldown);
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;
}
}
@ -107,7 +106,7 @@ public class AsyncTeleport implements IAsyncTeleport {
final Calendar c = new GregorianCalendar();
c.add(Calendar.SECOND, (int) delay);
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
@ -129,7 +128,7 @@ public class AsyncTeleport implements IAsyncTeleport {
nowAsync(teleportOwner, target, cause, future);
future.thenAccept(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().isTeleportPassengerDismount()) {
future.completeExceptionally(new Exception(tl("passengerTeleportFail")));
future.completeExceptionally(new TranslatableException("passengerTeleportFail"));
return;
}
@ -204,7 +203,7 @@ public class AsyncTeleport implements IAsyncTeleport {
}
}
} 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;
}
} else {
@ -233,7 +232,7 @@ public class AsyncTeleport implements IAsyncTeleport {
@Override
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);
}
@ -248,8 +247,8 @@ public class AsyncTeleport implements IAsyncTeleport {
teleport(otherUser, target, chargeFor, cause, future);
future.thenAccept(success -> {
if (success) {
otherUser.sendMessage(tl("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()));
otherUser.sendTl("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;
future.thenAccept(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)) {
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) {
tpType = TeleportType.BACK;
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);
}

View File

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

View File

@ -11,7 +11,7 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tl;
import static com.earth2me.essentials.I18n.tlLiteral;
public class Backup implements Runnable {
private transient final Server server;
@ -79,7 +79,7 @@ public class Backup implements Runnable {
taskLock.complete(new Object());
return;
}
ess.getLogger().log(Level.INFO, tl("backupStarted"));
ess.getLogger().log(Level.INFO, tlLiteral("backupStarted"));
final CommandSender cs = server.getConsoleSender();
server.dispatchCommand(cs, "save-all");
server.dispatchCommand(cs, "save-off");
@ -118,7 +118,7 @@ public class Backup implements Runnable {
}
active = false;
taskLock.complete(new Object());
ess.getLogger().log(Level.INFO, tl("backupFinished"));
ess.getLogger().log(Level.INFO, tlLiteral("backupFinished"));
}
}

View File

@ -1,12 +1,19 @@
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.entity.Player;
import static com.earth2me.essentials.I18n.tlLiteral;
public class CommandSource {
protected Essentials ess;
protected CommandSender sender;
public CommandSource(final CommandSender base) {
public CommandSource(final Essentials ess, final CommandSender base) {
this.ess = ess;
this.sender = base;
}
@ -21,7 +28,40 @@ public class CommandSource {
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) {
return ess.getUser((Player) sender);
}
@ -42,15 +82,18 @@ public class CommandSource {
}
}
public boolean isAuthorized(final String permission, final IEssentials ess) {
return !(sender instanceof Player) || getUser(ess).isAuthorized(permission);
public boolean isAuthorized(final String permission) {
//noinspection ConstantConditions
return !(sender instanceof Player) || getUser().isAuthorized(permission);
}
public String getSelfSelector() {
//noinspection ConstantConditions
return sender instanceof Player ? getPlayer().getName() : "*";
}
public String getDisplayName() {
//noinspection ConstantConditions
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.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.command.CommandSender;
import org.bukkit.entity.Player;
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 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 final IEssentials ess;
@ -63,6 +66,21 @@ public final class Console implements IMessageRecipient {
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
public boolean isReachable() {
return true;

View File

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

View File

@ -32,8 +32,6 @@ import java.util.List;
import java.util.logging.Level;
import java.util.regex.Pattern;
import static com.earth2me.essentials.I18n.tl;
public class EssentialsEntityListener implements Listener {
private static final transient Pattern powertoolPlayer = Pattern.compile("\\{player\\}");
private final IEssentials ess;
@ -167,11 +165,11 @@ public class EssentialsEntityListener implements Listener {
final User user = ess.getUser(event.getEntity());
if (ess.getSettings().infoAfterDeath()) {
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")) {
user.setLastLocation();
user.sendMessage(tl("backAfterDeath"));
user.sendTl("backAfterDeath");
}
if (!ess.getSettings().areDeathMessagesEnabled()) {
event.setDeathMessage("");

View File

@ -6,6 +6,7 @@ import com.earth2me.essentials.textreader.IText;
import com.earth2me.essentials.textreader.KeywordReplacer;
import com.earth2me.essentials.textreader.TextInput;
import com.earth2me.essentials.textreader.TextPager;
import com.earth2me.essentials.utils.CommonPlaceholders;
import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.FormatUtil;
import com.earth2me.essentials.utils.LocationUtil;
@ -18,6 +19,7 @@ import net.ess3.provider.CommandSendListenerProvider;
import net.ess3.provider.providers.BukkitCommandSendListenerProvider;
import net.ess3.provider.providers.PaperCommandSendListenerProvider;
import net.essentialsx.api.v2.events.AsyncUserDataLoadEvent;
import net.kyori.adventure.text.Component;
import org.bukkit.BanEntry;
import org.bukkit.BanList;
import org.bukkit.GameMode;
@ -75,7 +77,7 @@ import java.util.function.Predicate;
import java.util.logging.Level;
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 {
private final transient IEssentials ess;
@ -173,12 +175,20 @@ public class EssentialsPlayerListener implements Listener, FakeAccessor {
final String dateDiff = user.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(user.getMuteTimeout()) : 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 {
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(tlLiteral("mutedUserSpeaks", user.getName(), event.getMessage()));
}
try {
final Iterator<Player> it = event.getRecipients().iterator();
@ -423,7 +433,7 @@ public class EssentialsPlayerListener implements Listener, FakeAccessor {
if (!ess.getSettings().isCommandDisabled("mail") && user.isAuthorized("essentials.mail")) {
if (user.getUnreadMailAmount() == 0) {
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 {
user.notifyOfMail();
@ -432,8 +442,8 @@ public class EssentialsPlayerListener implements Listener, FakeAccessor {
if (user.isAuthorized("essentials.updatecheck")) {
ess.runTaskAsynchronously(() -> {
for (String str : ess.getUpdateChecker().getVersionMessages(false, false)) {
user.sendMessage(str);
for (final Component component : ess.getUpdateChecker().getVersionMessages(false, false, user.getSource())) {
user.sendComponent(component);
}
});
}
@ -444,7 +454,7 @@ public class EssentialsPlayerListener implements Listener, FakeAccessor {
user.getBase().setAllowFlight(true);
user.getBase().setFlying(true);
if (ess.getSettings().isSendFlyEnableOnJoin()) {
user.getBase().sendMessage(tl("flyMode", tl("enabled"), user.getDisplayName()));
user.sendTl("flyMode", CommonPlaceholders.enableDisable(user.getSource(), true), CommonPlaceholders.displayName(user));
}
}
}
@ -534,14 +544,14 @@ public class EssentialsPlayerListener implements Listener, FakeAccessor {
final Date banExpiry = banEntry.getExpiration();
if (banExpiry != null) {
final String expiry = DateUtil.formatDateDiff(banExpiry.getTime());
event.setKickMessage(tl("tempbanJoin", expiry, banEntry.getReason()));
event.setKickMessage(tlLiteral("tempbanJoin", expiry, banEntry.getReason()));
} else {
event.setKickMessage(tl("banJoin", banEntry.getReason()));
event.setKickMessage(tlLiteral("banJoin", banEntry.getReason()));
}
} else {
banEntry = ess.getServer().getBanList(BanList.Type.IP).getBanEntry(event.getAddress().getHostAddress());
if (banEntry != null) {
event.setKickMessage(tl("banIpJoin", banEntry.getReason()));
event.setKickMessage(tlLiteral("banIpJoin", banEntry.getReason()));
}
}
}
@ -557,7 +567,7 @@ public class EssentialsPlayerListener implements Listener, FakeAccessor {
return;
}
if (ess.getSettings().isCustomServerFullMessage()) {
event.disallow(Result.KICK_FULL, tl("serverFull"));
event.disallow(Result.KICK_FULL, tlLiteral("serverFull"));
}
}
}
@ -632,9 +642,9 @@ public class EssentialsPlayerListener implements Listener, FakeAccessor {
for (final User spyer : ess.getOnlineUsers()) {
if (spyer.isSocialSpyEnabled() && !player.equals(spyer.getBase())) {
if (user.isMuted() && ess.getSettings().getSocialSpyListenMutedPlayers()) {
spyer.sendMessage(tl("socialSpyMutedPrefix") + player.getDisplayName() + ": " + event.getMessage());
spyer.sendMessage(spyer.playerTl("socialSpyMutedPrefix") + player.getDisplayName() + ": " + event.getMessage());
} else {
spyer.sendMessage(tl("socialSpyPrefix") + player.getDisplayName() + ": " + event.getMessage());
spyer.sendMessage(spyer.playerTl("socialSpyPrefix") + player.getDisplayName() + ": " + event.getMessage());
}
}
}
@ -647,11 +657,19 @@ public class EssentialsPlayerListener implements Listener, FakeAccessor {
event.setCancelled(true);
final String dateDiff = user.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(user.getMuteTimeout()) : 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 {
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(tlLiteral("mutedUserSpeaks", player.getName(), event.getMessage()));
return;
}
@ -696,7 +714,7 @@ public class EssentialsPlayerListener implements Listener, FakeAccessor {
// User's current cooldown hasn't expired, inform and terminate cooldown code.
if (entry.getValue() > System.currentTimeMillis()) {
final String commandCooldownTime = DateUtil.formatDateDiff(entry.getValue());
user.sendMessage(tl("commandCooldown", commandCooldownTime));
user.sendTl("commandCooldown", commandCooldownTime);
cooldownFound = true;
event.setCancelled(true);
break;
@ -759,11 +777,11 @@ public class EssentialsPlayerListener implements Listener, FakeAccessor {
if (ess.getSettings().getNoGodWorlds().contains(newWorld) && user.isGodModeEnabledRaw()) {
// 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()
user.sendMessage(tl("noGodWorldWarning"));
user.sendTl("noGodWorldWarning");
}
if (!user.getWorld().getName().equals(newWorld)) {
user.sendMessage(tl("currentWorld", newWorld));
user.sendTl("currentWorld", newWorld);
}
if (user.isVanished()) {
user.setVanished(user.isAuthorized("essentials.vanish"));
@ -785,7 +803,7 @@ public class EssentialsPlayerListener implements Listener, FakeAccessor {
player.getBase().setBedSpawnLocation(event.getClickedBlock().getLocation());
// In 1.15 and above, vanilla sends its own bed spawn message.
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.craftbukkit.BanLookup;
import com.earth2me.essentials.userstorage.ModernUUIDCache;
import com.earth2me.essentials.utils.AdventureUtil;
import com.earth2me.essentials.utils.StringUtil;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import com.google.gson.reflect.TypeToken;
import net.ess3.api.IEssentials;
import net.essentialsx.api.v2.services.mail.MailMessage;
import nu.studer.java.util.OrderedProperties;
import org.bukkit.BanList;
import org.bukkit.Bukkit;
import org.bukkit.Location;
@ -49,7 +51,7 @@ import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.regex.Pattern;
import static com.earth2me.essentials.I18n.tl;
import static com.earth2me.essentials.I18n.tlLiteral;
public class EssentialsUpgrade {
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.save();
} catch (final IOException e) {
ess.getLogger().log(Level.SEVERE, tl("upgradingFilesError"), e);
ess.getLogger().log(Level.SEVERE, tlLiteral("upgradingFilesError"), e);
}
}
@ -528,10 +530,10 @@ public class EssentialsUpgrade {
bWriter.close();
if (needUpdate) {
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)) {
throw new Exception(tl("configFileRenameError"));
throw new Exception(tlLiteral("configFileRenameError"));
}
} else {
tempFile.delete();
@ -656,15 +658,15 @@ public class EssentialsUpgrade {
final File tmpFile = new File(listOfFile.getParentFile(), sanitizedFilename + ".tmp");
final File newFile = new File(listOfFile.getParentFile(), sanitizedFilename);
if (!listOfFile.renameTo(tmpFile)) {
ess.getLogger().log(Level.WARNING, tl("userdataMoveError", filename, sanitizedFilename));
ess.getLogger().log(Level.WARNING, tlLiteral("userdataMoveError", filename, sanitizedFilename));
continue;
}
if (newFile.exists()) {
ess.getLogger().log(Level.WARNING, tl("duplicatedUserdata", filename, sanitizedFilename));
ess.getLogger().log(Level.WARNING, tlLiteral("duplicatedUserdata", filename, sanitizedFilename));
continue;
}
if (!tmpFile.renameTo(newFile)) {
ess.getLogger().log(Level.WARNING, tl("userdataMoveBackError", sanitizedFilename, sanitizedFilename));
ess.getLogger().log(Level.WARNING, tlLiteral("userdataMoveBackError", sanitizedFilename, sanitizedFilename));
}
}
doneFile.setProperty("sanitizeAllUserFilenames", true);
@ -742,7 +744,7 @@ public class EssentialsUpgrade {
config.setProperty(entry.getKey(), loc);
}
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();
}
@ -770,7 +772,7 @@ public class EssentialsUpgrade {
config.setProperty(entry.getKey(), loc);
}
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();
}
@ -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() {
if (!ess.getDataFolder().exists()) {
ess.getDataFolder().mkdirs();

View File

@ -1,6 +1,8 @@
package com.earth2me.essentials;
import com.earth2me.essentials.utils.AdventureUtil;
import net.ess3.api.IEssentials;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.FileInputStream;
@ -13,25 +15,34 @@ import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.PropertyResourceBundle;
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.regex.Pattern;
public class I18n implements net.ess3.api.II18n {
private static final String MESSAGES = "messages";
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() {
@SuppressWarnings("NullableProblems")
public Enumeration<String> getKeys() {
return null;
}
protected Object handleGetObject(final String key) {
protected Object handleGetObject(final @NotNull String key) {
return null;
}
};
@ -40,30 +51,53 @@ public class I18n implements net.ess3.api.II18n {
private final transient ResourceBundle defaultBundle;
private final transient IEssentials ess;
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 Map<String, MessageFormat> messageFormatCache = new HashMap<>();
private final transient Map<Locale, Map<String, MessageFormat>> messageFormatCache = new HashMap<>();
public I18n(final IEssentials ess) {
this.ess = ess;
defaultBundle = ResourceBundle.getBundle(MESSAGES, Locale.ENGLISH, new UTF8PropertiesControl());
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) {
return "";
}
if (objects.length == 0) {
return NODOUBLEMARK.matcher(instance.translate(string)).replaceAll("'");
return NODOUBLEMARK.matcher(instance.translate(locale, tlKey)).replaceAll("'");
} else {
return instance.format(string, objects);
return instance.format(tlKey, objects);
}
}
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() {
@ -79,10 +113,44 @@ public class I18n implements net.ess3.api.II18n {
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 {
return customBundle.getString(string);
return getBundle(locale).getString(string);
} catch (final MissingResourceException ex) {
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) {
String format = translate(string);
MessageFormat messageFormat = messageFormatCache.get(format);
private String format(final String string, final Object... objects) {
return format(currentLocale, string, objects);
}
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) {
try {
messageFormat = new MessageFormat(format);
} catch (final IllegalArgumentException e) {
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);
}
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) {
if (loc != null && !loc.isEmpty()) {
final String[] parts = loc.split("[_\\.]");
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]);
}
currentLocale = getLocale(loc);
}
ResourceBundle.clearCache();
messageFormatCache = new HashMap<>();
loadedBundles.clear();
messageFormatCache.clear();
ess.getLogger().log(Level.INFO, String.format("Using locale %s", currentLocale.toString()));
try {
@ -132,28 +218,41 @@ public class I18n implements net.ess3.api.II18n {
} catch (final MissingResourceException ex) {
localeBundle = NULL_BUNDLE;
}
}
try {
customBundle = ResourceBundle.getBundle(MESSAGES, currentLocale, new FileResClassLoader(I18n.class.getClassLoader(), ess), new UTF8PropertiesControl());
} catch (final MissingResourceException ex) {
customBundle = NULL_BUNDLE;
public static Locale getLocale(final String loc) {
if (loc == null || loc.isEmpty()) {
return instance.currentLocale;
}
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.
*/
private static class FileResClassLoader extends ClassLoader {
private final transient File dataFolder;
private final transient File messagesFolder;
FileResClassLoader(final ClassLoader classLoader, final IEssentials ess) {
super(classLoader);
this.dataFolder = ess.getDataFolder();
this.messagesFolder = new File(ess.getDataFolder(), "messages");
//noinspection ResultOfMethodCallIgnored
this.messagesFolder.mkdirs();
}
@Override
public URL getResource(final String string) {
final File file = new File(dataFolder, string);
final File file = new File(messagesFolder, string);
if (file.exists()) {
try {
return file.toURI().toURL();
@ -165,7 +264,7 @@ public class I18n implements net.ess3.api.II18n {
@Override
public InputStream getResourceAsStream(final String string) {
final File file = new File(dataFolder, string);
final File file = new File(messagesFolder, string);
if (file.exists()) {
try {
return new FileInputStream(file);
@ -207,5 +306,13 @@ public class I18n implements net.ess3.api.II18n {
}
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.MaterialTagProvider;
import net.ess3.provider.PersistentDataProvider;
import net.ess3.provider.PlayerLocaleProvider;
import net.ess3.provider.SerializationProvider;
import net.ess3.provider.ServerStateProvider;
import net.ess3.provider.SignDataProvider;
@ -80,6 +81,16 @@ public interface IEssentials extends Plugin {
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();
BukkitScheduler getScheduler();
@ -170,5 +181,7 @@ public interface IEssentials extends Plugin {
SignDataProvider getSignDataProvider();
PlayerLocaleProvider getPlayerLocaleProvider();
PluginCommand getPluginCommand(String cmd);
}

View File

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

View File

@ -8,6 +8,8 @@ import net.ess3.api.MaxMoneyException;
import net.ess3.api.events.AfkStatusChangeEvent;
import net.essentialsx.api.v2.services.mail.MailMessage;
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.Material;
import org.bukkit.block.Block;
@ -15,7 +17,6 @@ import org.bukkit.entity.Player;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@ -142,6 +143,14 @@ public interface IUser {
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
*/

View File

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

View File

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

View File

@ -3,6 +3,7 @@ package com.earth2me.essentials;
import com.earth2me.essentials.config.ConfigurateUtil;
import com.earth2me.essentials.config.EssentialsConfiguration;
import com.earth2me.essentials.utils.NumberUtil;
import net.ess3.api.TranslatableException;
import org.spongepowered.configurate.CommentedConfigurationNode;
import java.io.File;
@ -14,7 +15,6 @@ import java.util.Map;
import java.util.Set;
import static com.earth2me.essentials.I18n.capitalCase;
import static com.earth2me.essentials.I18n.tl;
public class Kits implements IConf {
private final IEssentials ess;
@ -145,7 +145,7 @@ public class Kits implements IConf {
String name = capitalCase(kitItem);
final BigDecimal costPrice = new Trade("kit-" + kitItem.toLowerCase(Locale.ENGLISH), ess).getCommandCost(user);
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);
@ -153,7 +153,7 @@ public class Kits implements IConf {
if (nextUse == -1 && ess.getSettings().isSkippingUsedOneTimeKitsFromKitList()) {
continue;
} else if (nextUse != 0) {
name = tl("kitDelay", name);
name = user.playerTl("kitDelay", name);
}
list.append(" ").append(name).append(cost);
@ -161,7 +161,7 @@ public class Kits implements IConf {
}
return list.toString().trim();
} 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.Date;
import static com.earth2me.essentials.I18n.tl;
import static com.earth2me.essentials.I18n.tlLiteral;
public class MailServiceImpl implements MailService {
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) {
final String message = mail.getMessage();
if (mail.isLegacy()) {
return tl("mailMessage", message);
return tlLiteral("mailMessage", message);
}
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

@ -22,7 +22,7 @@ import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tl;
import static com.earth2me.essentials.I18n.tlLiteral;
public class ManagedFile {
private static final int BUFFERSIZE = 1024 * 8;
@ -45,7 +45,7 @@ public class ManagedFile {
try {
copyResourceAscii("/" + filename, file);
} catch (final IOException ex) {
Essentials.getWrappedLogger().log(Level.SEVERE, tl("itemsCsvNotLoaded", filename), ex);
Essentials.getWrappedLogger().log(Level.SEVERE, tlLiteral("itemsCsvNotLoaded", filename), ex);
}
}
}

View File

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

View File

@ -14,7 +14,7 @@ import java.util.Map;
import java.util.Set;
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
// Entities without a suffix, will default to 's'
@ -171,7 +171,7 @@ public enum Mob {
public Entity spawn(final World world, final Server server, final Location loc) throws MobException {
final Entity entity = world.spawn(loc, this.bukkitType.getEntityClass());
if (entity == null) {
Essentials.getWrappedLogger().log(Level.WARNING, tl("unableToSpawnMob"));
Essentials.getWrappedLogger().log(Level.WARNING, tlLiteral("unableToSpawnMob"));
throw new MobException();
}
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.StringUtil;
import com.earth2me.essentials.utils.VersionUtil;
import net.ess3.api.TranslatableException;
import org.bukkit.DyeColor;
import org.bukkit.Material;
import org.bukkit.entity.Ageable;
@ -38,8 +39,6 @@ import java.util.Locale;
import java.util.Random;
import java.util.stream.Collectors;
import static com.earth2me.essentials.I18n.tl;
public enum MobData {
BABY_AGEABLE("baby", Ageable.class, Data.BABY, true),
@ -328,14 +327,14 @@ public enum MobData {
}
this.matched = rawData;
} catch (final Exception e) {
throw new Exception(tl("sheepMalformedColor"), e);
throw new TranslatableException(e, "sheepMalformedColor");
}
} else if (this.value.equals(Data.EXP)) {
try {
((ExperienceOrb) spawned).setExperience(Integer.parseInt(rawData));
this.matched = rawData;
} catch (final NumberFormatException e) {
throw new Exception(tl("invalidNumber"), e);
throw new TranslatableException(e, "invalidNumber");
}
} else if (this.value.equals(Data.SIZE)) {
try {
@ -347,7 +346,7 @@ public enum MobData {
}
this.matched = rawData;
} catch (final NumberFormatException e) {
throw new Exception(tl("slimeMalformedSize"), e);
throw new TranslatableException(e, "slimeMalformedSize");
}
} else if (this.value instanceof Horse.Color) {
((Horse) spawned).setColor((Horse.Color) this.value);

View File

@ -2,6 +2,7 @@ package com.earth2me.essentials;
import com.earth2me.essentials.utils.FormatUtil;
import com.earth2me.essentials.utils.NumberUtil;
import net.ess3.api.TranslatableException;
import org.bukkit.ChatColor;
import org.bukkit.Server;
@ -14,7 +15,7 @@ import java.util.Locale;
import java.util.Map;
import java.util.Set;
import static com.earth2me.essentials.I18n.tl;
import static com.earth2me.essentials.I18n.tlLiteral;
public final class PlayerList {
@ -32,19 +33,19 @@ public final class PlayerList {
}
needComma = true;
if (user.isAfk()) {
groupString.append(tl("listAfkTag"));
groupString.append(tlLiteral("listAfkTag"));
}
if (user.isHidden()) {
groupString.append(tl("listHiddenTag"));
groupString.append(tlLiteral("listHiddenTag"));
}
user.setDisplayNick();
groupString.append(user.getDisplayName());
final String strippedNick = FormatUtil.stripFormat(user.getNickname());
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(ChatColor.WHITE);
}
return groupString.toString();
}
@ -62,13 +63,17 @@ public final class PlayerList {
}
}
}
final String online;
final String tlKey;
final Object[] objects;
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 {
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.
@ -117,7 +122,7 @@ public final class PlayerList {
users.addAll(groupUsers);
}
if (users.isEmpty()) {
throw new Exception(tl("groupDoesNotExist"));
throw new TranslatableException("groupDoesNotExist");
}
final String displayGroupName = Character.toTitleCase(groupName.charAt(0)) +
groupName.substring(1);
@ -126,11 +131,11 @@ public final class PlayerList {
// Build the output string
public static String outputFormat(final String group, final String message) {
return tl("listGroupTag", FormatUtil.replaceFormat(group)) +
return tlLiteral("listGroupTag", FormatUtil.replaceFormat(group)) +
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 Set<String> configGroups = ess.getSettings().getListGroupConfig().keySet();
@ -163,7 +168,9 @@ public final class PlayerList {
outputUserList = new ArrayList<>(matchedList);
final int limit = Integer.parseInt(groupValue);
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 {
output.add(outputFormat(oConfigGroup, listUsers(ess, outputUserList, ", ")));
}
@ -203,7 +210,7 @@ public final class PlayerList {
String groupName = asterisk.isEmpty() ? users.get(0).getGroup() : onlineGroup;
if (ess.getPermissionsHandler().getName().equals("ConfigPermissions")) {
groupName = tl("connectedPlayers");
groupName = source == null ? tlLiteral("connectedPlayers") : source.tl("connectedPlayers");
}
if (users == null || users.isEmpty()) {
continue;

View File

@ -8,12 +8,17 @@ import com.earth2me.essentials.signs.EssentialsSign;
import com.earth2me.essentials.signs.Signs;
import com.earth2me.essentials.textreader.IText;
import com.earth2me.essentials.textreader.SimpleTextInput;
import com.earth2me.essentials.utils.AdventureUtil;
import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.FormatUtil;
import com.earth2me.essentials.utils.LocationUtil;
import com.earth2me.essentials.utils.NumberUtil;
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.Color;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.event.EventPriority;
@ -43,7 +48,7 @@ import java.util.logging.Level;
import java.util.regex.Pattern;
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 {
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 boolean removeEffectsOnHeal;
private Map<String, String> worldAliases;
private Tag primaryColor = Tag.styling(NamedTextColor.GOLD);
private Tag secondaryColor = Tag.styling(NamedTextColor.RED);
public Settings(final IEssentials ess) {
this.ess = ess;
@ -779,6 +786,8 @@ public class Settings implements net.ess3.api.ISettings {
bindingItemPolicy = _getBindingItemsPolicy();
currencySymbol = _getCurrencySymbol();
worldAliases = _getWorldAliases();
primaryColor = _getPrimaryColor();
secondaryColor = _getSecondaryColor();
reloadCount.incrementAndGet();
}
@ -809,7 +818,7 @@ public class Settings implements net.ess3.api.ISettings {
final ItemStack iStack = itemDb.get(itemName);
epItemSpwn.add(iStack.getType());
} catch (final Exception ex) {
ess.getLogger().log(Level.SEVERE, tl("unknownItemInList", itemName, "item-spawn-blacklist"), ex);
ess.getLogger().log(Level.SEVERE, tlLiteral("unknownItemInList", itemName, "item-spawn-blacklist"), ex);
}
}
return epItemSpwn;
@ -837,7 +846,7 @@ public class Settings implements net.ess3.api.ISettings {
try {
newSigns.add(Signs.valueOf(signName).getSign());
} catch (final Exception ex) {
ess.getLogger().log(Level.SEVERE, tl("unknownItemInList", signName, "enabledSigns"));
ess.getLogger().log(Level.SEVERE, tlLiteral("unknownItemInList", signName, "enabledSigns"));
continue;
}
signsEnabled = true;
@ -883,6 +892,11 @@ public class Settings implements net.ess3.api.ISettings {
return config.getString("locale", "");
}
@Override
public boolean isPerPlayerLocale() {
return config.getBoolean("per-player-locale", false);
}
private String currencySymbol = "$";
// 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) {
ess.getLogger().log(Level.SEVERE, tl("unknownItemInList", itemName, configName));
ess.getLogger().log(Level.SEVERE, tlLiteral("unknownItemInList", itemName, configName));
} else {
list.add(mat);
}
@ -1699,7 +1713,7 @@ public class Settings implements net.ess3.api.ISettings {
try {
newSigns.add(Signs.valueOf(signName).getSign());
} catch (final Exception ex) {
ess.getLogger().log(Level.SEVERE, tl("unknownItemInList", signName, "unprotected-sign-names"));
ess.getLogger().log(Level.SEVERE, tlLiteral("unknownItemInList", signName, "unprotected-sign-names"));
}
}
return newSigns;
@ -1948,4 +1962,42 @@ public class Settings implements net.ess3.api.ISettings {
public int getMaxItemLore() {
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.VersionUtil;
import net.ess3.api.IEssentials;
import net.ess3.api.TranslatableException;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Server;
@ -27,8 +28,6 @@ import java.util.List;
import java.util.Locale;
import java.util.Set;
import static com.earth2me.essentials.I18n.tl;
public final class SpawnMob {
private static final Material GOLDEN_HELMET = EnumUtil.getMaterial("GOLDEN_HELMET", "GOLD_HELMET");
@ -49,7 +48,7 @@ public final class SpawnMob {
}
}
if (availableList.isEmpty()) {
availableList.add(tl("none"));
availableList.add(user.playerTl("none"));
}
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 {
final Block block = LocationUtil.getTarget(user.getBase()).getBlock();
if (block == null) {
throw new Exception(tl("unableToSpawnMob"));
throw new TranslatableException("unableToSpawnMob");
}
spawnmob(ess, server, user.getSource(), user, block.getLocation(), parts, data, mobCount);
}
@ -122,7 +121,7 @@ public final class SpawnMob {
if (mobCount > effectiveLimit) {
mobCount = effectiveLimit;
sender.sendMessage(tl("mobSpawnLimit"));
sender.sendTl("mobSpawnLimit");
}
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++) {
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) {
throw new Exception(tl("unableToSpawnMob"), e1);
throw new TranslatableException(e1, "unableToSpawnMob");
} catch (final NumberFormatException e2) {
throw new Exception(tl("numberRequired"), e2);
throw new TranslatableException(e2, "numberRequired");
} 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 {
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))) {
throw new Exception(tl("disabledToSpawnMob"));
throw new TranslatableException("disabledToSpawnMob");
}
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;
if (data.isEmpty()) {
sender.sendMessage(tl("mobDataList", StringUtil.joinList(MobData.getValidHelp(spawned))));
sender.sendTl("mobDataList", StringUtil.joinList(MobData.getValidHelp(spawned)));
}
if (spawned instanceof Zombie) {

View File

@ -6,6 +6,7 @@ import io.papermc.lib.PaperLib;
import net.ess3.api.IEssentials;
import net.ess3.api.ITeleport;
import net.ess3.api.IUser;
import net.ess3.api.TranslatableException;
import net.ess3.api.events.UserWarpEvent;
import net.ess3.api.events.teleport.PreTeleportEvent;
import net.ess3.api.events.teleport.TeleportWarmupEvent;
@ -19,8 +20,6 @@ import java.math.BigDecimal;
import java.util.Calendar;
import java.util.GregorianCalendar;
import static com.earth2me.essentials.I18n.tl;
/**
* @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.add(Calendar.SECOND, (int) cooldown);
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
@ -98,7 +97,7 @@ public class Teleport implements ITeleport {
final Calendar c = new GregorianCalendar();
c.add(Calendar.SECOND, (int) delay);
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.
@ -120,7 +119,7 @@ public class Teleport implements ITeleport {
}
final ITarget target = new PlayerTarget(entity);
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
@ -140,7 +139,7 @@ public class Teleport implements ITeleport {
if (!teleportee.getBase().isEmpty()) {
if (!ess.getSettings().isTeleportPassengerDismount()) {
throw new Exception(tl("passengerTeleportFail"));
throw new TranslatableException("passengerTeleportFail");
}
teleportee.getBase().eject();
}
@ -153,7 +152,7 @@ public class Teleport implements ITeleport {
PaperLib.teleportAsync(teleportee.getBase(), LocationUtil.getSafeDestination(ess, teleportee, loc), cause);
}
} 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 {
if (ess.getSettings().isForceDisableTeleportSafety()) {
@ -186,7 +185,7 @@ public class Teleport implements ITeleport {
@Deprecated
public void teleport(final Player entity, final Trade chargeFor, final TeleportCause cause) throws Exception {
final ITarget target = new PlayerTarget(entity);
teleportOwner.sendMessage(tl("teleportToPlayer", entity.getDisplayName()));
teleportOwner.sendTl("teleportToPlayer", entity.getDisplayName());
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 {
final ITarget target = new PlayerTarget(entity);
teleport(teleportee, target, chargeFor, cause);
teleportee.sendMessage(tl("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()));
teleportee.sendTl("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
@ -345,9 +344,9 @@ public class Teleport implements ITeleport {
warp = event.getWarp();
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)) {
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);
}
@ -365,7 +364,7 @@ public class Teleport implements ITeleport {
public void back(final IUser teleporter, final Trade chargeFor) throws Exception {
tpType = TeleportType.BACK;
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);
}

View File

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

View File

@ -23,8 +23,6 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tl;
public class Trade {
private static FileWriter fw = null;
private final transient String command;
@ -193,23 +191,23 @@ public class Trade {
}
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;
}
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;
}
final BigDecimal 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;
}
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());
}
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;
}
user.takeMoney(getMoney());
@ -297,7 +295,7 @@ public class Trade {
ess.getLogger().log(Level.INFO, "charging user " + user.getName() + " itemstack " + getItemStack().toString());
}
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;
}
Inventories.removeItemAmount(user.getBase(), getItemStack(), getItemStack().getAmount());
@ -306,7 +304,7 @@ public class Trade {
if (command != null) {
final BigDecimal cost = getCommandCost(user);
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;
}
user.takeMoney(cost);
@ -317,7 +315,7 @@ public class Trade {
}
final int experience = SetExpFix.getTotalExperience(user.getBase());
if (experience < getExperience() && getExperience() > 0) {
future.completeExceptionally(new ChargeException(tl("notEnoughExperience")));
future.completeExceptionally(new ChargeException(user.playerTl("notEnoughExperience")));
return;
}
SetExpFix.setTotalExperience(user.getBase(), experience - getExperience());

View File

@ -6,6 +6,8 @@ import com.earth2me.essentials.economy.EconomyLayer;
import com.earth2me.essentials.economy.EconomyLayers;
import com.earth2me.essentials.messaging.IMessageRecipient;
import com.earth2me.essentials.messaging.SimpleMessageRecipient;
import com.earth2me.essentials.utils.AdventureUtil;
import com.earth2me.essentials.utils.CommonPlaceholders;
import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.FormatUtil;
@ -14,6 +16,7 @@ import com.earth2me.essentials.utils.TriState;
import com.earth2me.essentials.utils.VersionUtil;
import com.google.common.collect.Lists;
import net.ess3.api.IEssentials;
import net.ess3.api.IUser;
import net.ess3.api.MaxMoneyException;
import net.ess3.api.events.AfkStatusChangeEvent;
import net.ess3.api.events.JailStatusChangeEvent;
@ -21,6 +24,8 @@ import net.ess3.api.events.MuteStatusChangeEvent;
import net.ess3.api.events.UserBalanceUpdateEvent;
import net.essentialsx.api.v2.events.TransactionEvent;
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.Material;
import org.bukkit.Statistic;
@ -49,7 +54,8 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
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 {
private static final Statistic PLAY_ONE_TICK = EnumUtil.getStatistic("PLAY_ONE_MINUTE", "PLAY_ONE_TICK");
@ -57,10 +63,13 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
// User modules
private final IMessageRecipient messageRecipient;
private transient final AsyncTeleport teleport;
@SuppressWarnings("deprecation")
private transient final Teleport legacyTeleport;
// User command confirmation strings
private final Map<User, BigDecimal> confirmingPayments = new WeakHashMap<>();
private String confirmingClearCommand;
private String lastHomeConfirmation;
// User teleport variables
private final transient LinkedHashMap<String, TpaRequest> teleportRequestQueue = new LinkedHashMap<>();
@ -74,29 +83,32 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
private boolean recipeSee = false;
private boolean enderSee = false;
private boolean ignoreMsg = false;
private Boolean toggleShout;
private boolean freeze = false;
// User afk variables
private String afkMessage;
private long afkSince;
private transient Location afkPosition = null;
// Misc
// Timestamps
private transient long lastOnlineActivity;
private transient long lastThrottledAction;
private transient long lastActivity = System.currentTimeMillis();
private transient long teleportInvulnerabilityTimestamp = 0;
private String confirmingClearCommand;
private long lastNotifiedAboutMailsMs;
private String lastHomeConfirmation;
private long lastHomeConfirmationTimestamp;
private Boolean toggleShout;
private boolean freeze = false;
// Misc
private transient final List<String> signCopy = Lists.newArrayList("", "", "", "");
private transient long lastVanishTime = System.currentTimeMillis();
private String lastLocaleString;
private Locale playerLocale;
public User(final Player base, final IEssentials ess) {
super(base, ess);
teleport = new AsyncTeleport(this, ess);
//noinspection deprecation
legacyTeleport = new Teleport(this, ess);
if (isAfk()) {
afkPosition = this.getLocation();
@ -215,7 +227,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
cooldownTime.add(Calendar.SECOND, (int) cooldown);
cooldownTime.add(Calendar.MILLISECOND, (int) ((cooldown * 1000.0) % 1000.0));
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());
@ -236,9 +248,9 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
return;
}
setMoney(getMoney().add(value), cause);
sendMessage(tl("addedToAccount", NumberUtil.displayCurrency(value, ess)));
sendTl("addedToAccount", NumberUtil.displayCurrency(value, ess));
if (initiator != null) {
initiator.sendMessage(tl("addedToOthersAccount", NumberUtil.displayCurrency(value, ess), this.getDisplayName(), NumberUtil.displayCurrency(getMoney(), ess)));
initiator.sendTl("addedToOthersAccount", NumberUtil.displayCurrency(value, ess), CommonPlaceholders.displayName((IUser) this), NumberUtil.displayCurrency(getMoney(), ess));
}
}
@ -249,18 +261,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 {
if (value.compareTo(BigDecimal.ZERO) < 1) {
throw new Exception(tl("payMustBePositive"));
throw new Exception(tlLocale(playerLocale, "payMustBePositive"));
}
if (canAfford(value)) {
setMoney(getMoney().subtract(value), cause);
reciever.setMoney(reciever.getMoney().add(value), cause);
sendMessage(tl("moneySentTo", NumberUtil.displayCurrency(value, ess), reciever.getDisplayName()));
reciever.sendMessage(tl("moneyRecievedFrom", NumberUtil.displayCurrency(value, ess), getDisplayName()));
sendTl("moneySentTo", NumberUtil.displayCurrency(value, ess), CommonPlaceholders.displayName((IUser) reciever));
reciever.sendTl("moneyRecievedFrom", NumberUtil.displayCurrency(value, ess), CommonPlaceholders.displayName((IUser) this));
final TransactionEvent transactionEvent = new TransactionEvent(this.getSource(), reciever, value);
ess.getServer().getPluginManager().callEvent(transactionEvent);
} else {
throw new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(value, ess)));
throw new ChargeException(tlLocale(playerLocale, "notEnoughMoney", NumberUtil.displayCurrency(value, ess)));
}
}
@ -283,9 +295,9 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
} 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);
}
sendMessage(tl("takenFromAccount", NumberUtil.displayCurrency(value, ess)));
sendTl("takenFromAccount", NumberUtil.displayCurrency(value, ess));
if (initiator != null) {
initiator.sendMessage(tl("takenFromOthersAccount", NumberUtil.displayCurrency(value, ess), this.getDisplayName(), NumberUtil.displayCurrency(getMoney(), ess)));
initiator.sendTl("takenFromOthersAccount", NumberUtil.displayCurrency(value, ess), CommonPlaceholders.displayName((IUser) this), NumberUtil.displayCurrency(getMoney(), ess));
}
}
@ -325,8 +337,9 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
return true;
if (VersionUtil.PRE_FLATTENING) {
//noinspection deprecation
final int id = material.getId();
if (isAuthorized("essentials.itemspawn.item-" + id)) return true;
return isAuthorized("essentials.itemspawn.item-" + id);
}
return false;
@ -363,6 +376,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
teleportRequestQueue.put(request.getName(), request);
}
@SuppressWarnings("deprecation")
@Override
@Deprecated
public boolean hasOutstandingTeleportRequest() {
@ -395,7 +409,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
}
teleportRequestQueue.remove(playerUsername);
if (inform) {
sendMessage(tl("requestTimedOutFrom", ess.getUser(request.getRequesterUuid()).getDisplayName()));
sendTl("requestTimedOutFrom", CommonPlaceholders.displayName((IUser) ess.getUser(request.getRequesterUuid())));
}
return null;
}
@ -429,7 +443,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
}
} else {
if (inform) {
sendMessage(tl("requestTimedOutFrom", ess.getUser(request.getRequesterUuid()).getDisplayName()));
sendTl("requestTimedOutFrom", CommonPlaceholders.displayName((IUser) ess.getUser(request.getRequesterUuid())));
}
teleportRequestQueue.remove(key);
}
@ -444,14 +458,15 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
/**
* Needed for backwards compatibility.
*/
public String getNick(final boolean longnick) {
public String getNick(@SuppressWarnings("unused") final boolean longNick) {
return getNick(true, true);
}
/**
* 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);
}
@ -533,6 +548,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
@Override
public String getDisplayName() {
//noinspection ConstantConditions
return super.getBase().getDisplayName() == null || (ess.getSettings().hideDisplayNameInVanish() && isHidden()) ? super.getBase().getName() : super.getBase().getDisplayName();
}
@ -553,6 +569,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
/**
* @deprecated This API is not asynchronous. Use {@link User#getAsyncTeleport()}
*/
@SuppressWarnings("deprecation")
@Override
@Deprecated
public Teleport getTeleport() {
@ -629,6 +646,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
}
}
@SuppressWarnings("deprecation")
@Override
public void setAfk(final boolean set) {
setAfk(set, AfkStatusChangeEvent.Cause.UNKNOWN);
@ -722,6 +740,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
}
//Returns true if status expired during this check
@SuppressWarnings("UnusedReturnValue")
public boolean checkJailTimeout(final long currentTime) {
if (getJailTimeout() > 0) {
@ -739,7 +758,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
setJailTimeout(0);
setOnlineJailedTime(0);
setJailed(false);
sendMessage(tl("haveBeenReleased"));
sendTl("haveBeenReleased");
setJail(null);
if (ess.getSettings().getTeleportWhenFreePolicy() == ISettings.TeleportWhenFreePolicy.BACK) {
final CompletableFuture<Boolean> future = new CompletableFuture<>();
@ -759,6 +778,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
}
//Returns true if status expired during this check
@SuppressWarnings("UnusedReturnValue")
public boolean checkMuteTimeout(final long currentTime) {
if (getMuteTimeout() > 0 && getMuteTimeout() < currentTime && isMuted()) {
final MuteStatusChangeEvent event = new MuteStatusChangeEvent(this, null, false, getMuteTimeout(), getMuteReason());
@ -766,7 +786,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
if (!event.isCancelled()) {
setMuteTimeout(0);
sendMessage(tl("canTalkAgain"));
sendTl("canTalkAgain");
setMuted(false);
setMuteReason(null);
return true;
@ -785,15 +805,10 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
setAfk(false, cause);
if (broadcast && !isHidden() && !isAfk()) {
setDisplayNick();
final String msg = tl("userIsNotAway", getDisplayName());
final String selfmsg = tl("userIsNotAwaySelf", 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);
if (ess.getSettings().broadcastAfkMessage()) {
ess.broadcastTl(this, u -> u == this, "userIsNotAway", CommonPlaceholders.displayName((IUser) this));
}
sendTl("userIsNotAwaySelf", CommonPlaceholders.displayName((IUser) this));
}
}
lastActivity = System.currentTimeMillis();
@ -814,9 +829,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
public void updateActivityOnChat(final boolean broadcast) {
if (ess.getSettings().cancelAfkOnChat()) {
//Chat happens async, make sure we have a sync context
ess.scheduleSyncDelayedTask(() -> {
updateActivity(broadcast, AfkStatusChangeEvent.Cause.CHAT);
});
ess.scheduleSyncDelayedTask(() -> updateActivity(broadcast, AfkStatusChangeEvent.Cause.CHAT));
}
}
@ -831,13 +844,14 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
&& lastActivity > 0 && (lastActivity + (autoafkkick * 1000)) < System.currentTimeMillis()
&& !isAuthorized("essentials.kick.exempt")
&& !isAuthorized("essentials.afk.kickexempt")) {
final String kickReason = tl("autoAfkKickReason", autoafkkick / 60.0);
lastActivity = 0;
this.getBase().kickPlayer(kickReason);
final double kickTime = autoafkkick / 60.0;
this.getBase().kickPlayer(playerTl("autoAfkKickReason", kickTime));
for (final User user : ess.getOnlineUsers()) {
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 +860,10 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
setAfk(true, AfkStatusChangeEvent.Cause.ACTIVITY);
if (isAfk() && !isHidden()) {
setDisplayNick();
final String msg = tl("userIsAway", getDisplayName());
final String selfmsg = tl("userIsAwaySelf", 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);
if (ess.getSettings().broadcastAfkMessage()) {
ess.broadcastTl(this, u -> u == this, "userIsAway", CommonPlaceholders.displayName((IUser) this));
}
sendTl("userIsAwaySelf", CommonPlaceholders.displayName((IUser) this));
}
}
}
@ -869,6 +878,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,
// 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()).
//noinspection ConstantConditions
if (!ess.getSettings().getNoGodWorlds().contains(this.getLocation().getWorld().getName())) {
return true;
}
@ -910,6 +920,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
return ess.getPermissionsHandler().canBuild(base, getGroup());
}
@SuppressWarnings("deprecation")
@Override
@Deprecated
public long getTeleportRequestTime() {
@ -978,6 +989,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
if (set) {
for (final User user : ess.getOnlineUsers()) {
if (!user.isAuthorized("essentials.vanish.see")) {
//noinspection deprecation
user.getBase().hidePlayer(getBase());
}
}
@ -993,6 +1005,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
}
} else {
for (final Player p : ess.getOnlinePlayers()) {
//noinspection deprecation
p.showPlayer(getBase());
}
setHidden(false);
@ -1052,6 +1065,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
public int compareTo(final User other) {
return FormatUtil.stripFormat(getDisplayName()).compareToIgnoreCase(FormatUtil.stripFormat(other.getDisplayName()));
@ -1073,7 +1128,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
@Override
public CommandSource getSource() {
return new CommandSource(getBase());
return new CommandSource(ess, getBase());
}
@Override
@ -1158,6 +1213,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
ess.getMail().sendMail(this, sender, message, expireAt);
}
@SuppressWarnings("deprecation")
@Override
@Deprecated
public void addMail(String mail) {
@ -1169,7 +1225,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
if (unread != 0) {
final int notifyPlayerOfMailCooldown = ess.getSettings().getNotifyPlayerOfMailCooldown() * 1000;
if (System.currentTimeMillis() - lastNotifiedAboutMailsMs >= notifyPlayerOfMailCooldown) {
sendMessage(tl("youHaveNewMail", unread));
sendTl("youHaveNewMail", unread);
lastNotifiedAboutMailsMs = System.currentTimeMillis();
}
}

View File

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

View File

@ -5,6 +5,7 @@ import com.earth2me.essentials.config.EssentialsConfiguration;
import com.earth2me.essentials.utils.StringUtil;
import net.ess3.api.InvalidNameException;
import net.ess3.api.InvalidWorldException;
import net.ess3.api.TranslatableException;
import org.bukkit.Location;
import java.io.File;
@ -17,7 +18,7 @@ import java.util.Map;
import java.util.UUID;
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 {
private final Map<StringIgnoreCase, EssentialsConfiguration> warpPoints = new HashMap<>();
@ -77,7 +78,7 @@ public class Warps implements IConf, net.ess3.api.IWarps {
if (conf == null) {
final File confFile = new File(warpsFolder, filename + ".yml");
if (confFile.exists()) {
throw new Exception(tl("similarWarpExist"));
throw new Exception(user == null ? tlLiteral("similarWarpExist") : user.playerTl("similarWarpExist"));
}
conf = new EssentialsConfiguration(confFile);
conf.load();
@ -109,10 +110,10 @@ public class Warps implements IConf, net.ess3.api.IWarps {
public void removeWarp(final String name) throws Exception {
final EssentialsConfiguration conf = warpPoints.get(new StringIgnoreCase(name));
if (conf == null) {
throw new Exception(tl("warpNotExist"));
throw new TranslatableException("warpNotExist");
}
if (!conf.getFile().delete()) {
throw new Exception(tl("warpDeleteError"));
throw new TranslatableException("warpDeleteError");
}
warpPoints.remove(new StringIgnoreCase(name));
}
@ -133,7 +134,7 @@ public class Warps implements IConf, net.ess3.api.IWarps {
warpPoints.put(new StringIgnoreCase(name), conf);
}
} catch (final Exception ex) {
Essentials.getWrappedLogger().log(Level.WARNING, tl("loadWarpError", filename), ex);
Essentials.getWrappedLogger().log(Level.WARNING, 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.craftbukkit.Inventories;
import com.earth2me.essentials.utils.VersionUtil;
import net.ess3.api.TranslatableException;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.spongepowered.configurate.CommentedConfigurationNode;
@ -13,8 +14,6 @@ import java.io.File;
import java.math.BigDecimal;
import java.util.Locale;
import static com.earth2me.essentials.I18n.tl;
public class Worth implements IConf {
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 {
if (is == null || is.getType() == Material.AIR) {
throw new Exception(tl("itemSellAir"));
throw new TranslatableException("itemSellAir");
}
int amount = 0;
@ -98,7 +97,7 @@ public class Worth implements IConf {
final boolean requireStack = ess.getSettings().isTradeInStacks(is.getType());
if (requireStack && !stack) {
throw new Exception(tl("itemMustBeStacked"));
throw new TranslatableException("itemMustBeStacked");
}
int max = 0;
@ -121,9 +120,9 @@ public class Worth implements IConf {
}
if (amount > max || amount < 1) {
if (!isBulkSell) {
user.sendMessage(tl("itemNotEnough2"));
user.sendMessage(tl("itemNotEnough3"));
throw new Exception(tl("itemNotEnough1"));
user.sendTl("itemNotEnough2");
user.sendTl("itemNotEnough3");
throw new TranslatableException("itemNotEnough1");
} else {
return amount;
}

View File

@ -1,16 +1,16 @@
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
public class InvalidWorldException extends Exception {
public class InvalidWorldException extends TranslatableException {
private final String world;
public InvalidWorldException(final String world) {
super(tl("invalidWorld"));
super("invalidWorld");
this.world = world;
}

View File

@ -1,18 +1,18 @@
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.
*/
public class UserDoesNotExistException extends Exception {
public class UserDoesNotExistException extends TranslatableException {
public UserDoesNotExistException(final String name) {
super(tl("userDoesNotExist", name));
super("userDoesNotExist", name);
}
public UserDoesNotExistException(final UUID uuid) {
super(tl("uuidDoesNotExist", uuid.toString()));
super("uuidDoesNotExist", uuid.toString());
}
}

View File

@ -2,15 +2,16 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.CommonPlaceholders;
import com.earth2me.essentials.utils.DateUtil;
import net.ess3.api.IUser;
import net.ess3.api.TranslatableException;
import net.ess3.api.events.AfkStatusChangeEvent;
import org.bukkit.Server;
import java.util.Collections;
import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandafk extends EssentialsCommand {
public Commandafk() {
super("afk");
@ -50,17 +51,23 @@ public class Commandafk extends EssentialsCommand {
if (sender.isMuted()) {
final String dateDiff = sender.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(sender.getMuteTimeout()) : 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")) {
throw new Exception(tl("noPermToAFKMessage"));
throw new TranslatableException("noPermToAFKMessage");
}
}
user.setDisplayNick();
String msg = "";
String selfmsg = "";
final boolean currentStatus = user.isAfk();
final boolean afterStatus = user.toggleAfk(AfkStatusChangeEvent.Cause.COMMAND);
@ -68,37 +75,39 @@ public class Commandafk extends EssentialsCommand {
return;
}
String tlKey = "";
String selfTlKey = "";
if (!afterStatus) {
if (!user.isHidden()) {
msg = tl("userIsNotAway", user.getDisplayName());
selfmsg = tl("userIsNotAwaySelf", user.getDisplayName());
tlKey = "userIsNotAway";
selfTlKey = "userIsNotAwaySelf";
}
user.updateActivity(false, AfkStatusChangeEvent.Cause.COMMAND);
} else {
if (!user.isHidden()) {
if (message != null) {
msg = tl("userIsAwayWithMessage", user.getDisplayName(), message);
selfmsg = tl("userIsAwaySelfWithMessage", user.getDisplayName(), message);
tlKey = "userIsAwayWithMessage";
selfTlKey = "userIsAwaySelfWithMessage";
} else {
msg = tl("userIsAway", user.getDisplayName());
selfmsg = tl("userIsAwaySelf", user.getDisplayName());
tlKey = "userIsAway";
selfTlKey = "userIsAwaySelf";
}
}
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
ess.broadcastMessage(user, msg, u -> u == user);
ess.broadcastTl(user, u -> u == user, tlKey, CommonPlaceholders.displayName((IUser) user), message);
}
if (!selfmsg.isEmpty()) {
user.sendMessage(selfmsg);
if (!selfTlKey.isEmpty()) {
user.sendTl(selfTlKey, CommonPlaceholders.displayName((IUser) user), message);
}
user.setDisplayNick(); // Set this again after toggling
}
@Override
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);
} else {
return Collections.emptyList();

View File

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

View File

@ -3,13 +3,12 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User;
import net.ess3.api.TranslatableException;
import org.bukkit.Server;
import java.util.Collections;
import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandback extends EssentialsCommand {
public Commandback() {
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 {
final User player = getPlayer(server, args, 0, true, false);
sender.sendMessage(tl("backOther", player.getName()));
sender.sendTl("backOther", player.getName());
teleportBack(sender, player, commandLabel);
}
private void teleportBack(final CommandSource sender, final User user, final String commandLabel) throws Exception {
if (user.getLastLocation() == null) {
throw new Exception(tl("noLocationFound"));
throw new TranslatableException("noLocationFound");
}
final String lastWorldName = user.getLastLocation().getWorld().getName();
@ -53,11 +52,11 @@ public class Commandback extends EssentialsCommand {
requester = ess.getUser(sender.getPlayer());
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)) {
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.CommandSource;
import net.ess3.api.TranslatableException;
import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandbackup extends EssentialsCommand {
public Commandbackup() {
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 {
final Backup backup = ess.getBackup();
if (backup == null) {
throw new Exception(tl("backupDisabled"));
throw new TranslatableException("backupDisabled");
}
final String command = ess.getSettings().getBackupCommand();
if (command == null || "".equals(command) || "save-all".equalsIgnoreCase(command)) {
throw new Exception(tl("backupDisabled"));
throw new TranslatableException("backupDisabled");
}
backup.run();
sender.sendMessage(tl("backupStarted"));
sender.sendTl("backupStarted");
}
}

View File

@ -2,14 +2,14 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.CommonPlaceholders;
import com.earth2me.essentials.utils.NumberUtil;
import net.ess3.api.IUser;
import org.bukkit.Server;
import java.util.Collections;
import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandbalance extends EssentialsCommand {
public Commandbalance() {
super("balance");
@ -22,16 +22,16 @@ public class Commandbalance extends EssentialsCommand {
}
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() : CommonPlaceholders.displayName((IUser) target), NumberUtil.displayCurrency(target.getMoney(), ess));
}
@Override
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")) {
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() : CommonPlaceholders.displayName((IUser) target), NumberUtil.displayCurrency(target.getMoney(), ess));
} else if (args.length < 2) {
user.sendMessage(tl("balance", NumberUtil.displayCurrency(user.getMoney(), ess)));
user.sendTl("balance", NumberUtil.displayCurrency(user.getMoney(), ess));
} else {
throw new NotEnoughArgumentsException();
}
@ -39,7 +39,7 @@ public class Commandbalance extends EssentialsCommand {
@Override
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);
} else {
return Collections.emptyList();

View File

@ -3,6 +3,7 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.textreader.SimpleTextInput;
import com.earth2me.essentials.textreader.TextPager;
import com.earth2me.essentials.utils.AdventureUtil;
import com.earth2me.essentials.utils.NumberUtil;
import com.google.common.collect.Lists;
import net.essentialsx.api.v2.services.BalanceTop;
@ -18,7 +19,7 @@ import java.util.Map;
import java.util.UUID;
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 static final int MINUSERS = 50;
@ -34,7 +35,7 @@ public class Commandbalancetop extends EssentialsCommand {
cal.setTimeInMillis(ess.getBalanceTop().getCacheAge());
final DateFormat format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
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);
};
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 (ess.getUsers().getUserCount() > MINUSERS) {
sender.sendMessage(tl("orderBalances", ess.getUsers().getUserCount()));
sender.sendTl("orderBalances", ess.getUsers().getUserCount());
}
ess.runTaskAsynchronously(new Viewer(sender, page, force));
@ -109,11 +110,11 @@ public class Commandbalancetop extends EssentialsCommand {
future.thenRun(() -> {
if (fresh) {
final SimpleTextInput newCache = new SimpleTextInput();
newCache.getLines().add(tl("serverTotal", NumberUtil.displayCurrency(ess.getBalanceTop().getBalanceTopTotal(), ess)));
newCache.getLines().add(tlLiteral("serverTotal", NumberUtil.displayCurrency(ess.getBalanceTop().getBalanceTopTotal(), ess)));
int pos = 1;
for (final Map.Entry<UUID, BalanceTop.Entry> entry : ess.getBalanceTop().getBalanceTopCache().entrySet()) {
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(tlLiteral("balanceTopLine", pos, AdventureUtil.parsed(AdventureUtil.legacyToMini(entry.getValue().getDisplayName())), NumberUtil.displayCurrency(entry.getValue().getBalance(), ess)));
}
pos++;
}

View File

@ -5,6 +5,7 @@ import com.earth2me.essentials.Console;
import com.earth2me.essentials.OfflinePlayerStub;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.FormatUtil;
import net.ess3.api.TranslatableException;
import org.bukkit.BanList;
import org.bukkit.Server;
@ -12,7 +13,7 @@ import java.util.Collections;
import java.util.List;
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 Commandban() {
@ -34,10 +35,10 @@ public class Commandban extends EssentialsCommand {
}
if (!user.getBase().isOnline()) {
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()) {
throw new Exception(tl("banExempt"));
throw new TranslatableException("banExempt");
}
final String senderName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.NAME;
@ -46,21 +47,21 @@ public class Commandban extends EssentialsCommand {
if (args.length > 1) {
banReason = FormatUtil.replaceFormat(getFinalArg(args, 1).replace("\\n", "\n").replace("|", "\n"));
} else {
banReason = tl("defaultBanReason");
banReason = tlLiteral("defaultBanReason");
}
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);
ess.getLogger().log(Level.INFO, tl("playerBanned", senderDisplayName, user.getName(), banDisplay));
ess.getLogger().log(Level.INFO, tlLiteral("playerBanned", senderDisplayName, user.getName(), banDisplay));
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

View File

@ -12,7 +12,7 @@ import java.util.Collections;
import java.util.List;
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 Commandbanip() {
@ -48,13 +48,13 @@ public class Commandbanip extends EssentialsCommand {
if (args.length > 1) {
banReason = FormatUtil.replaceFormat(getFinalArg(args, 1).replace("\\n", "\n").replace("|", "\n"));
} else {
banReason = tl("defaultBanReason");
banReason = tlLiteral("defaultBanReason");
}
final String banDisplay = tl("banFormat", banReason, senderDisplayName);
final String banDisplay = tlLiteral("banFormat", banReason, senderDisplayName);
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, tlLiteral("playerBanIpAddress", senderDisplayName, ipAddress, banReason));
for (final Player player : ess.getServer().getOnlinePlayers()) {
if (player.getAddress().getAddress().getHostAddress().equalsIgnoreCase(ipAddress)) {
@ -62,7 +62,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

View File

@ -7,8 +7,6 @@ import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.entity.Entity;
import static com.earth2me.essentials.I18n.tl;
public class Commandbeezooka extends EssentialsCommand {
public Commandbeezooka() {
@ -18,7 +16,7 @@ public class Commandbeezooka extends EssentialsCommand {
@Override
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)) {
user.sendMessage(tl("unsupportedFeature"));
user.sendTl("unsupportedFeature");
return;
}

View File

@ -3,6 +3,7 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.LocationUtil;
import com.google.common.collect.Lists;
import net.ess3.api.TranslatableException;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.TreeType;
@ -10,8 +11,6 @@ import org.bukkit.TreeType;
import java.util.Collections;
import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandbigtree extends EssentialsCommand {
public Commandbigtree() {
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);
if (loc.getBlock().getType().isSolid()) {
throw new Exception(tl("bigTreeFailure"));
throw new TranslatableException("bigTreeFailure");
}
final boolean success = user.getWorld().generateTree(loc, tree);
if (success) {
user.sendMessage(tl("bigTreeSuccess"));
user.sendTl("bigTreeSuccess");
} else {
throw new Exception(tl("bigTreeFailure"));
throw new TranslatableException("bigTreeFailure");
}
}

View File

@ -1,10 +1,11 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.FormatUtil;
import com.earth2me.essentials.craftbukkit.Inventories;
import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.FormatUtil;
import com.google.common.collect.Lists;
import net.ess3.api.TranslatableException;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.inventory.ItemStack;
@ -13,8 +14,6 @@ import org.bukkit.inventory.meta.BookMeta;
import java.util.Collections;
import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandbook extends EssentialsCommand {
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();
bmeta.setAuthor(newAuthor);
item.setItemMeta(bmeta);
user.sendMessage(tl("bookAuthorSet", newAuthor));
user.sendTl("bookAuthorSet", newAuthor);
} else {
throw new Exception(tl("denyChangeAuthor"));
throw new TranslatableException("denyChangeAuthor");
}
} else if (args.length > 1 && args[0].equalsIgnoreCase("title")) {
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();
bmeta.setTitle(newTitle);
item.setItemMeta(bmeta);
user.sendMessage(tl("bookTitleSet", newTitle));
user.sendTl("bookTitleSet", newTitle);
} else {
throw new Exception(tl("denyChangeTitle"));
throw new TranslatableException("denyChangeTitle");
}
} else {
if (isAuthor(bmeta, player) || user.isAuthorized("essentials.book.others")) {
final ItemStack newItem = new ItemStack(WRITABLE_BOOK, item.getAmount());
newItem.setItemMeta(bmeta);
Inventories.setItemInMainHand(user.getBase(), newItem);
user.sendMessage(tl("editBookContents"));
user.sendTl("editBookContents");
} else {
throw new Exception(tl("denyBookEdit"));
throw new TranslatableException("denyBookEdit");
}
}
} 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());
newItem.setItemMeta(bmeta);
Inventories.setItemInMainHand(user.getBase(), newItem);
user.sendMessage(tl("bookLocked"));
user.sendTl("bookLocked");
} 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 static com.earth2me.essentials.I18n.tl;
public class Commandbottom extends EssentialsCommand {
public Commandbottom() {
@ -28,7 +26,7 @@ public class Commandbottom extends EssentialsCommand {
final CompletableFuture<Boolean> future = getNewExceptionFuture(user.getSource(), commandLabel);
future.thenAccept(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);

View File

@ -1,13 +1,12 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.User;
import net.ess3.api.TranslatableException;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.block.Block;
import org.bukkit.event.block.BlockBreakEvent;
import static com.earth2me.essentials.I18n.tl;
public class Commandbreak extends EssentialsCommand {
public Commandbreak() {
super("break");
@ -22,7 +21,7 @@ public class Commandbreak extends EssentialsCommand {
throw new NoChargeException();
}
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 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 org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandbroadcast extends EssentialsCommand {
public Commandbroadcast() {
super("broadcast");
@ -17,6 +15,6 @@ public class Commandbroadcast extends EssentialsCommand {
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.User;
import com.earth2me.essentials.textreader.IText;
import com.earth2me.essentials.textreader.KeywordReplacer;
import com.earth2me.essentials.textreader.SimpleTextInput;
import com.earth2me.essentials.utils.FormatUtil;
import com.earth2me.essentials.utils.AdventureUtil;
import com.google.common.collect.Lists;
import net.ess3.api.TranslatableException;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.entity.Player;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandbroadcastworld extends EssentialsCommand {
public Commandbroadcastworld() {
@ -50,7 +44,7 @@ public class Commandbroadcastworld extends EssentialsCommand {
final World world = ess.getWorld(args[0]);
if (world == null) {
throw new Exception(tl("invalidWorld"));
throw new TranslatableException("invalidWorld");
}
sendBroadcast(world, sender.getSender().getName(), getFinalArg(args, 1));
}
@ -59,22 +53,7 @@ public class Commandbroadcastworld extends EssentialsCommand {
if (message.isEmpty()) {
throw new NotEnoughArgumentsException();
}
sendToWorld(world, tl("broadcast", FormatUtil.replaceFormat(message).replace("\\n", "\n"), 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);
}
}
}
ess.broadcastTl(null, u -> u.getBase().getWorld().equals(world), true, "broadcast", message, AdventureUtil.parsed(AdventureUtil.legacyToMini(name)));
}
@Override

View File

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

View File

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

View File

@ -19,8 +19,6 @@ import java.util.List;
import java.util.Locale;
import java.util.Set;
import static com.earth2me.essentials.I18n.tl;
public class Commandclearinventory extends EssentialsCommand {
private static final int EXTENDED_CAP = 8;
@ -55,7 +53,7 @@ public class Commandclearinventory extends EssentialsCommand {
}
if (allowAll && args.length > 0 && args[0].contentEquals("*")) {
sender.sendMessage(tl("inventoryClearingFromAll"));
sender.sendTl("inventoryClearingFromAll");
offset = 1;
players = ess.getOnlinePlayers();
} 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 (!formattedCommand.equals(previousClearCommand)) {
senderUser.setConfirmingClearCommand(formattedCommand);
senderUser.sendMessage(tl("confirmClear", formattedCommand));
senderUser.sendTl("confirmClear", formattedCommand);
return;
}
}
@ -115,7 +113,7 @@ public class Commandclearinventory extends EssentialsCommand {
if (type != ClearHandlerType.SPECIFIC_ITEM) {
final boolean armor = type == ClearHandlerType.ALL_INCLUDING_ARMOR;
if (showExtended) {
sender.sendMessage(tl(armor ? "inventoryClearingAllArmor" : "inventoryClearingAllItems", player.getDisplayName()));
sender.sendTl(armor ? "inventoryClearingAllArmor" : "inventoryClearingAllItems", player.getDisplayName());
}
Inventories.removeItems(player, item -> true, armor);
} else {
@ -130,15 +128,15 @@ public class Commandclearinventory extends EssentialsCommand {
if (amount == -1) {
final int removedAmount = Inventories.removeItemSimilar(player, stack, true);
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 {
stack.setAmount(amount < 0 ? 1 : 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 {
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 org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandclearinventoryconfirmtoggle extends EssentialsCommand {
public Commandclearinventoryconfirmtoggle() {
@ -21,9 +19,9 @@ public class Commandclearinventoryconfirmtoggle extends EssentialsCommand {
}
user.setPromptingClearConfirm(confirmingClear);
if (confirmingClear) {
user.sendMessage(tl("clearInventoryConfirmToggleOn"));
user.sendTl("clearInventoryConfirmToggleOn");
} else {
user.sendMessage(tl("clearInventoryConfirmToggleOff"));
user.sendTl("clearInventoryConfirmToggleOff");
}
user.setConfirmingClearCommand(null);
}

View File

@ -3,8 +3,6 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandcompass extends EssentialsCommand {
public Commandcompass() {
super("compass");
@ -15,24 +13,24 @@ public class Commandcompass extends EssentialsCommand {
final int bearing = (int) (user.getLocation().getYaw() + 180 + 360) % 360;
final String dir;
if (bearing < 23) {
dir = tl("north");
dir = user.playerTl("north");
} else if (bearing < 68) {
dir = tl("northEast");
dir = user.playerTl("northEast");
} else if (bearing < 113) {
dir = tl("east");
dir = user.playerTl("east");
} else if (bearing < 158) {
dir = tl("southEast");
dir = user.playerTl("southEast");
} else if (bearing < 203) {
dir = tl("south");
dir = user.playerTl("south");
} else if (bearing < 248) {
dir = tl("southWest");
dir = user.playerTl("southWest");
} else if (bearing < 293) {
dir = tl("west");
dir = user.playerTl("west");
} else if (bearing < 338) {
dir = tl("northWest");
dir = user.playerTl("northWest");
} 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.Map;
import static com.earth2me.essentials.I18n.tl;
public class Commandcondense extends EssentialsCommand {
private final Map<ItemStack, SimpleRecipe> condenseList = new HashMap<>();
@ -58,9 +56,9 @@ public class Commandcondense extends EssentialsCommand {
user.getBase().updateInventory();
if (didConvert) {
user.sendMessage(tl("itemsConverted"));
user.sendTl("itemsConverted");
} else {
user.sendMessage(tl("itemsNotConverted"));
user.sendTl("itemsNotConverted");
throw new NoChargeException();
}
}

View File

@ -5,6 +5,7 @@ import com.earth2me.essentials.User;
import com.earth2me.essentials.craftbukkit.Inventories;
import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.PasteUtil;
import net.ess3.api.TranslatableException;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.inventory.ItemStack;
@ -21,7 +22,7 @@ import java.util.List;
import java.util.concurrent.CompletableFuture;
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 Commandcreatekit() {
@ -44,7 +45,7 @@ public class Commandcreatekit extends EssentialsCommand {
boolean useSerializationProvider = ess.getSettings().isUseBetterKits();
if (useSerializationProvider && ess.getSerializationProvider() == null) {
ess.showError(user.getSource(), new Exception(tl("createKitUnsupported")), commandLabel);
ess.showError(user.getSource(), new TranslatableException("createKitUnsupported"), commandLabel);
useSerializationProvider = false;
}
@ -62,7 +63,7 @@ public class Commandcreatekit extends EssentialsCommand {
// Some users might want to directly write to config knowing the consequences. *shrug*
if (!ess.getSettings().isPastebinCreateKit()) {
ess.getKits().addKit(kitname, list, delay);
user.sendMessage(tl("createdKit", kitname, list.size(), delay));
user.sendTl("createdKit", kitname, list.size(), delay);
} else {
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)));
future.thenAccept(result -> {
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));
sender.sendMessage(separator);
sender.sendMessage(tl("createKitSuccess", kitName, delayFormat, result.getPasteUrl()));
sender.sendTl("createKitSuccess", kitName, delayFormat, result.getPasteUrl());
sender.sendMessage(separator);
if (ess.getSettings().isDebug()) {
ess.getLogger().info(sender.getSender().getName() + " created a kit: " + result.getPasteUrl());
@ -97,12 +98,12 @@ public class Commandcreatekit extends EssentialsCommand {
}
});
future.exceptionally(throwable -> {
sender.sendMessage(tl("createKitFailed", kitName));
sender.sendTl("createKitFailed", kitName);
ess.getLogger().log(Level.SEVERE, "Error creating kit: ", throwable);
return null;
});
} catch (Exception e) {
sender.sendMessage(tl("createKitFailed", kitName));
sender.sendTl("createKitFailed", kitName);
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.IUser;
import com.earth2me.essentials.User;
import net.ess3.api.TranslatableException;
import net.essentialsx.api.v2.events.HomeModifyEvent;
import org.bukkit.Bukkit;
import org.bukkit.Server;
@ -12,8 +13,6 @@ import java.util.Collections;
import java.util.List;
import java.util.Locale;
import static com.earth2me.essentials.I18n.tl;
public class Commanddelhome extends EssentialsCommand {
public Commanddelhome() {
super("delhome");
@ -47,10 +46,10 @@ public class Commanddelhome extends EssentialsCommand {
}
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);
if (event.isCancelled()) {
if (ess.getSettings().isDebug()) {
@ -60,13 +59,13 @@ public class Commanddelhome extends EssentialsCommand {
}
user.delHome(name);
sender.sendMessage(tl("deleteHome", name));
sender.sendTl("deleteHome", name);
}
@Override
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
final IUser user = sender.getUser(ess);
final boolean canDelOthers = sender.isAuthorized("essentials.delhome.others", ess);
final IUser user = sender.getUser();
final boolean canDelOthers = sender.isAuthorized("essentials.delhome.others");
if (args.length == 1) {
final List<String> homes = user == null ? new ArrayList<>() : user.getHomes();
if (canDelOthers) {

View File

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

View File

@ -8,8 +8,6 @@ import org.bukkit.Server;
import java.util.Collections;
import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commanddelkit extends EssentialsCommand {
public Commanddelkit() {
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 {
if (args.length == 0) {
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();
} else {
final String kitName = ess.getKits().matchKit(args[0]);
@ -30,7 +28,7 @@ public class Commanddelkit extends EssentialsCommand {
}
ess.getKits().removeKit(kitName);
sender.sendMessage(tl("deleteKit", kitName));
sender.sendTl("deleteKit", kitName);
}
}

View File

@ -1,6 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import net.ess3.api.TranslatableException;
import net.essentialsx.api.v2.events.WarpModifyEvent;
import org.bukkit.Bukkit;
import org.bukkit.Location;
@ -10,8 +11,6 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commanddelwarp extends EssentialsCommand {
public Commanddelwarp() {
super("delwarp");
@ -31,15 +30,15 @@ public class Commanddelwarp extends EssentialsCommand {
// World is unloaded/deleted
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);
if (event.isCancelled()) {
return;
}
ess.getWarps().removeWarp(args[0]);
sender.sendMessage(tl("deleteWarp", args[0]));
sender.sendTl("deleteWarp", args[0]);
} 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 org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commanddepth extends EssentialsCommand {
public Commanddepth() {
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 {
final int depth = user.getLocation().getBlockY() - user.getWorld().getSeaLevel();
if (depth > 0) {
user.sendMessage(tl("depthAboveSea", depth));
user.sendTl("depthAboveSea", depth);
} else if (depth < 0) {
user.sendMessage(tl("depthBelowSea", -depth));
user.sendTl("depthBelowSea", -depth);
} 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 org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commanddisposal extends EssentialsCommand {
public Commanddisposal() {
@ -13,8 +11,8 @@ public class Commanddisposal extends EssentialsCommand {
@Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
user.sendMessage(tl("openingDisposal"));
user.getBase().openInventory(ess.getServer().createInventory(user.getBase(), 36, tl("disposal")));
user.sendTl("openingDisposal");
user.getBase().openInventory(ess.getServer().createInventory(user.getBase(), 36, user.playerTl("disposal")));
}
}

View File

@ -3,9 +3,12 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.ChargeException;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.CommonPlaceholders;
import com.earth2me.essentials.utils.NumberUtil;
import com.google.common.collect.Lists;
import net.ess3.api.IUser;
import net.ess3.api.MaxMoneyException;
import net.ess3.api.TranslatableException;
import net.ess3.api.events.UserBalanceUpdateEvent;
import org.bukkit.Server;
@ -14,8 +17,6 @@ import java.util.Collections;
import java.util.List;
import java.util.Locale;
import static com.earth2me.essentials.I18n.tl;
public class Commandeco extends EssentialsLoopCommand {
public Commandeco() {
@ -54,7 +55,7 @@ public class Commandeco extends EssentialsLoopCommand {
if (player.getMoney().subtract(userAmount).compareTo(ess.getSettings().getMinMoney()) >= 0) {
player.takeMoney(userAmount, sender, UserBalanceUpdateEvent.Cause.COMMAND_ECO);
} 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;
}
@ -65,8 +66,8 @@ public class Commandeco extends EssentialsLoopCommand {
final boolean underMin = userAmount.compareTo(minBal) < 0;
final boolean aboveMax = userAmount.compareTo(maxBal) > 0;
player.setMoney(underMin ? minBal : aboveMax ? maxBal : userAmount, UserBalanceUpdateEvent.Cause.COMMAND_ECO);
player.sendMessage(tl("setBal", NumberUtil.displayCurrency(player.getMoney(), ess)));
sender.sendMessage(tl("setBalOthers", player.getDisplayName(), NumberUtil.displayCurrency(player.getMoney(), ess)));
player.sendTl("setBal", NumberUtil.displayCurrency(player.getMoney(), ess));
sender.sendTl("setBalOthers", CommonPlaceholders.displayName((IUser) player), NumberUtil.displayCurrency(player.getMoney(), ess));
break;
}
}

View File

@ -5,6 +5,7 @@ import com.earth2me.essentials.utils.FormatUtil;
import com.earth2me.essentials.utils.NumberUtil;
import com.earth2me.essentials.utils.VersionUtil;
import com.google.common.collect.Lists;
import net.ess3.api.TranslatableException;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Server;
@ -23,8 +24,6 @@ import org.bukkit.util.Vector;
import java.util.Collections;
import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandeditsign extends EssentialsCommand {
public Commandeditsign() {
super("editsign");
@ -38,7 +37,7 @@ public class Commandeditsign extends EssentialsCommand {
final Block target = user.getTargetBlock(5); //5 is a good number
if (!(target.getState() instanceof Sign)) {
throw new Exception(tl("editsignCommandTarget"));
throw new TranslatableException("editsignCommandTarget");
}
final ModifiableSign sign = wrapSign((Sign) target.getState(), user);
try {
@ -47,14 +46,14 @@ public class Commandeditsign extends EssentialsCommand {
final int line = Integer.parseInt(args[1]) - 1;
final String text = FormatUtil.formatString(user, "essentials.editsign", getFinalArg(args, 2)).trim();
if (ChatColor.stripColor(text).length() > 15 && !user.isAuthorized("essentials.editsign.unlimited")) {
throw new Exception(tl("editsignCommandLimit"));
throw new TranslatableException("editsignCommandLimit");
}
existingLines[line] = text;
if (callSignEvent(sign, user.getBase(), existingLines)) {
return;
}
user.sendMessage(tl("editsignCommandSetSuccess", line + 1, text));
user.sendTl("editsignCommandSetSuccess", line + 1, text);
} else if (args[0].equalsIgnoreCase("clear")) {
if (args.length == 1) {
final String[] existingLines = sign.getLines();
@ -66,7 +65,7 @@ public class Commandeditsign extends EssentialsCommand {
return;
}
user.sendMessage(tl("editsignCommandClear"));
user.sendTl("editsignCommandClear");
} else {
final String[] existingLines = sign.getLines();
final int line = Integer.parseInt(args[1]) - 1;
@ -76,7 +75,7 @@ public class Commandeditsign extends EssentialsCommand {
return;
}
user.sendMessage(tl("editsignCommandClearLine", line + 1));
user.sendTl("editsignCommandClearLine", line + 1);
}
} else if (args[0].equalsIgnoreCase("copy")) {
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.
user.getSignCopy().set(i, FormatUtil.unformatString(user, "essentials.editsign", sign.getLine(i)));
}
user.sendMessage(tl("editsignCopy", commandLabel));
user.sendTl("editsignCopy", commandLabel);
} else {
// 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.sendMessage(tl("editsignCopyLine", line + 1, commandLabel));
user.sendTl("editsignCopyLine", line + 1, commandLabel);
}
} else if (args[0].equalsIgnoreCase("paste")) {
@ -101,10 +100,10 @@ public class Commandeditsign extends EssentialsCommand {
for (int i = 0; i < 4; i++) {
existingLines[i] = FormatUtil.formatString(user, "essentials.editsign", user.getSignCopy().get(i));
}
user.sendMessage(tl("editsignPaste", commandLabel));
user.sendTl("editsignPaste", commandLabel);
} else {
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);
@ -112,7 +111,7 @@ public class Commandeditsign extends EssentialsCommand {
throw new NotEnoughArgumentsException();
}
} 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.utils.StringUtil;
import com.google.common.collect.Lists;
import net.ess3.api.TranslatableException;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.enchantments.Enchantment;
@ -18,8 +19,6 @@ import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import static com.earth2me.essentials.I18n.tl;
public class Commandenchant extends EssentialsCommand {
public Commandenchant() {
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 {
final ItemStack stack = user.getItemInHand();
if (stack == null || stack.getType() == Material.AIR) {
throw new Exception(tl("nothingInHand"));
throw new TranslatableException("nothingInHand");
}
if (args.length == 0) {
@ -41,7 +40,7 @@ public class Commandenchant extends EssentialsCommand {
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;
@ -60,9 +59,9 @@ public class Commandenchant extends EssentialsCommand {
user.getBase().updateInventory();
final String enchantName = enchantment.getName().toLowerCase(Locale.ENGLISH).replace('_', ' ');
if (level == 0) {
user.sendMessage(tl("enchantmentRemoved", enchantName));
user.sendTl("enchantmentRemoved", enchantName);
} else {
user.sendMessage(tl("enchantmentApplied", enchantName));
user.sendTl("enchantmentApplied", enchantName);
}
}

View File

@ -8,6 +8,7 @@ import com.earth2me.essentials.economy.EconomyLayer;
import com.earth2me.essentials.economy.EconomyLayers;
import com.earth2me.essentials.userstorage.ModernUserMap;
import com.earth2me.essentials.utils.CommandMapUtil;
import com.earth2me.essentials.utils.CommonPlaceholders;
import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.FloatUtil;
@ -20,8 +21,11 @@ import com.google.gson.JsonArray;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import net.ess3.api.IUser;
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.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Server;
@ -59,7 +63,7 @@ import java.util.function.Supplier;
import java.util.logging.Level;
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
public class Commandessentials extends EssentialsCommand {
@ -177,7 +181,7 @@ public class Commandessentials extends EssentialsCommand {
}
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;
}
@ -234,11 +238,11 @@ public class Commandessentials extends EssentialsCommand {
// 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) {
if (ess.getAlternativeCommandsHandler().disabledCommands().size() == 0) {
sender.sendMessage(tl("blockListEmpty"));
sender.sendTl("blockListEmpty");
return;
}
sender.sendMessage(tl("blockList"));
sender.sendTl("blockList");
for (final Map.Entry<String, String> entry : ess.getAlternativeCommandsHandler().disabledCommands().entrySet()) {
sender.sendMessage(entry.getKey() + " => " + entry.getValue());
}
@ -246,7 +250,7 @@ public class Commandessentials extends EssentialsCommand {
// Generates a paste of useful information
private void runDump(Server server, CommandSource sender, String commandLabel, String[] args) {
sender.sendMessage(tl("dumpCreating"));
sender.sendTl("dumpCreating");
final JsonObject dump = new JsonObject();
@ -378,7 +382,7 @@ public class Commandessentials extends EssentialsCommand {
try {
files.add(new PasteUtil.PasteFile("config.yml", new String(Files.readAllBytes(ess.getSettings().getConfigFile().toPath()), StandardCharsets.UTF_8)));
} catch (IOException e) {
sender.sendMessage(tl("dumpErrorUpload", "config.yml", e.getMessage()));
sender.sendTl("dumpErrorUpload", "config.yml", e.getMessage());
}
}
@ -388,7 +392,7 @@ public class Commandessentials extends EssentialsCommand {
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>")));
} catch (IOException e) {
sender.sendMessage(tl("dumpErrorUpload", "discord-config.yml", e.getMessage()));
sender.sendTl("dumpErrorUpload", "discord-config.yml", e.getMessage());
}
if (essDiscordLink != null) {
@ -396,7 +400,7 @@ public class Commandessentials extends EssentialsCommand {
files.add(new PasteUtil.PasteFile("discord-link-config.yml",
new String(Files.readAllBytes(essDiscordLink.getDataFolder().toPath().resolve("config.yml")), StandardCharsets.UTF_8)));
} catch (IOException e) {
sender.sendMessage(tl("dumpErrorUpload", "discord-link-config.yml", e.getMessage()));
sender.sendTl("dumpErrorUpload", "discord-link-config.yml", e.getMessage());
}
}
}
@ -405,7 +409,7 @@ public class Commandessentials extends EssentialsCommand {
try {
files.add(new PasteUtil.PasteFile("kits.yml", new String(Files.readAllBytes(ess.getKits().getFile().toPath()), StandardCharsets.UTF_8)));
} catch (IOException e) {
sender.sendMessage(tl("dumpErrorUpload", "kits.yml", e.getMessage()));
sender.sendTl("dumpErrorUpload", "kits.yml", e.getMessage());
}
}
@ -415,7 +419,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("(?:[0-9]{1,3}\\.){3}[0-9]{1,3}", "<censored ip address>")));
} catch (IOException e) {
sender.sendMessage(tl("dumpErrorUpload", "latest.log", e.getMessage()));
sender.sendTl("dumpErrorUpload", "latest.log", e.getMessage());
}
}
@ -423,7 +427,7 @@ public class Commandessentials extends EssentialsCommand {
try {
files.add(new PasteUtil.PasteFile("worth.yml", new String(Files.readAllBytes(ess.getWorth().getFile().toPath()), StandardCharsets.UTF_8)));
} catch (IOException e) {
sender.sendMessage(tl("dumpErrorUpload", "worth.yml", e.getMessage()));
sender.sendTl("dumpErrorUpload", "worth.yml", e.getMessage());
}
}
@ -431,7 +435,7 @@ public class Commandessentials extends EssentialsCommand {
try {
files.add(new PasteUtil.PasteFile("tpr.yml", new String(Files.readAllBytes(ess.getRandomTeleport().getFile().toPath()), StandardCharsets.UTF_8)));
} catch (IOException e) {
sender.sendMessage(tl("dumpErrorUpload", "tpr.yml", e.getMessage()));
sender.sendTl("dumpErrorUpload", "tpr.yml", e.getMessage());
}
}
@ -439,7 +443,7 @@ public class Commandessentials extends EssentialsCommand {
try {
files.add(new PasteUtil.PasteFile("spawn.yml", new String(Files.readAllBytes(ess.getDataFolder().toPath().resolve("spawn.yml")), StandardCharsets.UTF_8)));
} catch (IOException e) {
sender.sendMessage(tl("dumpErrorUpload", "spawn.yml", e.getMessage()));
sender.sendTl("dumpErrorUpload", "spawn.yml", e.getMessage());
}
}
@ -449,7 +453,7 @@ public class Commandessentials extends EssentialsCommand {
files.add(new PasteUtil.PasteFile("commandmap.json", CommandMapUtil.toJsonPretty(ess, knownCommandsCopy)));
files.add(new PasteUtil.PasteFile("commandoverride.json", disabledCommandsCopy.toString()));
} catch (IOException e) {
sender.sendMessage(tl("dumpErrorUpload", "commands.yml", e.getMessage()));
sender.sendTl("dumpErrorUpload", "commands.yml", e.getMessage());
}
}
@ -457,17 +461,17 @@ public class Commandessentials extends EssentialsCommand {
future.thenAccept(result -> {
if (result != null) {
final String dumpUrl = "https://essentialsx.net/dump.html?id=" + result.getPasteId();
sender.sendMessage(tl("dumpUrl", dumpUrl));
sender.sendMessage(tl("dumpDeleteKey", result.getDeletionKey()));
sender.sendTl("dumpUrl", dumpUrl);
sender.sendTl("dumpDeleteKey", result.getDeletionKey());
if (sender.isPlayer()) {
ess.getLogger().info(tl("dumpConsoleUrl", dumpUrl));
ess.getLogger().info(tl("dumpDeleteKey", result.getDeletionKey()));
ess.getLogger().info(tlLiteral("dumpConsoleUrl", dumpUrl));
ess.getLogger().info(tlLiteral("dumpDeleteKey", result.getDeletionKey()));
}
}
files.clear();
});
future.exceptionally(throwable -> {
sender.sendMessage(tl("dumpError", throwable.getMessage()));
sender.sendTl("dumpError", throwable.getMessage());
return null;
});
});
@ -480,7 +484,7 @@ public class Commandessentials extends EssentialsCommand {
}
final User user = getPlayer(server, args, 1, true, true);
user.reset();
sender.sendMessage("Reset Essentials userdata for player: " + user.getDisplayName());
sender.sendMessage("Reset Essentials userdata for player: " + CommonPlaceholders.displayName((IUser) user));
}
// Toggles debug mode.
@ -492,7 +496,7 @@ public class Commandessentials extends EssentialsCommand {
// Reloads all reloadable configs.
private void runReload(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
ess.reload();
sender.sendMessage(tl("essentialsReload", ess.getDescription().getVersion()));
sender.sendTl("essentialsReload", ess.getDescription().getVersion());
}
// Pop tarts.
@ -536,10 +540,10 @@ public class Commandessentials extends EssentialsCommand {
throw new Exception("/<command> cleanup <days> [money] [homes]");
}
sender.sendMessage(tl("cleaning"));
sender.sendTl("cleaning");
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;
ess.runTaskAsynchronously(() -> {
@ -577,7 +581,7 @@ public class Commandessentials extends EssentialsCommand {
user.reset();
}
sender.sendMessage(tl("cleaned"));
sender.sendTl("cleaned");
});
}
@ -592,7 +596,7 @@ public class Commandessentials extends EssentialsCommand {
switch (args[1]) {
case "fix":
sender.sendMessage(tl("fixingHomes"));
sender.sendTl("fixingHomes");
ess.runTaskAsynchronously(() -> {
for (final UUID u : ess.getUsers().getAllUserUUIDs()) {
final User user = ess.getUsers().loadUncachedUser(u);
@ -609,15 +613,19 @@ public class Commandessentials extends EssentialsCommand {
}
}
}
sender.sendMessage(tl("fixedHomes"));
sender.sendTl("fixedHomes");
});
break;
case "delete":
final boolean filterByWorld = args.length >= 3;
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(() -> {
for (final UUID u : ess.getUsers().getAllUserUUIDs()) {
final User user = ess.getUsers().loadUncachedUser(u);
@ -635,7 +643,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;
default:
@ -645,21 +658,21 @@ public class Commandessentials extends EssentialsCommand {
// Gets information about cached users
private void runUserMap(final CommandSource sender, final String[] args) {
if (!sender.isAuthorized("essentials.usermap", ess)) {
if (!sender.isAuthorized("essentials.usermap")) {
return;
}
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[1].equals("full")) {
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")) {
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());
ess.runTaskAsynchronously(() -> {
@ -701,18 +714,18 @@ public class Commandessentials extends EssentialsCommand {
ess.getLogger().info("Found " + total + " orphaned userdata files.");
});
} 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 {
try {
final UUID uuid = UUID.fromString(args[1]);
for (final Map.Entry<String, UUID> entry : userMap.getNameCache().entrySet()) {
if (entry.getValue().equals(uuid)) {
sender.sendMessage(tl("usermapEntry", entry.getKey(), args[1]));
sender.sendTl("usermapEntry", entry.getKey(), args[1]);
}
}
} catch (IllegalArgumentException ignored) {
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 +751,9 @@ public class Commandessentials extends EssentialsCommand {
serverMessageKey = "versionOutputWarn";
}
sender.sendMessage(tl(serverMessageKey, "Server", server.getBukkitVersion() + " " + server.getVersion()));
sender.sendMessage(tl(serverMessageKey, "Brand", server.getName()));
sender.sendMessage(tl("versionOutputFine", "EssentialsX", essVer));
sender.sendTl(serverMessageKey, "Server", server.getBukkitVersion() + " " + server.getVersion());
sender.sendTl(serverMessageKey, "Brand", server.getName());
sender.sendTl("versionOutputFine", "EssentialsX", essVer);
for (final Plugin plugin : pm.getPlugins()) {
final PluginDescriptionFile desc = plugin.getDescription();
@ -753,22 +766,22 @@ public class Commandessentials extends EssentialsCommand {
if (!version.equalsIgnoreCase(essVer)) {
isMismatched = true;
sender.sendMessage(tl("versionOutputWarn", name, version));
sender.sendTl("versionOutputWarn", name, version);
} else {
sender.sendMessage(tl("versionOutputFine", name, version));
sender.sendTl("versionOutputFine", name, version);
}
} else {
sender.sendMessage(tl("versionOutputUnsupported", name, version));
sender.sendTl("versionOutputUnsupported", name, version);
isUnsupported = true;
}
}
if (versionPlugins.contains(name)) {
if (warnPlugins.contains(name)) {
sender.sendMessage(tl("versionOutputUnsupported", name, version));
sender.sendTl("versionOutputUnsupported", name, version);
isUnsupported = true;
} else {
sender.sendMessage(tl("versionOutputFine", name, version));
sender.sendTl("versionOutputFine", name, version);
}
}
@ -784,48 +797,48 @@ public class Commandessentials extends EssentialsCommand {
} else {
layer = "None";
}
sender.sendMessage(tl("versionOutputEconLayer", layer));
sender.sendTl("versionOutputEconLayer", layer);
if (isMismatched) {
sender.sendMessage(tl("versionMismatchAll"));
sender.sendTl("versionMismatchAll");
}
if (!isVaultInstalled) {
sender.sendMessage(tl("versionOutputVaultMissing"));
sender.sendTl("versionOutputVaultMissing");
}
if (isUnsupported) {
sender.sendMessage(tl("versionOutputUnsupportedPlugins"));
sender.sendTl("versionOutputUnsupportedPlugins");
}
switch (supportStatus) {
case NMS_CLEANROOM:
sender.sendMessage(ChatColor.DARK_RED + tl("serverUnsupportedCleanroom"));
sender.sendComponent(sender.tlComponent("serverUnsupportedCleanroom").color(NamedTextColor.DARK_RED));
break;
case DANGEROUS_FORK:
sender.sendMessage(ChatColor.DARK_RED + tl("serverUnsupportedDangerous"));
sender.sendComponent(sender.tlComponent("serverUnsupportedDangerous").color(NamedTextColor.DARK_RED));
break;
case STUPID_PLUGIN:
sender.sendMessage(ChatColor.DARK_RED + tl("serverUnsupportedDumbPlugins"));
sender.sendComponent(sender.tlComponent("serverUnsupportedDumbPlugins").color(NamedTextColor.DARK_RED));
break;
case UNSTABLE:
sender.sendMessage(ChatColor.DARK_RED + tl("serverUnsupportedMods"));
sender.sendComponent(sender.tlComponent("serverUnsupportedMods").color(NamedTextColor.DARK_RED));
break;
case OUTDATED:
sender.sendMessage(ChatColor.RED + tl("serverUnsupported"));
sender.sendComponent(sender.tlComponent("serverUnsupported").color(NamedTextColor.RED));
break;
case LIMITED:
sender.sendMessage(ChatColor.RED + tl("serverUnsupportedLimitedApi"));
sender.sendComponent(sender.tlComponent("serverUnsupportedLimitedApi").color(NamedTextColor.RED));
break;
}
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(() -> {
for (String str : ess.getUpdateChecker().getVersionMessages(true, true)) {
sender.sendMessage(str);
for (final Component component : ess.getUpdateChecker().getVersionMessages(true, true, sender)) {
sender.sendComponent(component);
}
});
}

View File

@ -4,6 +4,8 @@ import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.IUser;
import com.earth2me.essentials.User;
import com.earth2me.essentials.craftbukkit.SetExpFix;
import com.earth2me.essentials.messaging.IMessageRecipient;
import com.earth2me.essentials.utils.CommonPlaceholders;
import com.earth2me.essentials.utils.NumberUtil;
import com.google.common.collect.Lists;
import org.bukkit.Server;
@ -13,8 +15,6 @@ import java.util.Collections;
import java.util.List;
import java.util.Locale;
import static com.earth2me.essentials.I18n.tl;
public class Commandexp extends EssentialsLoopCommand {
public Commandexp() {
super("exp");
@ -22,7 +22,7 @@ public class Commandexp extends EssentialsLoopCommand {
@Override
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 (user == null) {
throw new NotEnoughArgumentsException();
@ -39,7 +39,7 @@ public class Commandexp extends EssentialsLoopCommand {
}
if (!cmd.hasPermission(user)) {
user.sendMessage(tl("noAccessSubCommand", "/" + commandLabel + " " + cmd.name().toLowerCase(Locale.ENGLISH)));
user.sendTl("noAccessSubCommand", "/" + commandLabel + " " + cmd.name().toLowerCase(Locale.ENGLISH));
return;
}
@ -99,7 +99,7 @@ public class Commandexp extends EssentialsLoopCommand {
}
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", CommonPlaceholders.displayNameRecipient((IMessageRecipient) target), SetExpFix.getTotalExperience(target.getBase()), target.getBase().getLevel(), SetExpFix.getExpUntilNextLevel(target.getBase()));
}
//TODO: Limit who can give negative exp?
@ -131,7 +131,7 @@ public class Commandexp extends EssentialsLoopCommand {
amount = 0L;
}
SetExpFix.setTotalExperience(target.getBase(), (int) amount);
sender.sendMessage(tl("expSet", target.getDisplayName(), amount));
sender.sendTl("expSet", CommonPlaceholders.displayNameRecipient((IMessageRecipient) target), amount);
}
@Override

View File

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

View File

@ -2,6 +2,8 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.CommonPlaceholders;
import net.ess3.api.IUser;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.FoodLevelChangeEvent;
@ -9,8 +11,6 @@ import org.bukkit.event.entity.FoodLevelChangeEvent;
import java.util.Collections;
import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandfeed extends EssentialsLoopCommand {
public Commandfeed() {
super("feed");
@ -28,7 +28,7 @@ public class Commandfeed extends EssentialsLoopCommand {
}
feedPlayer(user.getBase());
user.sendMessage(tl("feed"));
user.sendTl("feed");
}
@Override
@ -44,7 +44,7 @@ public class Commandfeed extends EssentialsLoopCommand {
protected void updatePlayer(final Server server, final CommandSource sender, final User player, final String[] args) throws PlayerExemptException {
try {
feedPlayer(player.getBase());
sender.sendMessage(tl("feedOther", player.getDisplayName()));
sender.sendTl("feedOther", CommonPlaceholders.displayName((IUser) player));
} catch (final QuietAbortException e) {
//Handle Quietly
}
@ -66,7 +66,7 @@ public class Commandfeed extends EssentialsLoopCommand {
@Override
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);
} else {
return Collections.emptyList();

View File

@ -5,6 +5,7 @@ import com.earth2me.essentials.utils.FloatUtil;
import com.earth2me.essentials.utils.VersionUtil;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import net.ess3.api.TranslatableException;
import org.bukkit.Server;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.DragonFireball;
@ -27,8 +28,6 @@ import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static com.earth2me.essentials.I18n.tl;
public class Commandfireball extends EssentialsCommand {
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)) {
throw new Exception(tl("noPerm", "essentials.fireball." + type));
throw new TranslatableException("noPerm", "essentials.fireball." + type);
}
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.NumberUtil;
import com.google.common.collect.Lists;
import net.ess3.api.TranslatableException;
import org.bukkit.DyeColor;
import org.bukkit.FireworkEffect;
import org.bukkit.Server;
@ -17,8 +18,6 @@ import org.bukkit.util.Vector;
import java.util.Collections;
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:
//
//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();
if (!MaterialUtil.isFirework(stack.getType())) {
throw new Exception(tl("holdFirework"));
throw new TranslatableException("holdFirework");
}
if (args[0].equalsIgnoreCase("clear")) {
final FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta();
fmeta.clearEffects();
stack.setItemMeta(fmeta);
user.sendMessage(tl("fireworkEffectsCleared"));
user.sendTl("fireworkEffectsCleared");
} else if (args.length > 1 && (args[0].equalsIgnoreCase("power") || args[0].equalsIgnoreCase("p"))) {
final FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta();
try {
final int power = Integer.parseInt(args[1]);
fmeta.setPower(power > 3 ? 4 : power);
} catch (final NumberFormatException e) {
throw new Exception(tl("invalidFireworkFormat", args[1], args[0]));
throw new TranslatableException("invalidFireworkFormat", args[1], args[0]);
}
stack.setItemMeta(fmeta);
} 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]);
if (amount > serverLimit) {
amount = serverLimit;
user.sendMessage(tl("mobSpawnLimit"));
user.sendTl("mobSpawnLimit");
}
} else {
direction = true;
@ -99,7 +98,7 @@ public class Commandfirework extends EssentialsCommand {
try {
mStack.addFireworkMeta(user.getSource(), true, arg, ess);
} catch (final Exception e) {
user.sendMessage(tl("fireworkSyntax"));
user.sendTl("fireworkSyntax");
throw e;
}
}
@ -108,13 +107,13 @@ public class Commandfirework extends EssentialsCommand {
final FireworkMeta fmeta = (FireworkMeta) mStack.getItemStack().getItemMeta();
final FireworkEffect effect = mStack.getFireworkBuilder().build();
if (fmeta.getEffects().size() > 0 && !user.isAuthorized("essentials.firework.multiple")) {
throw new Exception(tl("multipleCharges"));
throw new TranslatableException("multipleCharges");
}
fmeta.addEffect(effect);
stack.setItemMeta(fmeta);
} else {
user.sendMessage(tl("fireworkSyntax"));
throw new Exception(tl("fireworkColor"));
user.sendTl("fireworkSyntax");
throw new TranslatableException("fireworkColor");
}
}
}

View File

@ -2,11 +2,11 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.CommonPlaceholders;
import net.ess3.api.IUser;
import net.ess3.api.events.FlyStatusChangeEvent;
import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandfly extends EssentialsToggleCommand {
public Commandfly() {
super("fly", "essentials.fly.others");
@ -39,9 +39,9 @@ public class Commandfly extends EssentialsToggleCommand {
user.getBase().setFlying(false);
}
user.sendMessage(tl("flyMode", tl(enabled ? "enabled" : "disabled"), user.getDisplayName()));
user.sendTl("flyMode", CommonPlaceholders.enableDisable(user.getSource(), enabled), CommonPlaceholders.displayName((IUser) user));
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), CommonPlaceholders.displayName((IUser) user));
}
}
}

View File

@ -3,6 +3,8 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.IUser;
import com.earth2me.essentials.User;
import com.earth2me.essentials.messaging.IMessageRecipient;
import com.earth2me.essentials.utils.CommonPlaceholders;
import com.google.common.collect.ImmutableList;
import org.bukkit.GameMode;
import org.bukkit.Server;
@ -11,8 +13,6 @@ import java.util.Collections;
import java.util.List;
import java.util.Locale;
import static com.earth2me.essentials.I18n.tl;
public class Commandgamemode extends EssentialsLoopCommand {
private final List<String> STANDARD_OPTIONS = ImmutableList.of("creative", "survival", "adventure", "spectator", "toggle");
@ -57,26 +57,26 @@ public class Commandgamemode extends EssentialsLoopCommand {
}
if (isProhibitedChange(user, gameMode)) {
user.sendMessage(tl("cantGamemode", gameMode.name()));
user.sendTl("cantGamemode", gameMode.name());
return;
}
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)), CommonPlaceholders.displayNameRecipient((IMessageRecipient) user));
}
private void setUserGamemode(final CommandSource sender, final GameMode gameMode, final User user) throws NotEnoughArgumentsException {
if (gameMode == null) {
throw new NotEnoughArgumentsException(tl("gameModeInvalid"));
throw new NotEnoughArgumentsException(sender.tl("gameModeInvalid"));
}
if (sender.isPlayer() && isProhibitedChange(sender.getUser(ess), gameMode)) {
sender.sendMessage(tl("cantGamemode", gameMode.name()));
if (sender.isPlayer() && isProhibitedChange(sender.getUser(), gameMode)) {
sender.sendTl("cantGamemode", gameMode.name());
return;
}
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)), CommonPlaceholders.displayNameRecipient((IMessageRecipient) user));
}
// 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.logging.Level;
import static com.earth2me.essentials.I18n.tl;
public class Commandgc extends EssentialsCommand {
public Commandgc() {
super("gc");
@ -31,11 +29,11 @@ public class Commandgc extends EssentialsCommand {
color = ChatColor.RED;
}
sender.sendMessage(tl("uptime", DateUtil.formatDateDiff(ManagementFactory.getRuntimeMXBean().getStartTime())));
sender.sendMessage(tl("tps", "" + color + NumberUtil.formatDouble(tps)));
sender.sendMessage(tl("gcmax", Runtime.getRuntime().maxMemory() / 1024 / 1024));
sender.sendMessage(tl("gctotal", Runtime.getRuntime().totalMemory() / 1024 / 1024));
sender.sendMessage(tl("gcfree", Runtime.getRuntime().freeMemory() / 1024 / 1024));
sender.sendTl("uptime", DateUtil.formatDateDiff(ManagementFactory.getRuntimeMXBean().getStartTime()));
sender.sendTl("tps", "" + color + NumberUtil.formatDouble(tps));
sender.sendTl("gcmax", Runtime.getRuntime().maxMemory() / 1024 / 1024);
sender.sendTl("gctotal", Runtime.getRuntime().totalMemory() / 1024 / 1024);
sender.sendTl("gcfree", Runtime.getRuntime().freeMemory() / 1024 / 1024);
final List<World> worlds = server.getWorlds();
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);
}
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.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandgetpos extends EssentialsCommand {
public Commandgetpos() {
super("getpos");
@ -35,20 +33,20 @@ public class Commandgetpos extends EssentialsCommand {
}
private void outputPosition(final CommandSource sender, final Location coords, final Location distance) {
sender.sendMessage(tl("currentWorld", coords.getWorld().getName()));
sender.sendMessage(tl("posX", coords.getBlockX()));
sender.sendMessage(tl("posY", coords.getBlockY()));
sender.sendMessage(tl("posZ", coords.getBlockZ()));
sender.sendMessage(tl("posYaw", (coords.getYaw() + 360) % 360));
sender.sendMessage(tl("posPitch", coords.getPitch()));
sender.sendTl("currentWorld", coords.getWorld().getName());
sender.sendTl("posX", coords.getBlockX());
sender.sendTl("posY", coords.getBlockY());
sender.sendTl("posZ", coords.getBlockZ());
sender.sendTl("posYaw", (coords.getYaw() + 360) % 360);
sender.sendTl("posPitch", coords.getPitch());
if (distance != null && coords.getWorld().equals(distance.getWorld())) {
sender.sendMessage(tl("distance", coords.distance(distance)));
sender.sendTl("distance", coords.distance(distance));
}
}
@Override
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);
} else {
return Collections.emptyList();

View File

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

View File

@ -2,11 +2,10 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.CommonPlaceholders;
import net.ess3.api.events.GodStatusChangeEvent;
import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandgod extends EssentialsToggleCommand {
public Commandgod() {
super("god", "essentials.god.others");
@ -38,9 +37,9 @@ public class Commandgod extends EssentialsToggleCommand {
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())) {
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 org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandgrindstone extends EssentialsCommand {
public Commandgrindstone() {
@ -14,7 +12,7 @@ public class Commandgrindstone extends EssentialsCommand {
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (ess.getContainerProvider() == null) {
user.sendMessage(tl("unsupportedBrand"));
user.sendTl("unsupportedBrand");
return;
}

View File

@ -14,8 +14,6 @@ import org.bukkit.inventory.PlayerInventory;
import java.util.Collections;
import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandhat extends EssentialsCommand {
// 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"))) {
final ItemStack hand = Inventories.getItemInMainHand(user.getBase());
if (hand == null || hand.getType() == Material.AIR) {
user.sendMessage(tl("hatFail"));
user.sendTl("hatFail");
return;
}
final TriState wildcard = user.isAuthorizedExact(PERM_PREFIX + "*");
final TriState material = user.isAuthorizedExact(PERM_PREFIX + hand.getType().name().toLowerCase());
if ((wildcard == TriState.TRUE && material != TriState.FALSE) || ((wildcard != TriState.TRUE) && material == TriState.TRUE)) {
user.sendMessage(tl("hatFail"));
user.sendTl("hatFail");
return;
}
if (hand.getType().getMaxDurability() != 0) {
user.sendMessage(tl("hatArmor"));
user.sendTl("hatArmor");
return;
}
final PlayerInventory inv = user.getBase().getInventory();
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")) {
user.sendMessage(tl("hatCurse"));
user.sendTl("hatCurse");
return;
}
inv.setHelmet(hand);
Inventories.setItemInMainHand(user.getBase(), head);
user.sendMessage(tl("hatPlaced"));
user.sendTl("hatPlaced");
return;
}
final PlayerInventory inv = user.getBase().getInventory();
final ItemStack head = inv.getHelmet();
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")) {
user.sendMessage(tl("hatCurse"));
user.sendTl("hatCurse");
} else {
final ItemStack air = new ItemStack(Material.AIR);
inv.setHelmet(air);
Inventories.addItem(user.getBase(), head);
user.sendMessage(tl("hatRemoved"));
user.sendTl("hatRemoved");
}
}

View File

@ -2,6 +2,8 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.CommonPlaceholders;
import net.ess3.api.IUser;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityRegainHealthEvent;
@ -11,8 +13,6 @@ import org.bukkit.potion.PotionEffect;
import java.util.Collections;
import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandheal extends EssentialsLoopCommand {
public Commandheal() {
super("heal");
@ -47,7 +47,7 @@ public class Commandheal extends EssentialsLoopCommand {
final Player player = user.getBase();
if (player.getHealth() == 0) {
throw new PlayerExemptException(tl("healDead"));
throw new PlayerExemptException("healDead");
}
final double amount = player.getMaxHealth() - player.getHealth();
@ -65,13 +65,13 @@ public class Commandheal extends EssentialsLoopCommand {
player.setHealth(newAmount);
player.setFoodLevel(20);
player.setFireTicks(0);
user.sendMessage(tl("heal"));
user.sendTl("heal");
if (ess.getSettings().isRemovingEffectsOnHeal()) {
for (final PotionEffect effect : player.getActivePotionEffects()) {
player.removePotionEffect(effect.getType());
}
}
sender.sendMessage(tl("healOther", user.getDisplayName()));
sender.sendTl("healOther", CommonPlaceholders.displayName((IUser) user));
} catch (final QuietAbortException e) {
//Handle Quietly
}
@ -79,7 +79,7 @@ public class Commandheal extends EssentialsLoopCommand {
@Override
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);
} else {
return Collections.emptyList();

View File

@ -18,8 +18,6 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import static com.earth2me.essentials.I18n.tl;
public class Commandhelp extends EssentialsCommand {
public Commandhelp() {
super("help");
@ -38,15 +36,15 @@ public class Commandhelp extends EssentialsCommand {
final String cmd = pageStr.substring(1);
for (final Map.Entry<String, Command> knownCmd : ess.getKnownCommandsProvider().getKnownCommands().entrySet()) {
if (knownCmd.getKey().equalsIgnoreCase(cmd)) {
user.sendMessage(tl("commandHelpLine1", cmd));
user.sendMessage(tl("commandHelpLine2", knownCmd.getValue().getDescription()));
user.sendMessage(tl("commandHelpLine4", knownCmd.getValue().getAliases().toString()));
user.sendMessage(tl("commandHelpLine3"));
user.sendTl("commandHelpLine1", cmd);
user.sendTl("commandHelpLine2", knownCmd.getValue().getDescription());
user.sendTl("commandHelpLine4", knownCmd.getValue().getAliases().toString());
user.sendTl("commandHelpLine3");
final boolean isEssCommand = knownCmd.getValue() instanceof PluginIdentifiableCommand && ((PluginIdentifiableCommand) knownCmd.getValue()).getPlugin().equals(ess);
final IEssentialsCommand essCommand = isEssCommand ? ess.getCommandMap().get(knownCmd.getValue().getName()) : null;
if (essCommand != null && !essCommand.getUsageStrings().isEmpty()) {
for (Map.Entry<String, String> usage : essCommand.getUsageStrings().entrySet()) {
user.sendMessage(tl("commandHelpLineUsage", usage.getKey().replace("<command>", cmd), usage.getValue()));
user.sendTl("commandHelpLineUsage", usage.getKey().replace("<command>", cmd), usage.getValue());
}
} else {
user.sendMessage(knownCmd.getValue().getUsage());
@ -77,7 +75,7 @@ public class Commandhelp extends EssentialsCommand {
@Override
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

View File

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

View File

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

View File

@ -3,6 +3,7 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.ChargeException;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.CommonPlaceholders;
import com.earth2me.essentials.utils.VersionUtil;
import net.ess3.api.IUser;
import net.ess3.api.MaxMoneyException;
@ -11,8 +12,6 @@ import org.bukkit.Server;
import java.util.Collections;
import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandice extends EssentialsLoopCommand {
public Commandice() {
super("ice");
@ -21,7 +20,7 @@ public class Commandice extends EssentialsLoopCommand {
@Override
protected void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception {
if (VersionUtil.getServerBukkitVersion().isLowerThan(VersionUtil.v1_17_R01)) {
sender.sendMessage(tl("unsupportedFeature"));
sender.sendTl("unsupportedFeature");
return;
}
@ -29,28 +28,28 @@ public class Commandice extends EssentialsLoopCommand {
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);
return;
}
//noinspection ConstantConditions
freezePlayer(sender.getUser(ess));
freezePlayer(sender.getUser());
}
@Override
protected void updatePlayer(Server server, CommandSource sender, User user, String[] args) throws NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException {
freezePlayer(user);
sender.sendMessage(tl("iceOther", user.getDisplayName()));
sender.sendTl("iceOther", CommonPlaceholders.displayName((IUser) user));
}
private void freezePlayer(final IUser user) {
user.getBase().setFreezeTicks(user.getBase().getMaxFreezeTicks());
user.sendMessage(tl("ice"));
user.sendTl("ice");
}
@Override
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);
} else {
return Collections.emptyList();

View File

@ -7,8 +7,6 @@ import java.util.Collections;
import java.util.List;
import java.util.UUID;
import static com.earth2me.essentials.I18n.tl;
public class Commandignore extends EssentialsCommand {
public Commandignore() {
super("ignore");
@ -25,7 +23,7 @@ public class Commandignore extends EssentialsCommand {
}
}
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;
}
@ -40,15 +38,15 @@ public class Commandignore extends EssentialsCommand {
}
if (player.isIgnoreExempt()) {
user.sendMessage(tl("ignoreExempt"));
user.sendTl("ignoreExempt");
} else if (user.isIgnoredPlayer(player)) {
user.setIgnoredPlayer(player, false);
user.sendMessage(tl("unignorePlayer", player.getName()));
user.sendTl("unignorePlayer", player.getName());
} else if (user.getUUID().equals(player.getUUID())) {
user.sendMessage(tl("ignoreYourself"));
user.sendTl("ignoreYourself");
} else {
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.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandinvsee extends EssentialsCommand {
public Commandinvsee() {
super("invsee");
@ -24,14 +22,14 @@ public class Commandinvsee extends EssentialsCommand {
final User invUser = getPlayer(server, user, args, 0);
if (user == invUser) {
user.sendMessage(tl("invseeNoSelf"));
user.sendTl("invseeNoSelf");
throw new NoChargeException();
}
final Inventory inv;
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());
if (VersionUtil.getServerBukkitVersion().isHigherThanOrEqualTo(VersionUtil.v1_9_4_R01)) {
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.craftbukkit.Inventories;
import com.google.common.collect.Lists;
import net.ess3.api.TranslatableException;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.inventory.ItemStack;
@ -12,8 +13,6 @@ import java.util.Collections;
import java.util.List;
import java.util.Locale;
import static com.earth2me.essentials.I18n.tl;
public class Commanditem extends EssentialsCommand {
public Commanditem() {
super("item");
@ -29,7 +28,7 @@ public class Commanditem extends EssentialsCommand {
final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", "");
if (!user.canSpawnItem(stack.getType())) {
throw new Exception(tl("cantSpawnItem", itemname));
throw new TranslatableException("cantSpawnItem", itemname);
}
try {
@ -46,7 +45,7 @@ public class Commanditem extends EssentialsCommand {
final MetaItemStack metaStack = new MetaItemStack(stack);
if (!metaStack.canSpawn(ess)) {
throw new Exception(tl("unableToSpawnItem", itemname));
throw new TranslatableException("unableToSpawnItem", itemname);
}
if (args.length > 2) {
@ -58,11 +57,11 @@ public class Commanditem extends EssentialsCommand {
}
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('_', ' ');
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);
user.getBase().updateInventory();
}

View File

@ -12,8 +12,6 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commanditemdb extends EssentialsCommand {
public Commanditemdb() {
super("itemdb");
@ -41,18 +39,18 @@ public class Commanditemdb extends EssentialsCommand {
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
if (!tl("itemType").contains("{1}") && !itemId.equals("none")) {
sender.sendMessage(tl("itemId", itemId));
if (!sender.tl("itemType").contains("{1}") && !itemId.equals("none")) {
sender.sendTl("itemId", itemId);
}
if (itemHeld && itemStack.getType() != Material.AIR) {
final int maxuses = itemStack.getType().getMaxDurability();
final int durability = (maxuses + 1) - MaterialUtil.getDamage(itemStack);
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);
}
final String itemNameList = StringUtil.joinList(", ", nameList);
sender.sendMessage(tl("itemNames", itemNameList));
sender.sendTl("itemNames", itemNameList);
}
@Override

View File

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

View File

@ -13,8 +13,6 @@ import org.bukkit.inventory.meta.ItemMeta;
import java.util.Collections;
import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commanditemname extends EssentialsCommand {
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 {
final ItemStack item = Inventories.getItemInHand(user.getBase());
if (item == null || MaterialUtil.isAir(item.getType())) {
user.sendMessage(tl("itemnameInvalidItem"));
user.sendTl("itemnameInvalidItem");
return;
}
final TriState wildcard = user.isAuthorizedExact(PERM_PREFIX + "*");
final TriState material = user.isAuthorizedExact(PERM_PREFIX + item.getType().name().toLowerCase());
if ((wildcard == TriState.TRUE && material != TriState.FALSE) || ((wildcard != TriState.TRUE) && material == TriState.TRUE)) {
user.sendMessage(tl("itemnameInvalidItem"));
user.sendTl("itemnameInvalidItem");
return;
}
@ -45,7 +43,7 @@ public class Commanditemname extends EssentialsCommand {
final ItemMeta im = item.getItemMeta();
im.setDisplayName(name);
item.setItemMeta(im);
user.sendMessage(name == null ? tl("itemnameClear") : tl("itemnameSuccess", name));
user.sendTl(name == null ? "itemnameClear" : "itemnameSuccess", name);
}
@Override

View File

@ -4,8 +4,6 @@ import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.utils.StringUtil;
import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandjails extends EssentialsCommand {
public Commandjails() {
super("jails");
@ -14,9 +12,9 @@ public class Commandjails extends EssentialsCommand {
@Override
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (ess.getJails().getCount() == 0) {
sender.sendMessage(tl("noJailsDefined"));
sender.sendTl("noJailsDefined");
} 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.utils.LocationUtil;
import com.google.common.collect.Lists;
import net.ess3.api.TranslatableException;
import org.bukkit.Location;
import org.bukkit.Server;
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.List;
import static com.earth2me.essentials.I18n.tl;
// This method contains an undocumented sub command #EasterEgg
public class Commandjump extends EssentialsCommand {
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 (user.isFlyClickJump()) {
user.setRightClickJump(false);
user.sendMessage(tl("jumpEasterDisable"));
user.sendTl("jumpEasterDisable");
} else {
user.setRightClickJump(true);
user.sendMessage(tl("jumpEasterEnable"));
user.sendTl("jumpEasterEnable");
}
return;
}
@ -41,7 +40,7 @@ public class Commandjump extends EssentialsCommand {
loc.setPitch(cloc.getPitch());
loc.setY(loc.getY() + 1);
} catch (final NullPointerException ex) {
throw new Exception(tl("jumpError"), ex);
throw new TranslatableException(ex, "jumpError");
}
final Trade charge = new Trade(this.getName(), ess);

View File

@ -4,6 +4,7 @@ import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.Console;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.FormatUtil;
import net.ess3.api.TranslatableException;
import net.essentialsx.api.v2.events.UserKickEvent;
import org.bukkit.Server;
@ -11,7 +12,7 @@ import java.util.Collections;
import java.util.List;
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 Commandkick() {
@ -33,11 +34,11 @@ public class Commandkick extends EssentialsCommand {
}
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) : tlLiteral("kickDefault");
kickReason = FormatUtil.replaceFormat(kickReason.replace("\\n", "\n").replace("|", "\n"));
final UserKickEvent event = new UserKickEvent(user, target, kickReason);
@ -51,8 +52,10 @@ public class Commandkick extends EssentialsCommand {
target.getBase().kickPlayer(kickReason);
final String senderDisplayName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.DISPLAY_NAME;
ess.getLogger().log(Level.INFO, tl("playerKicked", senderDisplayName, target.getName(), kickReason));
ess.broadcastMessage("essentials.kick.notify", tl("playerKicked", senderDisplayName, target.getName(), kickReason));
final String tlKey = "playerKicked";
final Object[] objects = {senderDisplayName, target.getName(), kickReason};
ess.getLogger().log(Level.INFO, tlLiteral(tlKey, objects));
ess.broadcastTl(null, "essentials.kick.notify", tlKey, objects);
}
@Override

View File

@ -5,7 +5,7 @@ import com.earth2me.essentials.utils.FormatUtil;
import org.bukkit.Server;
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 Commandkickall() {
@ -14,7 +14,7 @@ public class Commandkickall extends EssentialsCommand {
@Override
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) : tlLiteral("kickDefault");
kickReason = FormatUtil.replaceFormat(kickReason.replace("\\n", "\n").replace("|", "\n"));
for (final Player onlinePlayer : ess.getOnlinePlayers()) {
@ -24,6 +24,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.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandkill extends EssentialsLoopCommand {
public Commandkill() {
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 {
final Player matchPlayer = user.getBase();
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);
server.getPluginManager().callEvent(ede);
@ -38,7 +36,7 @@ public class Commandkill extends EssentialsLoopCommand {
}
ede.getEntity().setLastDamageCause(ede);
matchPlayer.setHealth(0);
sender.sendMessage(tl("kill", matchPlayer.getDisplayName()));
sender.sendTl("kill", matchPlayer.getDisplayName());
}
@Override

View File

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

View File

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

View File

@ -2,15 +2,15 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.CommonPlaceholders;
import com.google.common.collect.Lists;
import net.ess3.api.IUser;
import org.bukkit.Server;
import org.bukkit.entity.LightningStrike;
import java.util.Collections;
import java.util.List;
import static com.earth2me.essentials.I18n.tl;
public class Commandlightning extends EssentialsLoopCommand {
public Commandlightning() {
super("lightning");
@ -18,9 +18,9 @@ public class Commandlightning extends EssentialsLoopCommand {
@Override
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()) {
sender.getPlayer().getWorld().strikeLightning(sender.getUser(ess).getTargetBlock(600).getLocation());
sender.getPlayer().getWorld().strikeLightning(sender.getUser().getTargetBlock(600).getLocation());
return;
}
throw new NotEnoughArgumentsException();
@ -35,14 +35,14 @@ public class Commandlightning extends EssentialsLoopCommand {
}
final int finalPower = power;
loopOnlinePlayersConsumer(server, sender, false, true, args[0], player -> {
sender.sendMessage(tl("lightningUse", player.getDisplayName()));
sender.sendTl("lightningUse", CommonPlaceholders.displayName((IUser) player));
final LightningStrike strike = player.getBase().getWorld().strikeLightningEffect(player.getBase().getLocation());
if (!player.isGodModeEnabled()) {
player.getBase().damage(finalPower, strike);
}
if (ess.getSettings().warnOnSmite()) {
player.sendMessage(tl("lightningSmited"));
player.sendTl("lightningSmited");
}
});
loopOnlinePlayers(server, sender, true, true, args[0], null);

View File

@ -35,7 +35,7 @@ public class Commandlist extends EssentialsCommand {
// 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) {
for (final String str : PlayerList.prepareGroupedList(ess, commandLabel, playerList)) {
for (final String str : PlayerList.prepareGroupedList(ess, sender, commandLabel, playerList)) {
sender.sendMessage(str);
}
}
@ -43,7 +43,7 @@ public class Commandlist extends EssentialsCommand {
@Override
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
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 {
return Collections.emptyList();
}

View File

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

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