diff --git a/bukkit-shared/src/main/java/net/buycraft/plugin/bukkit/BukkitBuycraftPlatformBase.java b/bukkit-shared/src/main/java/net/buycraft/plugin/bukkit/BukkitBuycraftPlatformBase.java index c0dc4662..47d3e26e 100644 --- a/bukkit-shared/src/main/java/net/buycraft/plugin/bukkit/BukkitBuycraftPlatformBase.java +++ b/bukkit-shared/src/main/java/net/buycraft/plugin/bukkit/BukkitBuycraftPlatformBase.java @@ -4,10 +4,12 @@ import net.buycraft.plugin.BuyCraftAPI; import net.buycraft.plugin.IBuycraftPlatform; import net.buycraft.plugin.UuidUtil; +import net.buycraft.plugin.bukkit.events.BuycraftPurchaseEvent; import net.buycraft.plugin.data.QueuedPlayer; import net.buycraft.plugin.data.responses.ServerInformation; import net.buycraft.plugin.execution.placeholder.PlaceholderManager; import net.buycraft.plugin.execution.strategy.CommandExecutor; +import net.buycraft.plugin.execution.strategy.ToRunQueuedCommand; import net.buycraft.plugin.platform.PlatformInformation; import net.buycraft.plugin.platform.PlatformType; import org.bukkit.Bukkit; @@ -38,7 +40,14 @@ public PlaceholderManager getPlaceholderManager() { } @Override - public void dispatchCommand(String command) { + public void dispatchCommand(String command, ToRunQueuedCommand queuedCommand) { + + BuycraftPurchaseEvent event = new BuycraftPurchaseEvent(command, queuedCommand); + + Bukkit.getPluginManager().callEvent(event); + + if (event.isCancelled()) return; + plugin.getServer().dispatchCommand(Bukkit.getConsoleSender(), command); } diff --git a/bukkit-shared/src/main/java/net/buycraft/plugin/bukkit/events/BuycraftPurchaseEvent.java b/bukkit-shared/src/main/java/net/buycraft/plugin/bukkit/events/BuycraftPurchaseEvent.java new file mode 100644 index 00000000..c331158f --- /dev/null +++ b/bukkit-shared/src/main/java/net/buycraft/plugin/bukkit/events/BuycraftPurchaseEvent.java @@ -0,0 +1,47 @@ +package net.buycraft.plugin.bukkit.events; + +import net.buycraft.plugin.execution.strategy.ToRunQueuedCommand; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class BuycraftPurchaseEvent extends Event implements Cancellable { + + private static final HandlerList HANDLERS = new HandlerList(); + + private boolean cancelled; + private final String command; + private final ToRunQueuedCommand queuedCommand; + + public BuycraftPurchaseEvent(String command, ToRunQueuedCommand queuedCommand) { + this.command = command; + this.queuedCommand = queuedCommand; + } + + public ToRunQueuedCommand getQueuedCommand() { + return this.queuedCommand; + } + + public String getCommand() { + return this.command; + } + + @Override + public HandlerList getHandlers() { + return HANDLERS; + } + + public static HandlerList getHandlerList() { + return HANDLERS; + } + + @Override + public boolean isCancelled() { + return this.cancelled; + } + + @Override + public void setCancelled(boolean status) { + this.cancelled = status; + } +} diff --git a/bungeecord/src/main/java/net/buycraft/plugin/bungeecord/BungeeCordBuycraftPlatform.java b/bungeecord/src/main/java/net/buycraft/plugin/bungeecord/BungeeCordBuycraftPlatform.java index d91e12b9..9b60ab02 100644 --- a/bungeecord/src/main/java/net/buycraft/plugin/bungeecord/BungeeCordBuycraftPlatform.java +++ b/bungeecord/src/main/java/net/buycraft/plugin/bungeecord/BungeeCordBuycraftPlatform.java @@ -3,10 +3,12 @@ import net.buycraft.plugin.BuyCraftAPI; import net.buycraft.plugin.IBuycraftPlatform; import net.buycraft.plugin.UuidUtil; +import net.buycraft.plugin.bungeecord.events.BuycraftPurchaseEvent; import net.buycraft.plugin.data.QueuedPlayer; import net.buycraft.plugin.data.responses.ServerInformation; import net.buycraft.plugin.execution.placeholder.PlaceholderManager; import net.buycraft.plugin.execution.strategy.CommandExecutor; +import net.buycraft.plugin.execution.strategy.ToRunQueuedCommand; import net.buycraft.plugin.platform.NoBlocking; import net.buycraft.plugin.platform.PlatformInformation; import net.buycraft.plugin.platform.PlatformType; @@ -34,7 +36,12 @@ public PlaceholderManager getPlaceholderManager() { } @Override - public void dispatchCommand(String command) { + public void dispatchCommand(String command, ToRunQueuedCommand queuedCommand) { + + BuycraftPurchaseEvent event = plugin.getProxy().getPluginManager().callEvent(new BuycraftPurchaseEvent(command, queuedCommand)); + + if (event.isCancelled()) return; + plugin.getProxy().getPluginManager().dispatchCommand(plugin.getProxy().getConsole(), command); } diff --git a/bungeecord/src/main/java/net/buycraft/plugin/bungeecord/events/BuycraftPurchaseEvent.java b/bungeecord/src/main/java/net/buycraft/plugin/bungeecord/events/BuycraftPurchaseEvent.java new file mode 100644 index 00000000..24680feb --- /dev/null +++ b/bungeecord/src/main/java/net/buycraft/plugin/bungeecord/events/BuycraftPurchaseEvent.java @@ -0,0 +1,32 @@ +package net.buycraft.plugin.bungeecord.events; + +import net.buycraft.plugin.execution.strategy.ToRunQueuedCommand; +import net.md_5.bungee.api.plugin.Event; + +public class BuycraftPurchaseEvent extends Event { + + private boolean cancelled; + private final String command; + private final ToRunQueuedCommand queuedCommand; + + public BuycraftPurchaseEvent(String command, ToRunQueuedCommand queuedCommand) { + this.command = command; + this.queuedCommand = queuedCommand; + } + + public ToRunQueuedCommand getQueuedCommand() { + return this.queuedCommand; + } + + public String getCommand() { + return this.command; + } + + public boolean isCancelled() { + return this.cancelled; + } + + public void setCancelled(boolean status) { + this.cancelled = status; + } +} diff --git a/common/src/main/java/net/buycraft/plugin/IBuycraftPlatform.java b/common/src/main/java/net/buycraft/plugin/IBuycraftPlatform.java index 463ce415..149367fd 100644 --- a/common/src/main/java/net/buycraft/plugin/IBuycraftPlatform.java +++ b/common/src/main/java/net/buycraft/plugin/IBuycraftPlatform.java @@ -4,6 +4,7 @@ import net.buycraft.plugin.data.responses.ServerInformation; import net.buycraft.plugin.execution.placeholder.PlaceholderManager; import net.buycraft.plugin.execution.strategy.CommandExecutor; +import net.buycraft.plugin.execution.strategy.ToRunQueuedCommand; import net.buycraft.plugin.platform.PlatformInformation; import java.util.concurrent.TimeUnit; @@ -29,7 +30,7 @@ public interface IBuycraftPlatform { * * @param command the command to execute */ - void dispatchCommand(String command); + void dispatchCommand(String command, ToRunQueuedCommand queuedCommand); /** * Executes a task to be scheduled as soon as possible asynchronously. diff --git a/common/src/main/java/net/buycraft/plugin/execution/strategy/QueuedCommandExecutor.java b/common/src/main/java/net/buycraft/plugin/execution/strategy/QueuedCommandExecutor.java index e4038fc2..4bc6da83 100644 --- a/common/src/main/java/net/buycraft/plugin/execution/strategy/QueuedCommandExecutor.java +++ b/common/src/main/java/net/buycraft/plugin/execution/strategy/QueuedCommandExecutor.java @@ -70,7 +70,8 @@ public void run() { String finalCommand = platform.getPlaceholderManager().doReplace(command.getPlayer(), command.getCommand()); platform.log(Level.INFO, String.format("Dispatching command '%s' for player '%s'.", finalCommand, command.getPlayer().getName())); try { - platform.dispatchCommand(finalCommand); + + platform.dispatchCommand(finalCommand, command); completedCommandsTask.add(command.getCommand().getId()); } catch (Exception e) { platform.log(Level.SEVERE, String.format("Could not dispatch command '%s' for player '%s'. " + diff --git a/common/src/main/java/net/buycraft/plugin/platform/standalone/runner/StandaloneBuycraftRunner.java b/common/src/main/java/net/buycraft/plugin/platform/standalone/runner/StandaloneBuycraftRunner.java index 756faa93..9b88eaad 100644 --- a/common/src/main/java/net/buycraft/plugin/platform/standalone/runner/StandaloneBuycraftRunner.java +++ b/common/src/main/java/net/buycraft/plugin/platform/standalone/runner/StandaloneBuycraftRunner.java @@ -5,6 +5,7 @@ import net.buycraft.plugin.data.QueuedPlayer; import net.buycraft.plugin.data.responses.ServerInformation; import net.buycraft.plugin.execution.DuePlayerFetcher; +import net.buycraft.plugin.execution.strategy.ToRunQueuedCommand; import net.buycraft.plugin.platform.NoBlocking; import net.buycraft.plugin.platform.standalone.StandaloneBuycraftPlatform; import okhttp3.OkHttpClient; @@ -64,7 +65,7 @@ private class Platform extends StandaloneBuycraftPlatform { } @Override - public void dispatchCommand(String command) { + public void dispatchCommand(String command, ToRunQueuedCommand queuedCommand) { dispatcher.dispatchCommand(command); } diff --git a/common/src/test/java/net/buycraft/plugin/testutil/SimulatedPlayerBuycraftPlatform.java b/common/src/test/java/net/buycraft/plugin/testutil/SimulatedPlayerBuycraftPlatform.java index 6226e0dc..06189537 100644 --- a/common/src/test/java/net/buycraft/plugin/testutil/SimulatedPlayerBuycraftPlatform.java +++ b/common/src/test/java/net/buycraft/plugin/testutil/SimulatedPlayerBuycraftPlatform.java @@ -6,6 +6,7 @@ import net.buycraft.plugin.data.responses.ServerInformation; import net.buycraft.plugin.execution.placeholder.PlaceholderManager; import net.buycraft.plugin.execution.strategy.CommandExecutor; +import net.buycraft.plugin.execution.strategy.ToRunQueuedCommand; import net.buycraft.plugin.platform.PlatformInformation; import java.util.HashMap; @@ -27,7 +28,7 @@ public PlaceholderManager getPlaceholderManager() { } @Override - public void dispatchCommand(String command) { + public void dispatchCommand(String command, ToRunQueuedCommand queuedCommand) { } @Override diff --git a/nukkit/pom.xml b/nukkit/pom.xml deleted file mode 100644 index 8cf9eec4..00000000 --- a/nukkit/pom.xml +++ /dev/null @@ -1,92 +0,0 @@ - - - - BuycraftX - net.buycraft - 12.0.7 - - 4.0.0 - - buycraftx-nukkit - - - - - src/main/resources - true - - - - - org.apache.maven.plugins - maven-shade-plugin - 2.4 - - - - - - - - com.google.gson - net.buycraft.plugin.internal.gson - - - okhttp3 - net.buycraft.plugin.internal.okhttp3 - - - okio - net.buycraft.plugin.internal.okio - - - retrofit2 - net.buycraft.plugin.internal.retrofit2 - - - com.fasterxml.jackson - net.buycraft.plugin.internal.jackson - - - org.slf4j - net.buycraft.plugin.internal.slf4j - - - - false - - - - package - - shade - - - - - - - - - - zxda-nukkit-repo - https://repo.nukkitx.com/maven-snapshots/ - - - - - - cn.nukkit - nukkit - 1.0-SNAPSHOT - provided - - - net.buycraft - buycraftx-plugin-shared - ${project.parent.version} - compile - - - diff --git a/nukkit/src/main/java/net/buycraft/plugin/nukkit/BuycraftCommand.java b/nukkit/src/main/java/net/buycraft/plugin/nukkit/BuycraftCommand.java deleted file mode 100644 index 036f7302..00000000 --- a/nukkit/src/main/java/net/buycraft/plugin/nukkit/BuycraftCommand.java +++ /dev/null @@ -1,55 +0,0 @@ -package net.buycraft.plugin.nukkit; - -import cn.nukkit.command.Command; -import cn.nukkit.command.CommandExecutor; -import cn.nukkit.command.CommandSender; -import cn.nukkit.utils.TextFormat; -import net.buycraft.plugin.nukkit.command.Subcommand; - -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.Map; - -public class BuycraftCommand implements CommandExecutor { - private final Map subcommandMap = new LinkedHashMap<>(); - private final BuycraftPlugin plugin; - - public BuycraftCommand(final BuycraftPlugin plugin) { - this.plugin = plugin; - } - - private void showHelp(CommandSender sender) { - sender.sendMessage(TextFormat.DARK_AQUA + TextFormat.BOLD.toString() + plugin.getI18n().get("usage")); - for (Map.Entry entry : subcommandMap.entrySet()) { - sender.sendMessage(TextFormat.GREEN + "/tebex " + entry.getKey() + TextFormat.GRAY + ": " + entry.getValue().getDescription()); - } - } - - @Override - public boolean onCommand(CommandSender sender, Command command, String s, String[] args) { - if (!sender.hasPermission("buycraft.admin")) { - sender.sendMessage(TextFormat.RED + plugin.getI18n().get("no_permission")); - return true; - } - - if (args.length == 0) { - showHelp(sender); - return true; - } - - for (Map.Entry entry : subcommandMap.entrySet()) { - if (entry.getKey().equalsIgnoreCase(args[0])) { - String[] withoutSubcommand = Arrays.copyOfRange(args, 1, args.length); - entry.getValue().execute(sender, withoutSubcommand); - return true; - } - } - - showHelp(sender); - return true; - } - - public Map getSubcommandMap() { - return this.subcommandMap; - } -} diff --git a/nukkit/src/main/java/net/buycraft/plugin/nukkit/BuycraftListener.java b/nukkit/src/main/java/net/buycraft/plugin/nukkit/BuycraftListener.java deleted file mode 100644 index e57c7b1d..00000000 --- a/nukkit/src/main/java/net/buycraft/plugin/nukkit/BuycraftListener.java +++ /dev/null @@ -1,53 +0,0 @@ -package net.buycraft.plugin.nukkit; - -import cn.nukkit.event.EventHandler; -import cn.nukkit.event.Listener; -import cn.nukkit.event.player.PlayerJoinEvent; -import cn.nukkit.event.player.PlayerQuitEvent; -import net.buycraft.plugin.data.QueuedPlayer; -import net.buycraft.plugin.data.ServerEvent; - -import java.util.Date; - -public class BuycraftListener implements Listener { - private final BuycraftPlugin plugin; - - public BuycraftListener(final BuycraftPlugin plugin) { - this.plugin = plugin; - } - - @EventHandler - public void onPlayerJoin(PlayerJoinEvent event) { - if (plugin.getApiClient() == null) { - return; - } - - plugin.getServerEventSenderTask().queueEvent(new ServerEvent( - event.getPlayer().getUniqueId().toString().replace("-", ""), - event.getPlayer().getName(), - event.getPlayer().getAddress(), - ServerEvent.JOIN_EVENT, - new Date() - )); - - QueuedPlayer qp = plugin.getDuePlayerFetcher().fetchAndRemoveDuePlayer(event.getPlayer().getName()); - if (qp != null) { - plugin.getPlayerJoinCheckTask().queue(qp); - } - } - - @EventHandler - public void onPlayerQuit(PlayerQuitEvent event) { - if (plugin.getApiClient() == null) { - return; - } - - plugin.getServerEventSenderTask().queueEvent(new ServerEvent( - event.getPlayer().getUniqueId().toString().replace("-", ""), - event.getPlayer().getName(), - event.getPlayer().getAddress(), - ServerEvent.LEAVE_EVENT, - new Date() - )); - } -} diff --git a/nukkit/src/main/java/net/buycraft/plugin/nukkit/BuycraftPlugin.java b/nukkit/src/main/java/net/buycraft/plugin/nukkit/BuycraftPlugin.java deleted file mode 100644 index e3b7da51..00000000 --- a/nukkit/src/main/java/net/buycraft/plugin/nukkit/BuycraftPlugin.java +++ /dev/null @@ -1,210 +0,0 @@ -package net.buycraft.plugin.nukkit; - -import cn.nukkit.command.Command; -import cn.nukkit.command.CommandSender; -import cn.nukkit.plugin.PluginBase; -import net.buycraft.plugin.BuyCraftAPI; -import net.buycraft.plugin.IBuycraftPlatform; -import net.buycraft.plugin.data.responses.ServerInformation; -import net.buycraft.plugin.execution.DuePlayerFetcher; -import net.buycraft.plugin.execution.ServerEventSenderTask; -import net.buycraft.plugin.execution.placeholder.NamePlaceholder; -import net.buycraft.plugin.execution.placeholder.PlaceholderManager; -import net.buycraft.plugin.execution.placeholder.XuidPlaceholder; -import net.buycraft.plugin.execution.strategy.CommandExecutor; -import net.buycraft.plugin.execution.strategy.PostCompletedCommandsTask; -import net.buycraft.plugin.execution.strategy.QueuedCommandExecutor; -import net.buycraft.plugin.nukkit.command.*; -import net.buycraft.plugin.nukkit.logging.LoggerUtils; -import net.buycraft.plugin.nukkit.util.VersionCheck; -import net.buycraft.plugin.shared.Setup; -import net.buycraft.plugin.shared.config.BuycraftConfiguration; -import net.buycraft.plugin.shared.config.BuycraftI18n; -import net.buycraft.plugin.shared.tasks.PlayerJoinCheckTask; -import net.buycraft.plugin.shared.util.AnalyticsSend; -import okhttp3.OkHttpClient; - -import java.io.File; -import java.io.IOException; -import java.nio.file.NoSuchFileException; -import java.nio.file.Path; -import java.util.concurrent.TimeUnit; - -public class BuycraftPlugin extends PluginBase { - private final PlaceholderManager placeholderManager = new PlaceholderManager(); - private final BuycraftConfiguration configuration = new BuycraftConfiguration(); - - private BuyCraftAPI apiClient; - private DuePlayerFetcher duePlayerFetcher; - private ServerInformation serverInformation; - private OkHttpClient httpClient; - private IBuycraftPlatform platform; - private CommandExecutor commandExecutor; - private BuycraftI18n i18n; - private PostCompletedCommandsTask completedCommandsTask; - private PlayerJoinCheckTask playerJoinCheckTask; - private ServerEventSenderTask serverEventSenderTask; - private LoggerUtils loggerUtils; - private BuycraftCommand command; - - @Override - public void onEnable() { - // Pre-initialization. - platform = new NukkitBuycraftPlatform(this); - - // Initialize configuration. - getDataFolder().mkdir(); - Path configPath = getDataFolder().toPath().resolve("config.properties"); - try { - try { - configuration.load(configPath); - } catch (NoSuchFileException e) { - // Save defaults - configuration.fillDefaults(); - configuration.save(configPath); - } - } catch (IOException e) { - throw new RuntimeException("Unable to load configuration", e); - } - - i18n = configuration.createI18n(); - httpClient = Setup.okhttp(new File(getDataFolder(), "cache")); - loggerUtils = new LoggerUtils(getLogger()); - - // Initialize API client. - final String serverKey = configuration.getServerKey(); - if (serverKey == null || serverKey.equals("INVALID")) { - getLogger().info("Looks like this is a fresh setup. Get started by using 'tebex secret ' in the console."); - } else { - getLogger().info("Validating your server key..."); - final BuyCraftAPI client = BuyCraftAPI.create(configuration.getServerKey(), httpClient); - try { - updateInformation(client); - } catch (IOException e) { - getLogger().error(String.format("We can't check if your server can connect to Tebex: %s", e.getMessage())); - } - apiClient = client; - } - - // Check for latest version. - if (configuration.isCheckForUpdates()) { - final VersionCheck check = new VersionCheck(this, getDescription().getVersion(), configuration.getServerKey()); - try { - check.verify(); - } catch (IOException e) { - getLogger().error("Can't check for updates", e); - } - getServer().getPluginManager().registerEvents(check, this); - } - - // Initialize placeholders. - placeholderManager.addPlaceholder(new NamePlaceholder()); - placeholderManager.addPlaceholder(new XuidPlaceholder()); - - // Queueing tasks. - platform.executeAsyncLater(duePlayerFetcher = new DuePlayerFetcher(platform, configuration.isVerbose()), 1, TimeUnit.SECONDS); - completedCommandsTask = new PostCompletedCommandsTask(platform); - commandExecutor = new QueuedCommandExecutor(platform, completedCommandsTask); - getServer().getScheduler().scheduleDelayedRepeatingTask(this, completedCommandsTask, 20, 20); - getServer().getScheduler().scheduleDelayedRepeatingTask(this, (Runnable) commandExecutor, 1, 1); - playerJoinCheckTask = new PlayerJoinCheckTask(platform); - getServer().getScheduler().scheduleDelayedRepeatingTask(this, playerJoinCheckTask, 1, 1); - serverEventSenderTask = new ServerEventSenderTask(platform, configuration.isVerbose()); - getServer().getScheduler().scheduleDelayedRepeatingTask(this, serverEventSenderTask, 20 * 60, 20 * 60, true); - - // Register listener. - getServer().getPluginManager().registerEvents(new BuycraftListener(this), this); - - // Initialize and register commands. - command = new BuycraftCommand(this); - command.getSubcommandMap().put("forcecheck", new ForceCheckSubcommand(this)); - command.getSubcommandMap().put("secret", new SecretSubcommand(this)); - command.getSubcommandMap().put("info", new InformationSubcommand(this)); - command.getSubcommandMap().put("report", new ReportCommand(this)); - command.getSubcommandMap().put("coupon", new CouponSubcommand(this)); - - // Send data to Keen IO - if (serverInformation != null) { - getServer().getScheduler().scheduleDelayedRepeatingTask(this, () -> { - try { - AnalyticsSend.postServerInformation(httpClient, serverKey, platform, false); - } catch (IOException e) { - getLogger().warning("Can't send analytics", e); - } - }, 0, 20 * 60 * 60 * 24); - } - } - - @Override - public void onDisable() { - if (completedCommandsTask != null) { - completedCommandsTask.flush(); - } - } - - @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - return this.command.onCommand(sender, command, label, args); - } - - public void saveConfiguration() throws IOException { - Path configPath = getDataFolder().toPath().resolve("config.properties"); - configuration.save(configPath); - } - - public void updateInformation(BuyCraftAPI client) throws IOException { - serverInformation = client.getServerInformation().execute().body(); - } - - public PlaceholderManager getPlaceholderManager() { - return this.placeholderManager; - } - - public BuycraftConfiguration getConfiguration() { - return this.configuration; - } - - public BuyCraftAPI getApiClient() { - return this.apiClient; - } - - public void setApiClient(final BuyCraftAPI apiClient) { - this.apiClient = apiClient; - } - - public DuePlayerFetcher getDuePlayerFetcher() { - return this.duePlayerFetcher; - } - - public ServerInformation getServerInformation() { - return this.serverInformation; - } - - public OkHttpClient getHttpClient() { - return this.httpClient; - } - - public IBuycraftPlatform getPlatform() { - return this.platform; - } - - public CommandExecutor getCommandExecutor() { - return this.commandExecutor; - } - - public BuycraftI18n getI18n() { - return this.i18n; - } - - public PlayerJoinCheckTask getPlayerJoinCheckTask() { - return this.playerJoinCheckTask; - } - - public ServerEventSenderTask getServerEventSenderTask() { - return serverEventSenderTask; - } - - public LoggerUtils getLoggerUtils() { - return this.loggerUtils; - } -} diff --git a/nukkit/src/main/java/net/buycraft/plugin/nukkit/NukkitBuycraftPlatform.java b/nukkit/src/main/java/net/buycraft/plugin/nukkit/NukkitBuycraftPlatform.java deleted file mode 100644 index 5b479b70..00000000 --- a/nukkit/src/main/java/net/buycraft/plugin/nukkit/NukkitBuycraftPlatform.java +++ /dev/null @@ -1,125 +0,0 @@ -package net.buycraft.plugin.nukkit; - -import cn.nukkit.Player; -import cn.nukkit.scheduler.AsyncTask; -import net.buycraft.plugin.BuyCraftAPI; -import net.buycraft.plugin.IBuycraftPlatform; -import net.buycraft.plugin.data.QueuedPlayer; -import net.buycraft.plugin.data.responses.ServerInformation; -import net.buycraft.plugin.execution.placeholder.PlaceholderManager; -import net.buycraft.plugin.execution.strategy.CommandExecutor; -import net.buycraft.plugin.platform.PlatformInformation; -import net.buycraft.plugin.platform.PlatformType; - -import java.util.concurrent.TimeUnit; -import java.util.logging.Level; - -public class NukkitBuycraftPlatform implements IBuycraftPlatform { - private final BuycraftPlugin plugin; - - public NukkitBuycraftPlatform(BuycraftPlugin plugin) { - this.plugin = plugin; - } - - @Override - public BuyCraftAPI getApiClient() { - return plugin.getApiClient(); - } - - @Override - public PlaceholderManager getPlaceholderManager() { - return plugin.getPlaceholderManager(); - } - - @Override - public void dispatchCommand(String command) { - plugin.getServer().getCommandMap().dispatch(plugin.getServer().getConsoleSender(), command); - } - - @Override - public void executeAsync(Runnable runnable) { - plugin.getServer().getScheduler().scheduleAsyncTask(plugin, new AsyncTask() { - @Override - public void onRun() { - runnable.run(); - } - }); - } - - @Override - public void executeAsyncLater(Runnable runnable, long time, TimeUnit unit) { - plugin.getServer().getScheduler().scheduleDelayedTask(plugin, () -> - plugin.getServer().getScheduler().scheduleAsyncTask(plugin, new AsyncTask() { - @Override - public void onRun() { - runnable.run(); - } - }), (int) (unit.toMillis(time) / 50)); - } - - @Override - public void executeBlocking(Runnable runnable) { - // BungeeCord has no concept of "blocking" - executeAsync(runnable); - } - - @Override - public void executeBlockingLater(Runnable runnable, long time, TimeUnit unit) { - // BungeeCord has no concept of "blocking" - executeAsyncLater(runnable, time, unit); - } - - private Player getPlayer(QueuedPlayer player) { - return plugin.getServer().getPlayer(player.getName()); - } - - @Override - public boolean isPlayerOnline(QueuedPlayer player) { - return getPlayer(player) != null; - } - - @Override - public int getFreeSlots(QueuedPlayer player) { - Player player1 = getPlayer(player); - if (player1 != null) { - int free = 0; - for (int i = 0; i < player1.getInventory().getSize(); i++) { - if (player1.getInventory().getItem(i).getId() == 0) { - free++; - } - } - return free; - } - return -1; - } - - @Override - public void log(Level level, String message) { - plugin.getLoggerUtils().log(level, message); - } - - @Override - public void log(Level level, String message, Throwable throwable) { - plugin.getLoggerUtils().log(level, message, throwable); - } - - @Override - public CommandExecutor getExecutor() { - return plugin.getCommandExecutor(); - } - - @Override - public PlatformInformation getPlatformInformation() { - return new PlatformInformation(PlatformType.NUKKIT, plugin.getServer().getNukkitVersion()); - } - - @Override - public String getPluginVersion() { - return plugin.getDescription().getVersion(); - } - - @Override - public ServerInformation getServerInformation() { - return plugin.getServerInformation(); - } -} diff --git a/nukkit/src/main/java/net/buycraft/plugin/nukkit/command/CouponSubcommand.java b/nukkit/src/main/java/net/buycraft/plugin/nukkit/command/CouponSubcommand.java deleted file mode 100644 index ebf452ab..00000000 --- a/nukkit/src/main/java/net/buycraft/plugin/nukkit/command/CouponSubcommand.java +++ /dev/null @@ -1,82 +0,0 @@ -package net.buycraft.plugin.nukkit.command; - -import cn.nukkit.command.CommandSender; -import cn.nukkit.utils.TextFormat; -import net.buycraft.plugin.data.Coupon; -import net.buycraft.plugin.nukkit.BuycraftPlugin; -import net.buycraft.plugin.shared.util.CouponUtil; - -import java.io.IOException; -import java.util.Arrays; - -public class CouponSubcommand implements Subcommand { - private static final int COUPON_PAGE_LIMIT = 10; - - private final BuycraftPlugin plugin; - - public CouponSubcommand(final BuycraftPlugin plugin) { - this.plugin = plugin; - } - - @Override - public void execute(CommandSender sender, String[] args) { - if (args.length == 0) { - sender.sendMessage(TextFormat.RED + plugin.getI18n().get("usage_coupon_subcommands")); - return; - } - - switch (args[0]) { - case "create": - createCoupon(sender, args); - break; - case "delete": - deleteCoupon(sender, args); - break; - default: - sender.sendMessage(TextFormat.RED + plugin.getI18n().get("usage_coupon_subcommands")); - break; - } - } - - private void createCoupon(final CommandSender sender, String[] args) { - String[] stripped = Arrays.copyOfRange(args, 1, args.length); - final Coupon coupon; - try { - coupon = CouponUtil.parseArguments(stripped); - } catch (Exception e) { - sender.sendMessage(TextFormat.RED + plugin.getI18n().get("coupon_creation_arg_parse_failure", e.getMessage())); - return; - } - - plugin.getPlatform().executeAsync(() -> { - try { - plugin.getApiClient().createCoupon(coupon).execute(); - sender.sendMessage(TextFormat.GREEN + plugin.getI18n().get("coupon_creation_success", coupon.getCode())); - } catch (IOException e) { - sender.sendMessage(TextFormat.RED + plugin.getI18n().get("generic_api_operation_error")); - } - }); - } - - private void deleteCoupon(final CommandSender sender, String[] args) { - if (args.length != 2) { - sender.sendMessage(TextFormat.RED + plugin.getI18n().get("no_coupon_specified")); - return; - } - final String code = args[1]; - - plugin.getPlatform().executeAsync(() -> { - try { - plugin.getApiClient().deleteCoupon(code).execute(); - sender.sendMessage(TextFormat.GREEN + plugin.getI18n().get("coupon_deleted")); - } catch (IOException e) { - sender.sendMessage(TextFormat.RED + e.getMessage()); - } - }); - } - - @Override - public String getDescription() { - return plugin.getI18n().get("usage_coupon"); - } -} diff --git a/nukkit/src/main/java/net/buycraft/plugin/nukkit/command/ForceCheckSubcommand.java b/nukkit/src/main/java/net/buycraft/plugin/nukkit/command/ForceCheckSubcommand.java deleted file mode 100644 index 4b1fa1a7..00000000 --- a/nukkit/src/main/java/net/buycraft/plugin/nukkit/command/ForceCheckSubcommand.java +++ /dev/null @@ -1,39 +0,0 @@ -package net.buycraft.plugin.nukkit.command; - -import cn.nukkit.command.CommandSender; -import cn.nukkit.utils.TextFormat; -import net.buycraft.plugin.nukkit.BuycraftPlugin; - -public class ForceCheckSubcommand implements Subcommand { - private final BuycraftPlugin plugin; - - public ForceCheckSubcommand(final BuycraftPlugin plugin) { - this.plugin = plugin; - } - - @Override - public void execute(CommandSender sender, String[] args) { - if (args.length != 0) { - sender.sendMessage(TextFormat.RED + plugin.getI18n().get("no_params")); - return; - } - - if (plugin.getApiClient() == null) { - sender.sendMessage(TextFormat.RED + plugin.getI18n().get("need_secret_key")); - return; - } - - if (plugin.getDuePlayerFetcher().inProgress()) { - sender.sendMessage(TextFormat.RED + plugin.getI18n().get("already_checking_for_purchases")); - return; - } - - plugin.getPlatform().executeAsync(() -> plugin.getDuePlayerFetcher().run(false)); - sender.sendMessage(TextFormat.GREEN + plugin.getI18n().get("forcecheck_queued")); - } - - @Override - public String getDescription() { - return plugin.getI18n().get("usage_forcecheck"); - } -} diff --git a/nukkit/src/main/java/net/buycraft/plugin/nukkit/command/InformationSubcommand.java b/nukkit/src/main/java/net/buycraft/plugin/nukkit/command/InformationSubcommand.java deleted file mode 100644 index f6986931..00000000 --- a/nukkit/src/main/java/net/buycraft/plugin/nukkit/command/InformationSubcommand.java +++ /dev/null @@ -1,45 +0,0 @@ -package net.buycraft.plugin.nukkit.command; - -import cn.nukkit.command.CommandSender; -import cn.nukkit.utils.TextFormat; -import net.buycraft.plugin.nukkit.BuycraftPlugin; - -public class InformationSubcommand implements Subcommand { - private final BuycraftPlugin plugin; - - public InformationSubcommand(final BuycraftPlugin plugin) { - this.plugin = plugin; - } - - @Override - public void execute(CommandSender sender, String[] args) { - if (args.length != 0) { - sender.sendMessage(TextFormat.RED + plugin.getI18n().get("no_params")); - return; - } - - if (plugin.getApiClient() == null) { - sender.sendMessage(TextFormat.RED + plugin.getI18n().get("need_secret_key")); - return; - } - - if (plugin.getServerInformation() == null) { - sender.sendMessage(TextFormat.RED + plugin.getI18n().get("information_no_server")); - return; - } - - sender.sendMessage(TextFormat.GRAY + plugin.getI18n().get("information_title")); - sender.sendMessage(TextFormat.GRAY + plugin.getI18n().get("information_server", - plugin.getServerInformation().getServer().getName(), - plugin.getServerInformation().getAccount().getName())); - sender.sendMessage(TextFormat.GRAY + plugin.getI18n().get("information_currency", - plugin.getServerInformation().getAccount().getCurrency().getIso4217())); - sender.sendMessage(TextFormat.GRAY + plugin.getI18n().get("information_domain", - plugin.getServerInformation().getAccount().getDomain())); - } - - @Override - public String getDescription() { - return plugin.getI18n().get("usage_information"); - } -} diff --git a/nukkit/src/main/java/net/buycraft/plugin/nukkit/command/ReportCommand.java b/nukkit/src/main/java/net/buycraft/plugin/nukkit/command/ReportCommand.java deleted file mode 100644 index 9663d1bb..00000000 --- a/nukkit/src/main/java/net/buycraft/plugin/nukkit/command/ReportCommand.java +++ /dev/null @@ -1,58 +0,0 @@ -package net.buycraft.plugin.nukkit.command; - -import cn.nukkit.command.CommandSender; -import cn.nukkit.utils.TextFormat; -import net.buycraft.plugin.nukkit.BuycraftPlugin; -import net.buycraft.plugin.shared.util.ReportBuilder; - -import java.io.BufferedWriter; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardOpenOption; -import java.text.SimpleDateFormat; -import java.util.Date; - -public class ReportCommand implements Subcommand { - private final BuycraftPlugin plugin; - - public ReportCommand(BuycraftPlugin plugin) { - this.plugin = plugin; - } - - @Override - public void execute(final CommandSender sender, String[] args) { - sender.sendMessage(TextFormat.YELLOW + plugin.getI18n().get("report_wait")); - - plugin.getPlatform().executeAsync(() -> { - ReportBuilder builder = ReportBuilder.builder() - .client(plugin.getHttpClient()) - .configuration(plugin.getConfiguration()) - .platform(plugin.getPlatform()) - .duePlayerFetcher(plugin.getDuePlayerFetcher()) - .ip(plugin.getServer().getIp()) - .port(plugin.getServer().getPort()) - .serverOnlineMode(false) - .build(); - - SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss"); - String filename = "report-" + f.format(new Date()) + ".txt"; - Path p = plugin.getDataFolder().toPath().resolve(filename); - String generated = builder.generate(); - - try (BufferedWriter w = Files.newBufferedWriter(p, StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW)) { - w.write(generated); - sender.sendMessage(TextFormat.YELLOW + plugin.getI18n().get("report_saved", p.toAbsolutePath().toString())); - } catch (IOException e) { - sender.sendMessage(TextFormat.RED + plugin.getI18n().get("report_cant_save")); - plugin.getLogger().info(generated); - } - }); - } - - @Override - public String getDescription() { - return plugin.getI18n().get("usage_report"); - } -} diff --git a/nukkit/src/main/java/net/buycraft/plugin/nukkit/command/SecretSubcommand.java b/nukkit/src/main/java/net/buycraft/plugin/nukkit/command/SecretSubcommand.java deleted file mode 100644 index ff6242e1..00000000 --- a/nukkit/src/main/java/net/buycraft/plugin/nukkit/command/SecretSubcommand.java +++ /dev/null @@ -1,67 +0,0 @@ -package net.buycraft.plugin.nukkit.command; - -import cn.nukkit.command.CommandSender; -import cn.nukkit.command.ConsoleCommandSender; -import cn.nukkit.utils.TextFormat; -import net.buycraft.plugin.BuyCraftAPI; -import net.buycraft.plugin.data.responses.ServerInformation; -import net.buycraft.plugin.nukkit.BuycraftPlugin; - -import java.io.IOException; - -public class SecretSubcommand implements Subcommand { - private final BuycraftPlugin plugin; - - public SecretSubcommand(final BuycraftPlugin plugin) { - this.plugin = plugin; - } - - @Override - public void execute(final CommandSender sender, final String[] args) { - if (!(sender instanceof ConsoleCommandSender)) { - sender.sendMessage(TextFormat.RED + plugin.getI18n().get("secret_console_only")); - return; - } - - if (args.length != 1) { - sender.sendMessage(TextFormat.RED + plugin.getI18n().get("secret_need_key")); - return; - } - - plugin.getPlatform().executeAsync(() -> { - String currentKey = plugin.getConfiguration().getServerKey(); - BuyCraftAPI client = BuyCraftAPI.create(args[0], plugin.getHttpClient()); - try { - plugin.updateInformation(client); - } catch (IOException e) { - plugin.getLogger().error("Unable to verify secret", e); - sender.sendMessage(TextFormat.RED + plugin.getI18n().get("secret_does_not_work")); - return; - } - - ServerInformation information = plugin.getServerInformation(); - plugin.setApiClient(client); - plugin.getConfiguration().setServerKey(args[0]); - try { - plugin.saveConfiguration(); - } catch (IOException e) { - sender.sendMessage(TextFormat.RED + plugin.getI18n().get("secret_cant_be_saved")); - } - - sender.sendMessage(TextFormat.GREEN + plugin.getI18n().get("secret_success", - information.getServer().getName(), information.getAccount().getName())); - - boolean repeatChecks = false; - if (currentKey.equals("INVALID")) { - repeatChecks = true; - } - - plugin.getDuePlayerFetcher().run(repeatChecks); - }); - } - - @Override - public String getDescription() { - return "Sets the secret key to use for this server."; - } -} diff --git a/nukkit/src/main/java/net/buycraft/plugin/nukkit/command/Subcommand.java b/nukkit/src/main/java/net/buycraft/plugin/nukkit/command/Subcommand.java deleted file mode 100644 index 8f4ce6c0..00000000 --- a/nukkit/src/main/java/net/buycraft/plugin/nukkit/command/Subcommand.java +++ /dev/null @@ -1,9 +0,0 @@ -package net.buycraft.plugin.nukkit.command; - -import cn.nukkit.command.CommandSender; - -public interface Subcommand { - void execute(CommandSender sender, String[] args); - - String getDescription(); -} diff --git a/nukkit/src/main/java/net/buycraft/plugin/nukkit/logging/LoggerUtils.java b/nukkit/src/main/java/net/buycraft/plugin/nukkit/logging/LoggerUtils.java deleted file mode 100644 index 700750d2..00000000 --- a/nukkit/src/main/java/net/buycraft/plugin/nukkit/logging/LoggerUtils.java +++ /dev/null @@ -1,21 +0,0 @@ -package net.buycraft.plugin.nukkit.logging; - -import cn.nukkit.plugin.PluginLogger; - -import java.util.logging.Level; - -public class LoggerUtils { - private final PluginLogger logger; - - public LoggerUtils(final PluginLogger logger) { - this.logger = logger; - } - - public void log(Level level, String message) { - log(level, message, null); - } - - public void log(Level level, String message, Throwable e) { - logger.info(message, e); - } -} diff --git a/nukkit/src/main/java/net/buycraft/plugin/nukkit/util/VersionCheck.java b/nukkit/src/main/java/net/buycraft/plugin/nukkit/util/VersionCheck.java deleted file mode 100644 index 62986f12..00000000 --- a/nukkit/src/main/java/net/buycraft/plugin/nukkit/util/VersionCheck.java +++ /dev/null @@ -1,64 +0,0 @@ -package net.buycraft.plugin.nukkit.util; - -import cn.nukkit.event.EventHandler; -import cn.nukkit.event.Listener; -import cn.nukkit.event.player.PlayerJoinEvent; -import cn.nukkit.utils.TextFormat; -import net.buycraft.plugin.data.responses.Version; -import net.buycraft.plugin.nukkit.BuycraftPlugin; -import net.buycraft.plugin.shared.util.VersionUtil; - -import java.io.IOException; -import java.util.concurrent.TimeUnit; - -import static net.buycraft.plugin.shared.util.VersionUtil.isVersionGreater; - -public class VersionCheck implements Listener { - private final BuycraftPlugin plugin; - private final String pluginVersion; - private final String secret; - private Version lastKnownVersion; - private boolean upToDate = true; - - public VersionCheck(final BuycraftPlugin plugin, final String pluginVersion, final String secret) { - this.plugin = plugin; - this.pluginVersion = pluginVersion; - this.secret = secret; - } - - public void verify() throws IOException { - if (pluginVersion.endsWith("-SNAPSHOT")) { - return; // SNAPSHOT versions ignore updates - } - - lastKnownVersion = VersionUtil.getVersion(plugin.getHttpClient(), "nukkit", secret); - if (lastKnownVersion == null) { - return; - } - - // Compare versions - String latestVersionString = lastKnownVersion.getVersion(); - if (!latestVersionString.equals(pluginVersion)) { - upToDate = !isVersionGreater(pluginVersion, latestVersionString); - if (!upToDate) { - plugin.getLogger().info(plugin.getI18n().get("update_available", lastKnownVersion.getVersion())); - } - } - } - - @EventHandler - public void onPostLogin(final PlayerJoinEvent event) { - if (event.getPlayer().hasPermission("buycraft.admin") && !upToDate) { - plugin.getPlatform().executeAsyncLater(() -> - event.getPlayer().sendMessage(TextFormat.YELLOW + plugin.getI18n().get("update_available", lastKnownVersion.getVersion())), 3, TimeUnit.SECONDS); - } - } - - public Version getLastKnownVersion() { - return this.lastKnownVersion; - } - - public boolean isUpToDate() { - return this.upToDate; - } -} diff --git a/nukkit/src/main/resources/plugin.yml b/nukkit/src/main/resources/plugin.yml deleted file mode 100644 index e82bbaac..00000000 --- a/nukkit/src/main/resources/plugin.yml +++ /dev/null @@ -1,9 +0,0 @@ -name: BuycraftX -main: net.buycraft.plugin.nukkit.BuycraftPlugin -version: "${project.version}" -author: Buycraft -api: [1.0.0, 2.0.0] -commands: - tebex: - aliases: [buycraft] - description: Main command for the Tebex plugin. \ No newline at end of file diff --git a/pom.xml b/pom.xml index 42df04dd..e749372e 100644 --- a/pom.xml +++ b/pom.xml @@ -12,11 +12,8 @@ bukkit-shared bukkit-pre-1.13 bukkit-post-1.13 - sponge bungeecord plugin-shared - nukkit - velocity diff --git a/sponge/pom.xml b/sponge/pom.xml deleted file mode 100644 index c378e720..00000000 --- a/sponge/pom.xml +++ /dev/null @@ -1,139 +0,0 @@ - - - - BuycraftX - net.buycraft - 12.0.7 - - 4.0.0 - - buycraftx-sponge - - - - - org.apache.maven.plugins - maven-shade-plugin - 2.4 - - - - com.google.code.gson - com.google.guava - org.slf4j - - - - - okhttp3 - net.buycraft.plugin.internal.okhttp3 - - - okio - net.buycraft.plugin.internal.okio - - - retrofit2 - net.buycraft.plugin.internal.retrofit2 - - - com.fasterxml.jackson - net.buycraft.plugin.internal.jackson - - - false - - - - package - - shade - - - - - - de.icongmbh.oss.maven.plugins - javassist-maven-plugin - 1.1.0 - - false - - - org.kitteh.craftirc.sponge.util.versioning.Transform - - - version - ${project.version} - - - - - - - - process-classes - - javassist - - - - - - net.buycraft - buycraftx-sponge - ${project.version} - - - - - com.google.code.maven-replacer-plugin - replacer - 1.5.3 - - - prepare-package - - replace - - - ${project.basedir}/target/classes/mcmod.info - SET_BY_MAGIC - ${project.version} - - - - - - - - - - sponge-repo - https://repo.spongepowered.org/maven - - - - - - org.spongepowered - spongeapi - 7.0.0 - provided - - - net.buycraft - buycraftx-plugin-shared - ${project.parent.version} - compile - - - de.icongmbh.oss.maven.plugins - javassist-maven-plugin - 1.1.0 - provided - - - - diff --git a/sponge/src/main/java/net/buycraft/plugin/sponge/BuycraftListener.java b/sponge/src/main/java/net/buycraft/plugin/sponge/BuycraftListener.java deleted file mode 100644 index 675e29f3..00000000 --- a/sponge/src/main/java/net/buycraft/plugin/sponge/BuycraftListener.java +++ /dev/null @@ -1,51 +0,0 @@ -package net.buycraft.plugin.sponge; - -import net.buycraft.plugin.data.QueuedPlayer; -import net.buycraft.plugin.data.ServerEvent; -import org.spongepowered.api.event.Listener; -import org.spongepowered.api.event.network.ClientConnectionEvent; - -import java.util.Date; - -public class BuycraftListener { - private final BuycraftPlugin plugin; - - public BuycraftListener(final BuycraftPlugin plugin) { - this.plugin = plugin; - } - - @Listener - public void onPlayerJoinEvent(ClientConnectionEvent.Join event) { - if (plugin.getApiClient() == null) { - return; - } - - plugin.getServerEventSenderTask().queueEvent(new ServerEvent( - event.getTargetEntity().getUniqueId().toString().replace("-", ""), - event.getTargetEntity().getName(), - event.getTargetEntity().getConnection().getAddress().getAddress().getHostAddress(), - ServerEvent.JOIN_EVENT, - new Date() - )); - - QueuedPlayer qp = plugin.getDuePlayerFetcher().fetchAndRemoveDuePlayer(event.getTargetEntity().getName()); - if (qp != null) { - plugin.getPlayerJoinCheckTask().queue(qp); - } - } - - @Listener - public void onPlayerQuitEvent(ClientConnectionEvent.Disconnect event) { - if (plugin.getApiClient() == null) { - return; - } - - plugin.getServerEventSenderTask().queueEvent(new ServerEvent( - event.getTargetEntity().getUniqueId().toString().replace("-", ""), - event.getTargetEntity().getName(), - event.getTargetEntity().getConnection().getAddress().getAddress().getHostAddress(), - ServerEvent.LEAVE_EVENT, - new Date() - )); - } -} diff --git a/sponge/src/main/java/net/buycraft/plugin/sponge/BuycraftPlugin.java b/sponge/src/main/java/net/buycraft/plugin/sponge/BuycraftPlugin.java deleted file mode 100644 index 4a66d594..00000000 --- a/sponge/src/main/java/net/buycraft/plugin/sponge/BuycraftPlugin.java +++ /dev/null @@ -1,407 +0,0 @@ -package net.buycraft.plugin.sponge; - -import com.google.gson.JsonParseException; -import com.google.inject.Inject; -import com.sun.net.httpserver.HttpServer; -import net.buycraft.plugin.BuyCraftAPI; -import net.buycraft.plugin.IBuycraftPlatform; -import net.buycraft.plugin.data.responses.ServerInformation; -import net.buycraft.plugin.execution.DuePlayerFetcher; -import net.buycraft.plugin.execution.ServerEventSenderTask; -import net.buycraft.plugin.execution.placeholder.NamePlaceholder; -import net.buycraft.plugin.execution.placeholder.PlaceholderManager; -import net.buycraft.plugin.execution.placeholder.UuidPlaceholder; -import net.buycraft.plugin.execution.strategy.CommandExecutor; -import net.buycraft.plugin.execution.strategy.PostCompletedCommandsTask; -import net.buycraft.plugin.execution.strategy.QueuedCommandExecutor; -import net.buycraft.plugin.shared.Setup; -import net.buycraft.plugin.shared.config.BuycraftConfiguration; -import net.buycraft.plugin.shared.config.BuycraftI18n; -import net.buycraft.plugin.shared.config.signs.BuyNowSignLayout; -import net.buycraft.plugin.shared.config.signs.RecentPurchaseSignLayout; -import net.buycraft.plugin.shared.config.signs.storage.BuyNowSignStorage; -import net.buycraft.plugin.shared.config.signs.storage.RecentPurchaseSignStorage; -import net.buycraft.plugin.shared.tasks.ListingUpdateTask; -import net.buycraft.plugin.shared.tasks.PlayerJoinCheckTask; -import net.buycraft.plugin.shared.util.AnalyticsSend; -import net.buycraft.plugin.sponge.command.*; -import net.buycraft.plugin.sponge.httplistener.Handler; -import net.buycraft.plugin.sponge.logging.LoggerUtils; -import net.buycraft.plugin.sponge.signs.buynow.BuyNowSignListener; -import net.buycraft.plugin.sponge.signs.purchases.RecentPurchaseSignListener; -import net.buycraft.plugin.sponge.tasks.BuyNowSignUpdater; -import net.buycraft.plugin.sponge.tasks.SignUpdater; -import net.buycraft.plugin.sponge.util.VersionCheck; -import okhttp3.OkHttpClient; -import org.slf4j.Logger; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.command.args.GenericArguments; -import org.spongepowered.api.command.spec.CommandSpec; -import org.spongepowered.api.config.ConfigDir; -import org.spongepowered.api.event.Listener; -import org.spongepowered.api.event.game.state.GamePreInitializationEvent; -import org.spongepowered.api.event.game.state.GameStoppingServerEvent; -import org.spongepowered.api.plugin.Plugin; -import org.spongepowered.api.text.Text; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.nio.charset.StandardCharsets; -import java.nio.file.FileAlreadyExistsException; -import java.nio.file.Files; -import java.nio.file.NoSuchFileException; -import java.nio.file.Path; -import java.util.concurrent.TimeUnit; - -@Plugin(id = "buycraft", name = "Buycraft", version = BuycraftPlugin.MAGIC_VERSION) -public class BuycraftPlugin { - static final String MAGIC_VERSION = "SET_BY_MAGIC"; - private final PlaceholderManager placeholderManager = new PlaceholderManager(); - private final BuycraftConfiguration configuration = new BuycraftConfiguration(); - - private BuyCraftAPI apiClient; - private DuePlayerFetcher duePlayerFetcher; - private ListingUpdateTask listingUpdateTask; - private ServerInformation serverInformation; - private RecentPurchaseSignStorage recentPurchaseSignStorage; - private BuyNowSignStorage buyNowSignStorage; - private OkHttpClient httpClient; - private IBuycraftPlatform platform; - private CommandExecutor commandExecutor; - @Inject - private Logger logger; - private LoggerUtils loggerUtils; - @Inject - @ConfigDir(sharedRoot = false) - private Path baseDirectory; - private RecentPurchaseSignLayout recentPurchaseSignLayout = RecentPurchaseSignLayout.DEFAULT; - private BuyNowSignLayout buyNowSignLayout = BuyNowSignLayout.DEFAULT; - private BuycraftI18n i18n; - private PostCompletedCommandsTask completedCommandsTask; - private PlayerJoinCheckTask playerJoinCheckTask; - private ServerEventSenderTask serverEventSenderTask; - - @Listener - public void onGamePreInitializationEvent(GamePreInitializationEvent event) { - platform = new SpongeBuycraftPlatform(this); - try { - try { - Files.createDirectory(baseDirectory); - } catch (FileAlreadyExistsException ignored) { - } - Path configPath = baseDirectory.resolve("config.properties"); - try { - configuration.load(configPath); - } catch (NoSuchFileException e) { - // Save defaults - configuration.fillDefaults(); - configuration.save(configPath); - } - } catch (IOException e) { - getLogger().error("Unable to load configuration! The plugin will disable itself now.", e); - return; - } - i18n = configuration.createI18n(); - httpClient = Setup.okhttp(baseDirectory.resolve("cache").toFile()); - // Check for latest version. - String curVersion = getClass().getAnnotation(Plugin.class).version(); - if (configuration.isCheckForUpdates()) { - VersionCheck check = new VersionCheck(this, curVersion, configuration.getServerKey()); - try { - check.verify(); - } catch (IOException e) { - getLogger().error("Can't check for updates", e); - } - Sponge.getEventManager().registerListeners(this, check); - } - String serverKey = configuration.getServerKey(); - if (serverKey == null || serverKey.equals("INVALID")) { - getLogger().info("Looks like this is a fresh setup. Get started by using 'tebex secret ' in the console."); - } else { - getLogger().info("Validating your server key..."); - BuyCraftAPI client = BuyCraftAPI.create(configuration.getServerKey(), httpClient); - try { - updateInformation(client); - } catch (IOException e) { - getLogger().error(String.format("We can't check if your server can connect to Tebex: %s", e.getMessage())); - } - apiClient = client; - } - Integer pushCommandsPort = configuration.getPushCommandsPort(); - if (pushCommandsPort != null) { - this.initializeHttpListener(pushCommandsPort); - } - placeholderManager.addPlaceholder(new NamePlaceholder()); - placeholderManager.addPlaceholder(new UuidPlaceholder()); - platform.executeAsyncLater(duePlayerFetcher = new DuePlayerFetcher(platform, configuration.isVerbose()), 1, TimeUnit.SECONDS); - completedCommandsTask = new PostCompletedCommandsTask(platform); - commandExecutor = new QueuedCommandExecutor(platform, completedCommandsTask); - Sponge.getScheduler().createTaskBuilder().intervalTicks(1).delayTicks(1).execute((Runnable) commandExecutor).submit(this); - Sponge.getScheduler().createTaskBuilder().intervalTicks(20).delayTicks(20).async().execute(completedCommandsTask).submit(this); - playerJoinCheckTask = new PlayerJoinCheckTask(platform); - Sponge.getScheduler().createTaskBuilder().intervalTicks(20).delayTicks(20).execute(playerJoinCheckTask).submit(this); - serverEventSenderTask = new ServerEventSenderTask(platform, configuration.isVerbose()); - Sponge.getScheduler().createTaskBuilder().interval(1, TimeUnit.MINUTES).async().delay(1, TimeUnit.MINUTES).execute(serverEventSenderTask).submit(this); - listingUpdateTask = new ListingUpdateTask(platform, null); - if (apiClient != null) { - getLogger().info("Fetching all server packages..."); - listingUpdateTask.run(); - } - Sponge.getScheduler().createTaskBuilder() - .delayTicks(20 * 60 * 20) - .intervalTicks(20 * 60 * 20) - .execute(listingUpdateTask).async().submit(this); - - recentPurchaseSignStorage = new RecentPurchaseSignStorage(); - try { - recentPurchaseSignStorage.load(baseDirectory.resolve("purchase_signs.json")); - } catch (IOException | JsonParseException e) { - logger.warn("Can't load purchase signs, continuing anyway", e); - } - - buyNowSignStorage = new BuyNowSignStorage(); - try { - buyNowSignStorage.load(baseDirectory.resolve("buy_now_signs.json")); - } catch (IOException | JsonParseException e) { - logger.warn("Can't load purchase signs, continuing anyway", e); - } - - try { - Path signLayoutDirectory = baseDirectory.resolve("sign_layouts"); - try { - Files.createDirectory(signLayoutDirectory); - } catch (FileAlreadyExistsException ignored) { - } - - Path rpPath = signLayoutDirectory.resolve("recentpurchase.txt"); - Path bnPath = signLayoutDirectory.resolve("buynow.txt"); - - try { - Files.copy(getClass().getClassLoader().getResourceAsStream("sign_layouts/recentpurchase.txt"), rpPath); - } catch (FileAlreadyExistsException ignored) { - } - try { - Files.copy(getClass().getClassLoader().getResourceAsStream("sign_layouts/buynow.txt"), bnPath); - } catch (FileAlreadyExistsException ignored) { - } - - recentPurchaseSignLayout = new RecentPurchaseSignLayout(Files.readAllLines(rpPath, StandardCharsets.UTF_8)); - buyNowSignLayout = new BuyNowSignLayout(Files.readAllLines(bnPath, StandardCharsets.UTF_8)); - } catch (IOException e) { - getLogger().error("Unable to load sign layouts", e); - } - - Sponge.getScheduler().createTaskBuilder() - .delay(1, TimeUnit.SECONDS) - .interval(15, TimeUnit.MINUTES) - .execute(new SignUpdater(this)) - .submit(this); - - Sponge.getScheduler().createTaskBuilder() - .delay(1, TimeUnit.SECONDS) - .interval(15, TimeUnit.MINUTES) - .execute(new BuyNowSignUpdater(this)) - .submit(this); - - if (serverInformation != null) { - Sponge.getScheduler().createTaskBuilder() - .delay(0, TimeUnit.SECONDS) - .interval(1, TimeUnit.DAYS) - .execute(() -> { - try { - AnalyticsSend.postServerInformation(httpClient, configuration.getServerKey(), platform, - Sponge.getServer().getOnlineMode()); - } catch (IOException e) { - getLogger().warn("Can't send analytics", e); - } - }) - .submit(this); - } - - Sponge.getEventManager().registerListeners(this, new BuycraftListener(this)); - Sponge.getEventManager().registerListeners(this, new RecentPurchaseSignListener(this)); - Sponge.getEventManager().registerListeners(this, new BuyNowSignListener(this)); - - Sponge.getCommandManager().register(this, buildCommands(), "tebex", "buycraft"); - Sponge.getCommandManager().register(this, CommandSpec.builder() - .description(Text.of(i18n.get("usage_sponge_listing"))) - .executor(new ListPackagesCmd(this)) - .build(), configuration.getBuyCommandName()); - } - - @Listener - public void onGameStoppingServerEvent(GameStoppingServerEvent event) { - try { - recentPurchaseSignStorage.save(baseDirectory.resolve("purchase_signs.json")); - } catch (IOException e) { - logger.error("Can't save purchase signs, continuing anyway"); - } - try { - buyNowSignStorage.save(baseDirectory.resolve("buy_now_signs.json")); - } catch (IOException e) { - logger.error("Can't save purchase signs, continuing anyway"); - } - completedCommandsTask.flush(); - } - - private void initializeHttpListener(Integer port) { - try { - HttpServer server = HttpServer.create(new InetSocketAddress(port), 50); - server.createContext("/", new Handler(this)); - server.start(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - private CommandSpec buildCommands() { - CommandSpec refresh = CommandSpec.builder() - .description(Text.of(i18n.get("usage_refresh"))) - .permission("buycraft.admin") - .executor(new RefreshCmd(this)) - .build(); - CommandSpec secret = CommandSpec.builder() - .description(Text.of(i18n.get("usage_secret"))) - .permission("buycraft.admin") - .arguments(GenericArguments.onlyOne(GenericArguments.string(Text.of("secret")))) - .executor(new SecretCmd(this)) - .build(); - CommandSpec report = CommandSpec.builder() - .description(Text.of(i18n.get("usage_report"))) - .executor(new ReportCmd(this)) - .permission("buycraft.admin") - .build(); - CommandSpec info = CommandSpec.builder() - .description(Text.of(i18n.get("usage_information"))) - .executor(new InfoCmd(this)) - .build(); - CommandSpec forcecheck = CommandSpec.builder() - .description(Text.of(i18n.get("usage_forcecheck"))) - .executor(new ForceCheckCmd(this)) - .permission("buycraft.admin") - .build(); - CommandSpec coupon = buildCouponCommands(); - return CommandSpec.builder() - .description(Text.of("Main command for the Tebex plugin.")) - .child(report, "report") - .child(secret, "secret") - .child(refresh, "refresh") - .child(info, "info") - .child(forcecheck, "forcecheck") - .child(coupon, "coupon") - .build(); - } - - private CommandSpec buildCouponCommands() { - CouponCmd cmd = new CouponCmd(this); - CommandSpec create = CommandSpec.builder() - .executor(cmd::createCoupon) - .arguments(GenericArguments.allOf(GenericArguments.string(Text.of("args")))) - .build(); - CommandSpec delete = CommandSpec.builder() - .executor(cmd::deleteCoupon) - .arguments(GenericArguments.onlyOne(GenericArguments.string(Text.of("code")))) - .build(); - return CommandSpec.builder() - .description(Text.of(i18n.get("usage_coupon"))) - .permission("buycraft.admin") - .child(create, "create") - .child(delete, "delete") - .build(); - } - - public void saveConfiguration() throws IOException { - configuration.save(baseDirectory.resolve("config.properties")); - } - - public void updateInformation(BuyCraftAPI client) throws IOException { - serverInformation = client.getServerInformation().execute().body(); - if (!configuration.isBungeeCord() && Sponge.getServer().getOnlineMode() != serverInformation.getAccount().isOnlineMode()) { - getLogger().warn("Your server and webstore online mode settings are mismatched. Unless you are using" + - " a proxy and server combination (such as BungeeCord/Spigot or LilyPad/Connect) that corrects UUIDs, then" + - " you may experience issues with packages not applying."); - getLogger().warn("If you have verified that your set up is correct, you can suppress this message by setting " + - "is-bungeecord=true in your BuycraftX config.properties."); - } - } - - public PlaceholderManager getPlaceholderManager() { - return this.placeholderManager; - } - - public BuycraftConfiguration getConfiguration() { - return this.configuration; - } - - public BuyCraftAPI getApiClient() { - return this.apiClient; - } - - public void setApiClient(final BuyCraftAPI apiClient) { - this.apiClient = apiClient; - } - - public DuePlayerFetcher getDuePlayerFetcher() { - return this.duePlayerFetcher; - } - - public ListingUpdateTask getListingUpdateTask() { - return this.listingUpdateTask; - } - - public ServerInformation getServerInformation() { - return this.serverInformation; - } - - public RecentPurchaseSignStorage getRecentPurchaseSignStorage() { - return this.recentPurchaseSignStorage; - } - - public BuyNowSignStorage getBuyNowSignStorage() { - return this.buyNowSignStorage; - } - - public OkHttpClient getHttpClient() { - return this.httpClient; - } - - public IBuycraftPlatform getPlatform() { - return this.platform; - } - - public CommandExecutor getCommandExecutor() { - return this.commandExecutor; - } - - public Logger getLogger() { - return this.logger; - } - - public LoggerUtils getLoggerUtils() { - return this.loggerUtils; - } - - public Path getBaseDirectory() { - return this.baseDirectory; - } - - public RecentPurchaseSignLayout getRecentPurchaseSignLayout() { - return this.recentPurchaseSignLayout; - } - - public BuyNowSignLayout getBuyNowSignLayout() { - return this.buyNowSignLayout; - } - - public BuycraftI18n getI18n() { - return this.i18n; - } - - public PlayerJoinCheckTask getPlayerJoinCheckTask() { - return this.playerJoinCheckTask; - } - - public ServerEventSenderTask getServerEventSenderTask() { - return serverEventSenderTask; - } -} diff --git a/sponge/src/main/java/net/buycraft/plugin/sponge/SpongeBuycraftPlatform.java b/sponge/src/main/java/net/buycraft/plugin/sponge/SpongeBuycraftPlatform.java deleted file mode 100644 index 0407a30c..00000000 --- a/sponge/src/main/java/net/buycraft/plugin/sponge/SpongeBuycraftPlatform.java +++ /dev/null @@ -1,109 +0,0 @@ -package net.buycraft.plugin.sponge; - -import net.buycraft.plugin.BuyCraftAPI; -import net.buycraft.plugin.IBuycraftPlatform; -import net.buycraft.plugin.UuidUtil; -import net.buycraft.plugin.data.QueuedPlayer; -import net.buycraft.plugin.data.responses.ServerInformation; -import net.buycraft.plugin.execution.placeholder.PlaceholderManager; -import net.buycraft.plugin.execution.strategy.CommandExecutor; -import net.buycraft.plugin.platform.PlatformInformation; -import net.buycraft.plugin.platform.PlatformType; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.entity.living.player.Player; -import org.spongepowered.api.plugin.Plugin; - -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import java.util.logging.Level; - -public class SpongeBuycraftPlatform implements IBuycraftPlatform { - private final BuycraftPlugin plugin; - - public SpongeBuycraftPlatform(final BuycraftPlugin plugin) { - this.plugin = plugin; - } - - @Override - public BuyCraftAPI getApiClient() { - return plugin.getApiClient(); - } - - @Override - public PlaceholderManager getPlaceholderManager() { - return plugin.getPlaceholderManager(); - } - - @Override - public void dispatchCommand(String command) { - Sponge.getGame().getCommandManager().process(Sponge.getServer().getConsole().getCommandSource().get(), command); - } - - @Override - public void executeAsync(Runnable runnable) { - Sponge.getScheduler().createTaskBuilder().execute(runnable).async().submit(plugin); - } - - @Override - public void executeAsyncLater(Runnable runnable, long time, TimeUnit unit) { - Sponge.getScheduler().createTaskBuilder().execute(runnable).async().delay(time, unit).submit(plugin); - } - - @Override - public void executeBlocking(Runnable runnable) { - Sponge.getScheduler().createTaskBuilder().execute(runnable).submit(plugin); - } - - @Override - public void executeBlockingLater(Runnable runnable, long time, TimeUnit unit) { - Sponge.getScheduler().createTaskBuilder().execute(runnable).delay(time, unit).submit(plugin); - } - - private Optional getPlayer(QueuedPlayer player) { - if (player.getUuid() != null && (plugin.getConfiguration().isBungeeCord() || Sponge.getServer().getOnlineMode())) { - return Sponge.getServer().getPlayer(UuidUtil.mojangUuidToJavaUuid(player.getUuid())); - } - return Sponge.getServer().getPlayer(player.getName()); - } - - @Override - public boolean isPlayerOnline(QueuedPlayer player) { - return getPlayer(player).isPresent(); - } - - @Override - public int getFreeSlots(QueuedPlayer player) { - return getPlayer(player).map(value -> Math.max(0, 36 - value.getInventory().size())).orElse(-1); - } - - @Override - public void log(Level level, String message) { - plugin.getLogger().info(message); - } - - @Override - public void log(Level level, String message, Throwable throwable) { - plugin.getLogger().info(message, throwable); - } - - @Override - public CommandExecutor getExecutor() { - return plugin.getCommandExecutor(); - } - - @Override - public PlatformInformation getPlatformInformation() { - return new PlatformInformation(PlatformType.SPONGE, Sponge.getPlatform().getImplementation().getName() + " " + - Sponge.getPlatform().getImplementation().getVersion().orElse("UNKNOWN")); - } - - @Override - public String getPluginVersion() { - return plugin.getClass().getAnnotation(Plugin.class).version(); - } - - @Override - public ServerInformation getServerInformation() { - return plugin.getServerInformation(); - } -} diff --git a/sponge/src/main/java/net/buycraft/plugin/sponge/command/CouponCmd.java b/sponge/src/main/java/net/buycraft/plugin/sponge/command/CouponCmd.java deleted file mode 100644 index 3b63965b..00000000 --- a/sponge/src/main/java/net/buycraft/plugin/sponge/command/CouponCmd.java +++ /dev/null @@ -1,73 +0,0 @@ -package net.buycraft.plugin.sponge.command; - -import net.buycraft.plugin.data.Coupon; -import net.buycraft.plugin.shared.util.CouponUtil; -import net.buycraft.plugin.sponge.BuycraftPlugin; -import org.spongepowered.api.command.CommandException; -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.command.CommandSource; -import org.spongepowered.api.command.args.CommandContext; -import org.spongepowered.api.text.Text; -import org.spongepowered.api.text.format.TextColors; - -import java.io.IOException; -import java.util.Collection; -import java.util.Optional; - -public class CouponCmd { - private static final int COUPON_PAGE_LIMIT = 10; - private final BuycraftPlugin plugin; - - public CouponCmd(final BuycraftPlugin plugin) { - this.plugin = plugin; - } - - public CommandResult createCoupon(CommandSource source, CommandContext ctx) throws CommandException { - Collection argsList = ctx.getAll("args"); - String[] argsArray = argsList.toArray(new String[0]); - final Coupon coupon; - try { - coupon = CouponUtil.parseArguments(argsArray); - } catch (Exception e) { - source.sendMessage(Text.builder(plugin.getI18n().get("coupon_creation_arg_parse_failure", e.getMessage())) - .color(TextColors.RED) - .build()); - return CommandResult.empty(); - } - - plugin.getPlatform().executeAsync(() -> { - try { - plugin.getApiClient().createCoupon(coupon).execute(); - source.sendMessage(Text.builder(plugin.getI18n().get("coupon_creation_success", coupon.getCode())) - .color(TextColors.GREEN) - .build()); - } catch (IOException e) { - source.sendMessage(Text.builder(plugin.getI18n().get("generic_api_operation_error")) - .color(TextColors.RED) - .build()); - } - }); - - return CommandResult.empty(); - } - - public CommandResult deleteCoupon(CommandSource source, CommandContext ctx) throws CommandException { - Optional codeOptional = ctx.getOne("code"); - if (!codeOptional.isPresent()) { - source.sendMessage(Text.builder(plugin.getI18n().get("no_coupon_specified")).color(TextColors.RED).build()); - return CommandResult.empty(); - } - final String code = codeOptional.get(); - - plugin.getPlatform().executeAsync(() -> { - try { - plugin.getApiClient().deleteCoupon(code).execute(); - source.sendMessage(Text.builder(plugin.getI18n().get("coupon_deleted")).color(TextColors.GREEN).build()); - } catch (IOException e) { - source.sendMessage(Text.builder(e.getMessage()).color(TextColors.RED).build()); - } - }); - - return CommandResult.empty(); - } -} diff --git a/sponge/src/main/java/net/buycraft/plugin/sponge/command/ForceCheckCmd.java b/sponge/src/main/java/net/buycraft/plugin/sponge/command/ForceCheckCmd.java deleted file mode 100644 index 1ced1c75..00000000 --- a/sponge/src/main/java/net/buycraft/plugin/sponge/command/ForceCheckCmd.java +++ /dev/null @@ -1,36 +0,0 @@ -package net.buycraft.plugin.sponge.command; - -import net.buycraft.plugin.sponge.BuycraftPlugin; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.command.CommandException; -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.command.CommandSource; -import org.spongepowered.api.command.args.CommandContext; -import org.spongepowered.api.command.spec.CommandExecutor; -import org.spongepowered.api.text.Text; -import org.spongepowered.api.text.format.TextColors; - -public class ForceCheckCmd implements CommandExecutor { - private final BuycraftPlugin plugin; - - public ForceCheckCmd(final BuycraftPlugin plugin) { - this.plugin = plugin; - } - - @Override - public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException { - if (plugin.getApiClient() == null) { - sender.sendMessage(Text.builder(plugin.getI18n().get("need_secret_key")).color(TextColors.RED).build()); - return CommandResult.success(); - } - - if (plugin.getDuePlayerFetcher().inProgress()) { - sender.sendMessage(Text.builder(plugin.getI18n().get("already_checking_for_purchases")).color(TextColors.RED).build()); - return CommandResult.success(); - } - - Sponge.getScheduler().createTaskBuilder().execute(() -> plugin.getDuePlayerFetcher().run(false)).async().submit(plugin); - sender.sendMessage(Text.builder(plugin.getI18n().get("forcecheck_queued")).color(TextColors.GREEN).build()); - return CommandResult.success(); - } -} diff --git a/sponge/src/main/java/net/buycraft/plugin/sponge/command/InfoCmd.java b/sponge/src/main/java/net/buycraft/plugin/sponge/command/InfoCmd.java deleted file mode 100644 index 9dfc0c66..00000000 --- a/sponge/src/main/java/net/buycraft/plugin/sponge/command/InfoCmd.java +++ /dev/null @@ -1,61 +0,0 @@ -package net.buycraft.plugin.sponge.command; - -import net.buycraft.plugin.sponge.BuycraftPlugin; -import org.spongepowered.api.command.CommandException; -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.command.CommandSource; -import org.spongepowered.api.command.args.CommandContext; -import org.spongepowered.api.command.spec.CommandExecutor; -import org.spongepowered.api.text.LiteralText; -import org.spongepowered.api.text.Text; -import org.spongepowered.api.text.action.TextActions; -import org.spongepowered.api.text.format.TextColors; - -import java.net.MalformedURLException; -import java.net.URL; - -public class InfoCmd implements CommandExecutor { - private final BuycraftPlugin plugin; - - public InfoCmd(final BuycraftPlugin plugin) { - this.plugin = plugin; - } - - @Override - public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException { - if (plugin.getApiClient() == null) { - sender.sendMessage(Text.builder(plugin.getI18n().get("generic_api_operation_error")).color(TextColors.RED).build()); - return CommandResult.success(); - } - - if (plugin.getServerInformation() == null) { - sender.sendMessage(Text.builder(plugin.getI18n().get("information_no_server")).color(TextColors.RED).build()); - return CommandResult.success(); - } - - String webstoreURL = plugin.getServerInformation().getAccount().getDomain(); - try { - LiteralText webstore = Text.builder(webstoreURL) - .color(TextColors.GREEN) - .onClick(TextActions.openUrl(new URL(webstoreURL))) - .onHover(TextActions.showText(Text.of(webstoreURL))) - .build(); - - LiteralText server = Text.builder(plugin.getServerInformation().getServer().getName()) - .color(TextColors.GREEN) - .build(); - - sender.sendMessages( - Text.builder(plugin.getI18n().get("information_title") + " ").color(TextColors.GRAY).build(), - Text.builder(plugin.getI18n().get("information_sponge_server") + " ").color(TextColors.GRAY).append(server).build(), - Text.builder(plugin.getI18n().get("information_currency", plugin.getServerInformation().getAccount().getCurrency().getIso4217())) - .color(TextColors.GRAY).build(), - Text.builder(plugin.getI18n().get("information_domain", "")).color(TextColors.GRAY).append(webstore).build() - ); - } catch (MalformedURLException e) { - e.printStackTrace(); - } - - return CommandResult.success(); - } -} diff --git a/sponge/src/main/java/net/buycraft/plugin/sponge/command/ListPackagesCmd.java b/sponge/src/main/java/net/buycraft/plugin/sponge/command/ListPackagesCmd.java deleted file mode 100644 index f679a207..00000000 --- a/sponge/src/main/java/net/buycraft/plugin/sponge/command/ListPackagesCmd.java +++ /dev/null @@ -1,70 +0,0 @@ -package net.buycraft.plugin.sponge.command; - -import com.google.common.collect.ImmutableList; -import net.buycraft.plugin.data.Package; -import net.buycraft.plugin.shared.util.Node; -import net.buycraft.plugin.sponge.BuycraftPlugin; -import net.buycraft.plugin.sponge.tasks.SendCheckoutLinkTask; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.command.CommandException; -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.command.CommandSource; -import org.spongepowered.api.command.args.CommandContext; -import org.spongepowered.api.command.spec.CommandExecutor; -import org.spongepowered.api.entity.living.player.Player; -import org.spongepowered.api.service.pagination.PaginationList; -import org.spongepowered.api.service.pagination.PaginationService; -import org.spongepowered.api.text.Text; -import org.spongepowered.api.text.action.TextActions; -import org.spongepowered.api.text.format.TextColors; - -import java.util.List; -import java.util.stream.Collectors; - -public class ListPackagesCmd implements CommandExecutor { - private final BuycraftPlugin plugin; - - public ListPackagesCmd(final BuycraftPlugin plugin) { - this.plugin = plugin; - } - - @Override - public CommandResult execute(CommandSource sender, CommandContext args) throws CommandException { - if (plugin.getApiClient() == null) { - sender.sendMessage(Text.builder(plugin.getI18n().get("generic_api_operation_error")).color(TextColors.RED).build()); - return CommandResult.success(); - } - - if (plugin.getListingUpdateTask().getListing() == null) { - sender.sendMessage(Text.builder("We're currently retrieving the listing. Sit tight!").color(TextColors.RED).build()); - return CommandResult.success(); - } - - sendPaginatedMessage(new Node(plugin.getListingUpdateTask().getListing().getCategories(), ImmutableList.of(), - plugin.getI18n().get("categories"), null), sender); - - return CommandResult.success(); - } - - private void sendPaginatedMessage(Node node, CommandSource source) { - PaginationService paginationService = Sponge.getServiceManager().provide(PaginationService.class).get(); - PaginationList.Builder builder = paginationService.builder(); - List contents = node.getSubcategories().stream() - .map(category -> Text.builder("> " + category.getName()).color(TextColors.GRAY).onClick(TextActions.executeCallback(commandSource -> { - if (commandSource instanceof Player) { - sendPaginatedMessage(node.getChild(category), source); - } - })).build()).collect(Collectors.toList()); - for (Package p : node.getPackages()) { - contents.add(Text.builder(p.getName()).color(TextColors.WHITE).append(Text.builder(" - ").color(TextColors.GRAY).build()) - .append(Text.builder("$x".replace("$", plugin.getServerInformation().getAccount().getCurrency().getSymbol()) - .replace("x", "" + p.getEffectivePrice())).color(TextColors.GREEN).build()) - .onClick(TextActions.executeCallback(commandSource -> { - if (commandSource instanceof Player) { - plugin.getPlatform().executeAsync(new SendCheckoutLinkTask(plugin, p.getId(), (Player) commandSource)); - } - })).build()); - } - builder.title(Text.builder(plugin.getI18n().get("sponge_listing")).color(TextColors.AQUA).build()).contents(contents).padding(Text.of("-")).sendTo(source); - } -} diff --git a/sponge/src/main/java/net/buycraft/plugin/sponge/command/RefreshCmd.java b/sponge/src/main/java/net/buycraft/plugin/sponge/command/RefreshCmd.java deleted file mode 100644 index 7a21fabc..00000000 --- a/sponge/src/main/java/net/buycraft/plugin/sponge/command/RefreshCmd.java +++ /dev/null @@ -1,29 +0,0 @@ -package net.buycraft.plugin.sponge.command; - -import net.buycraft.plugin.sponge.BuycraftPlugin; -import org.spongepowered.api.command.CommandException; -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.command.CommandSource; -import org.spongepowered.api.command.args.CommandContext; -import org.spongepowered.api.command.spec.CommandExecutor; -import org.spongepowered.api.text.Text; -import org.spongepowered.api.text.format.TextColors; - -public class RefreshCmd implements CommandExecutor { - private final BuycraftPlugin plugin; - - public RefreshCmd(final BuycraftPlugin plugin) { - this.plugin = plugin; - } - - @Override - public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { - if (plugin.getApiClient() == null) { - src.sendMessage(Text.builder(plugin.getI18n().get("need_secret_key")).color(TextColors.RED).build()); - } else { - plugin.getPlatform().executeAsync(plugin.getListingUpdateTask()); - src.sendMessage(Text.builder(plugin.getI18n().get("refresh_queued")).color(TextColors.GREEN).build()); - } - return CommandResult.success(); - } -} diff --git a/sponge/src/main/java/net/buycraft/plugin/sponge/command/ReportCmd.java b/sponge/src/main/java/net/buycraft/plugin/sponge/command/ReportCmd.java deleted file mode 100644 index c8300674..00000000 --- a/sponge/src/main/java/net/buycraft/plugin/sponge/command/ReportCmd.java +++ /dev/null @@ -1,64 +0,0 @@ -package net.buycraft.plugin.sponge.command; - -import net.buycraft.plugin.shared.util.ReportBuilder; -import net.buycraft.plugin.sponge.BuycraftPlugin; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.command.CommandException; -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.command.CommandSource; -import org.spongepowered.api.command.args.CommandContext; -import org.spongepowered.api.command.spec.CommandExecutor; -import org.spongepowered.api.text.Text; -import org.spongepowered.api.text.format.TextColors; - -import java.io.BufferedWriter; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardOpenOption; -import java.text.SimpleDateFormat; -import java.util.Date; - -public class ReportCmd implements CommandExecutor { - private final BuycraftPlugin plugin; - - public ReportCmd(final BuycraftPlugin plugin) { - this.plugin = plugin; - } - - @Override - public CommandResult execute(final CommandSource src, CommandContext args) throws CommandException { - src.sendMessage(Text.builder(plugin.getI18n().get("report_wait")).color(TextColors.RED).build()); - - plugin.getPlatform().executeAsync(() -> { - String serverIP = (Sponge.getServer().getBoundAddress().isPresent()) ? Sponge.getServer().getBoundAddress().get().getHostName() : "?"; - int serverPort = (Sponge.getServer().getBoundAddress().isPresent()) ? Sponge.getServer().getBoundAddress().get().getPort() : -1; - - ReportBuilder builder = ReportBuilder.builder() - .client(plugin.getHttpClient()) - .configuration(plugin.getConfiguration()) - .platform(plugin.getPlatform()) - .duePlayerFetcher(plugin.getDuePlayerFetcher()) - .ip(serverIP) - .port(serverPort) - .listingUpdateTask(plugin.getListingUpdateTask()) - .serverOnlineMode(Sponge.getServer().getOnlineMode()) - .build(); - - SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss"); - String filename = "report-" + f.format(new Date()) + ".txt"; - Path p = plugin.getBaseDirectory().resolve(filename); - String generated = builder.generate(); - - try (BufferedWriter w = Files.newBufferedWriter(p, StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW)) { - w.write(generated); - src.sendMessage(Text.builder(plugin.getI18n().get("report_saved", p.toAbsolutePath().toString())).color(TextColors.YELLOW).build()); - } catch (IOException e) { - src.sendMessage(Text.builder(plugin.getI18n().get("report_cant_save")).color(TextColors.RED).build()); - plugin.getLogger().info(generated); - } - }); - return CommandResult.success(); - } -} diff --git a/sponge/src/main/java/net/buycraft/plugin/sponge/command/SecretCmd.java b/sponge/src/main/java/net/buycraft/plugin/sponge/command/SecretCmd.java deleted file mode 100644 index de53a7dc..00000000 --- a/sponge/src/main/java/net/buycraft/plugin/sponge/command/SecretCmd.java +++ /dev/null @@ -1,66 +0,0 @@ -package net.buycraft.plugin.sponge.command; - -import net.buycraft.plugin.BuyCraftAPI; -import net.buycraft.plugin.data.responses.ServerInformation; -import net.buycraft.plugin.sponge.BuycraftPlugin; -import org.spongepowered.api.command.CommandException; -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.command.CommandSource; -import org.spongepowered.api.command.args.CommandContext; -import org.spongepowered.api.command.source.ConsoleSource; -import org.spongepowered.api.command.spec.CommandExecutor; -import org.spongepowered.api.text.Text; -import org.spongepowered.api.text.format.TextColors; - -import java.io.IOException; - -public class SecretCmd implements CommandExecutor { - private final BuycraftPlugin plugin; - - public SecretCmd(final BuycraftPlugin plugin) { - this.plugin = plugin; - } - - @Override - public CommandResult execute(final CommandSource src, final CommandContext args) throws CommandException { - if (!(src instanceof ConsoleSource)) { - src.sendMessage(Text.builder(plugin.getI18n().get("secret_console_only")).color(TextColors.RED).build()); - } else { - if (!args.getOne("secret").isPresent()) { - src.sendMessage(Text.builder(plugin.getI18n().get("secret_need_key")).color(TextColors.RED).build()); - } else { - plugin.getPlatform().executeAsync(() -> { - String currentKey = plugin.getConfiguration().getServerKey(); - BuyCraftAPI client = BuyCraftAPI.create((String) args.getOne("secret").get(), plugin.getHttpClient()); - try { - plugin.updateInformation(client); - } catch (IOException e) { - plugin.getLogger().error("Unable to verify secret", e); - src.sendMessage(Text.builder(plugin.getI18n().get("secret_does_not_work")).color(TextColors.RED).build()); - return; - } - - ServerInformation information = plugin.getServerInformation(); - plugin.setApiClient(client); - plugin.getListingUpdateTask().run(); - plugin.getConfiguration().setServerKey((String) args.getOne("secret").get()); - try { - plugin.saveConfiguration(); - } catch (IOException e) { - src.sendMessage(Text.builder(plugin.getI18n().get("secret_cant_be_saved")).color(TextColors.RED).build()); - } - src.sendMessage(Text.builder(plugin.getI18n().get("secret_success", - information.getServer().getName(), information.getAccount().getName())).color(TextColors.GREEN).build()); - - boolean repeatChecks = false; - if (currentKey.equals("INVALID")) { - repeatChecks = true; - } - - plugin.getDuePlayerFetcher().run(repeatChecks); - }); - } - } - return CommandResult.success(); - } -} diff --git a/sponge/src/main/java/net/buycraft/plugin/sponge/httplistener/Handler.java b/sponge/src/main/java/net/buycraft/plugin/sponge/httplistener/Handler.java deleted file mode 100644 index 01f1931c..00000000 --- a/sponge/src/main/java/net/buycraft/plugin/sponge/httplistener/Handler.java +++ /dev/null @@ -1,113 +0,0 @@ -package net.buycraft.plugin.sponge.httplistener; - -import com.google.common.base.Charsets; -import com.google.common.hash.Hashing; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.sun.net.httpserver.HttpExchange; -import com.sun.net.httpserver.HttpHandler; -import net.buycraft.plugin.data.QueuedCommand; -import net.buycraft.plugin.data.QueuedPlayer; -import net.buycraft.plugin.execution.strategy.ToRunQueuedCommand; -import net.buycraft.plugin.sponge.BuycraftPlugin; -import org.apache.commons.io.IOUtils; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -public class Handler implements HttpHandler { - private BuycraftPlugin plugin; - - public Handler(BuycraftPlugin plugin) { - this.plugin = plugin; - } - - @Override - public void handle(HttpExchange httpExchange) throws IOException { - Object[] response = this.handleRequest(httpExchange); - - httpExchange.sendResponseHeaders(Integer.parseInt(response[0].toString()), String.valueOf(response[1]).getBytes().length); - OutputStream os = httpExchange.getResponseBody(); - os.write(String.valueOf(response[1]).getBytes()); - os.flush(); - os.close(); - httpExchange.close(); - } - - private Object[] handleRequest(HttpExchange ex) { - if (ex.getRequestURI().toString().equalsIgnoreCase("/ping")) { - return new Object[]{200, "Connected"}; - } else { - try { - String body = IOUtils.toString(ex.getRequestBody(), Charsets.UTF_8); - String hash = Hashing.sha256().hashString(body.concat(plugin.getConfiguration().getServerKey()), Charsets.UTF_8).toString(); - - if (!ex.getRequestHeaders().containsKey("X-Signature")) { - return new Object[]{422, "X-Signature header missing"}; - } - - if (hash.equals(ex.getRequestHeaders().get("X-Signature").get(0))) { - JsonArray jsonBody; - try { - jsonBody = new JsonParser().parse(body).getAsJsonArray(); - } catch (Exception e) { - e.printStackTrace(); - return new Object[]{422, "Invalid JSON: " + e.getMessage()}; - } - - if (jsonBody != null) { - return pushCommand(jsonBody); - } - } else { - return new Object[]{422, "Invalid signature"}; - } - } catch (Exception e) { - e.printStackTrace(); - return new Object[]{422, "Error: " + e.getMessage()}; - } - } - return new Object[]{422, "Error"}; - } - - private Object[] pushCommand(JsonArray jsonBody) { - int playerId = 0; - for (JsonElement command : jsonBody) { - if (command instanceof JsonObject) { - JsonObject commandObject = command.getAsJsonObject(); - QueuedPlayer qp = new QueuedPlayer(playerId, - commandObject.get("username_name").getAsString(), - commandObject.get("username").getAsString().replace("-", "")); - - - Map map = new ConcurrentHashMap(); - map.put("delay", commandObject.get("delay").getAsInt()); - - if (commandObject.get("require_slots").getAsInt() > 0) { - map.put("slots", commandObject.get("require_slots").getAsInt()); - } - - int packageId = 0; - - if (commandObject.has("package") && !commandObject.get("package").isJsonNull()) { - packageId = commandObject.get("package").getAsInt(); - } - - QueuedCommand qc = new QueuedCommand(commandObject.get("id").getAsInt(), - commandObject.get("payment").getAsInt(), - packageId, - map, - commandObject.get("command").getAsString(), - qp); - - plugin.getCommandExecutor().queue(new ToRunQueuedCommand(qp, qc, commandObject.get("require_online").getAsInt() == 1)); - playerId += 1; - } - } - - return new Object[]{200, "Commands executed"}; - } -} diff --git a/sponge/src/main/java/net/buycraft/plugin/sponge/logging/LoggerUtils.java b/sponge/src/main/java/net/buycraft/plugin/sponge/logging/LoggerUtils.java deleted file mode 100644 index fa1cf16a..00000000 --- a/sponge/src/main/java/net/buycraft/plugin/sponge/logging/LoggerUtils.java +++ /dev/null @@ -1,21 +0,0 @@ -package net.buycraft.plugin.sponge.logging; - -import net.buycraft.plugin.sponge.BuycraftPlugin; - -import java.util.logging.Level; - -public class LoggerUtils { - private final BuycraftPlugin plugin; - - public LoggerUtils(final BuycraftPlugin plugin) { - this.plugin = plugin; - } - - public void log(Level level, String message) { - log(level, message, null); - } - - public void log(Level level, String message, Throwable e) { - plugin.getLogger().info(message, e); - } -} diff --git a/sponge/src/main/java/net/buycraft/plugin/sponge/signs/buynow/BuyNowSignListener.java b/sponge/src/main/java/net/buycraft/plugin/sponge/signs/buynow/BuyNowSignListener.java deleted file mode 100644 index 5e101ba5..00000000 --- a/sponge/src/main/java/net/buycraft/plugin/sponge/signs/buynow/BuyNowSignListener.java +++ /dev/null @@ -1,144 +0,0 @@ -package net.buycraft.plugin.sponge.signs.buynow; - -import net.buycraft.plugin.shared.config.signs.storage.SavedBuyNowSign; -import net.buycraft.plugin.shared.config.signs.storage.SerializedBlockLocation; -import net.buycraft.plugin.sponge.BuycraftPlugin; -import net.buycraft.plugin.sponge.tasks.BuyNowSignUpdater; -import net.buycraft.plugin.sponge.tasks.SendCheckoutLinkTask; -import net.buycraft.plugin.sponge.util.SpongeSerializedBlockLocation; -import org.spongepowered.api.block.BlockSnapshot; -import org.spongepowered.api.block.BlockTypes; -import org.spongepowered.api.data.manipulator.mutable.tileentity.SignData; -import org.spongepowered.api.data.value.mutable.ListValue; -import org.spongepowered.api.entity.living.player.Player; -import org.spongepowered.api.event.Listener; -import org.spongepowered.api.event.block.ChangeBlockEvent; -import org.spongepowered.api.event.block.InteractBlockEvent; -import org.spongepowered.api.event.block.tileentity.ChangeSignEvent; -import org.spongepowered.api.text.Text; -import org.spongepowered.api.text.format.TextColors; -import org.spongepowered.api.world.Location; -import org.spongepowered.api.world.World; - -import java.util.*; - -public class BuyNowSignListener { - private static final long COOLDOWN_MS = 250; // 5 ticks - private final BuycraftPlugin plugin; - private final Map signCooldowns = new HashMap<>(); - - public BuyNowSignListener(final BuycraftPlugin plugin) { - this.plugin = plugin; - } - - @Listener - public void onSignChange(ChangeSignEvent event) { - boolean ourSign; - - try { - ourSign = Arrays.asList("[buycraft_buy]", "[tebex_buy]").contains(event.getOriginalText().lines().get(0).toPlain().toLowerCase()); - } catch (IndexOutOfBoundsException e) { - return; - } - - if (!ourSign) { - return; - } - - Optional pl = event.getCause().first(Player.class); - if (!pl.isPresent()) { - // This change was not caused by a player. - return; - } - Player player = pl.get(); - - if (!player.hasPermission("buycraft.admin")) { - event.getCause().first(Player.class).get().sendMessage(Text.builder("You can't create Buycraft signs.").color(TextColors.RED).build()); - return; - } - - int pos; - try { - pos = Integer.parseInt(event.getOriginalText().lines().get(1).toPlain()); - } catch (NumberFormatException | IndexOutOfBoundsException e) { - event.getCause().first(Player.class).get().sendMessage(Text.builder("The second line must be a number.").color(TextColors.RED).build()); - return; - } - - plugin.getBuyNowSignStorage().addSign(new SavedBuyNowSign( - SpongeSerializedBlockLocation.create(event.getTargetTile().getLocation()), - pos)); - player.sendMessage(Text.builder("Added new buy now sign!").color(TextColors.GREEN).build()); - - // The below is due to the design of the Sponge Data API - SignData signData = event.getText(); - ListValue lines = signData.lines(); - for (int i = 0; i < 4; i++) { - if (i == 0) { - lines.set(i, Text.builder("Buy!").build()); - } else { - lines.set(i, Text.EMPTY); - } - } - signData.set(lines); - - plugin.getPlatform().executeAsync(new BuyNowSignUpdater(plugin)); - } - - private boolean isSign(Location sign) { - return sign.getBlockType().equals(BlockTypes.WALL_SIGN) || sign.getBlockType().equals(BlockTypes.STANDING_SIGN); - } - - private boolean removeSign(Player player, SerializedBlockLocation location) { - if (plugin.getBuyNowSignStorage().containsLocation(location)) { - if (!player.hasPermission("buycraft.admin")) { - player.sendMessage(Text.builder("You don't have permission to break this sign.").color(TextColors.RED).build()); - return false; - } - if (plugin.getBuyNowSignStorage().removeSign(location)) { - player.sendMessage(Text.builder("Removed buy now sign!").color(TextColors.RED).build()); - return true; - } else { - player.sendMessage(Text.builder("Unable to remove buy now sign!").color(TextColors.RED).build()); - return false; - } - } - return true; - } - - @Listener - public void onBlockBreak(ChangeBlockEvent.Break event) { - event.getTransactions().forEach(trans -> { - if ((trans.getOriginal().getState().getType().equals(BlockTypes.WALL_SIGN) || trans.getOriginal().getState().getType().equals(BlockTypes.STANDING_SIGN))) { - Optional> locationOptional = trans.getOriginal().getLocation(); - Optional playerOptional = event.getCause().first(Player.class); - if (!removeSign(playerOptional.get(), SpongeSerializedBlockLocation.create(locationOptional.get()))) { - event.setCancelled(true); - } - } - }); - } - - @Listener - public void onRightClickBlock(InteractBlockEvent.Secondary event) { - BlockSnapshot b = event.getTargetBlock(); - if (!(b.getState().getType().equals(BlockTypes.WALL_SIGN) || b.getState().getType().equals(BlockTypes.STANDING_SIGN))) { - return; - } - Player p = event.getCause().first(Player.class).get(); - SerializedBlockLocation sbl = SpongeSerializedBlockLocation.create(b.getLocation().get()); - - for (SavedBuyNowSign s : plugin.getBuyNowSignStorage().getSigns()) { - if (s.getLocation().equals(sbl)) { - // Signs are rate limited (per player) in order to limit API calls issued. - Long ts = signCooldowns.get(p.getUniqueId()); - long now = System.currentTimeMillis(); - if (ts == null || ts + COOLDOWN_MS <= now) { - signCooldowns.put(p.getUniqueId(), now); - plugin.getPlatform().executeAsync(new SendCheckoutLinkTask(plugin, s.getPackageId(), p)); - } - return; - } - } - } -} diff --git a/sponge/src/main/java/net/buycraft/plugin/sponge/signs/purchases/RecentPurchaseSignListener.java b/sponge/src/main/java/net/buycraft/plugin/sponge/signs/purchases/RecentPurchaseSignListener.java deleted file mode 100644 index 2a4849d0..00000000 --- a/sponge/src/main/java/net/buycraft/plugin/sponge/signs/purchases/RecentPurchaseSignListener.java +++ /dev/null @@ -1,116 +0,0 @@ -package net.buycraft.plugin.sponge.signs.purchases; - -import net.buycraft.plugin.shared.config.signs.storage.RecentPurchaseSignPosition; -import net.buycraft.plugin.shared.config.signs.storage.SerializedBlockLocation; -import net.buycraft.plugin.sponge.BuycraftPlugin; -import net.buycraft.plugin.sponge.tasks.SignUpdater; -import net.buycraft.plugin.sponge.util.SpongeSerializedBlockLocation; -import org.spongepowered.api.block.BlockTypes; -import org.spongepowered.api.data.manipulator.mutable.tileentity.SignData; -import org.spongepowered.api.data.value.mutable.ListValue; -import org.spongepowered.api.entity.living.player.Player; -import org.spongepowered.api.event.Listener; -import org.spongepowered.api.event.block.ChangeBlockEvent; -import org.spongepowered.api.event.block.tileentity.ChangeSignEvent; -import org.spongepowered.api.text.Text; -import org.spongepowered.api.text.format.TextColors; -import org.spongepowered.api.world.Location; -import org.spongepowered.api.world.World; - -import java.util.Arrays; -import java.util.Optional; - -public class RecentPurchaseSignListener { - private final BuycraftPlugin plugin; - - public RecentPurchaseSignListener(final BuycraftPlugin plugin) { - this.plugin = plugin; - } - - @Listener - public void onSignChange(ChangeSignEvent event) { - boolean ourSign; - - try { - ourSign = Arrays.asList("[buycraft_rp]", "[tebex_rp]").contains(event.getOriginalText().lines().get(0).toPlain().toLowerCase()); - } catch (IndexOutOfBoundsException e) { - return; - } - - if (!ourSign) { - return; - } - - Optional pl = event.getCause().first(Player.class); - if (!pl.isPresent()) { - // This change was not caused by a player. - return; - } - Player player = pl.get(); - - if (!player.hasPermission("buycraft.admin")) { - event.getCause().first(Player.class).get().sendMessage(Text.builder("You can't create Buycraft signs.").color(TextColors.RED).build()); - return; - } - - int pos; - try { - pos = Integer.parseInt(event.getOriginalText().lines().get(1).toPlain()); - } catch (NumberFormatException | IndexOutOfBoundsException e) { - event.getCause().first(Player.class).get().sendMessage(Text.builder("The second line must be a number.").color(TextColors.RED).build()); - return; - } - if (pos <= 0) { - player.sendMessage(Text.builder("You can't show negative or zero purchases!").color(TextColors.RED).build()); - return; - } - if (pos > 100) { - player.sendMessage(Text.builder("You can't show more than 100 recent purchases!").color(TextColors.RED).build()); - return; - } - - plugin.getRecentPurchaseSignStorage().addSign(new RecentPurchaseSignPosition(SpongeSerializedBlockLocation.create(event.getTargetTile().getLocation()), pos)); - player.sendMessage(Text.builder("Added new recent purchase sign!").color(TextColors.GREEN).build()); - - // The below is due to the design of the Sponge Data API - SignData signData = event.getText(); - ListValue lines = signData.lines(); - for (int i = 0; i < 4; i++) { - lines.set(i, Text.EMPTY); - } - signData.set(lines); - - plugin.getPlatform().executeAsync(new SignUpdater(plugin)); - } - - private boolean isSign(Location sign) { - return sign.getBlockType().equals(BlockTypes.WALL_SIGN) || sign.getBlockType().equals(BlockTypes.STANDING_SIGN); - } - - private boolean removeSign(Player player, SerializedBlockLocation location) { - if (plugin.getRecentPurchaseSignStorage().containsLocation(location)) { - if (!player.hasPermission("buycraft.admin")) { - player.sendMessage(Text.builder("You don't have permission to break this sign.").color(TextColors.RED).build()); - return false; - } - if (plugin.getRecentPurchaseSignStorage().removeSign(location)) { - player.sendMessage(Text.builder("Removed recent purchase sign!").color(TextColors.RED).build()); - return true; - } - } - return true; - } - - @Listener - public void onBlockBreak(ChangeBlockEvent.Break event) { - event.getTransactions().forEach(trans -> { - if ((trans.getOriginal().getState().getType().equals(BlockTypes.WALL_SIGN) || trans.getOriginal().getState().getType().equals(BlockTypes.STANDING_SIGN))) { - Optional> locationOptional = trans.getOriginal().getLocation(); - Optional playerOptional = event.getCause().first(Player.class); - if (!removeSign(playerOptional.get(), SpongeSerializedBlockLocation.create(locationOptional.get()))) { - event.setCancelled(true); - } - } - }); - } -} diff --git a/sponge/src/main/java/net/buycraft/plugin/sponge/tasks/BuyNowSignUpdater.java b/sponge/src/main/java/net/buycraft/plugin/sponge/tasks/BuyNowSignUpdater.java deleted file mode 100644 index 01a80cad..00000000 --- a/sponge/src/main/java/net/buycraft/plugin/sponge/tasks/BuyNowSignUpdater.java +++ /dev/null @@ -1,61 +0,0 @@ -package net.buycraft.plugin.sponge.tasks; - -import net.buycraft.plugin.data.Package; -import net.buycraft.plugin.shared.config.signs.storage.SavedBuyNowSign; -import net.buycraft.plugin.sponge.BuycraftPlugin; -import net.buycraft.plugin.sponge.util.SpongeSerializedBlockLocation; -import org.spongepowered.api.block.BlockState; -import org.spongepowered.api.block.BlockTypes; -import org.spongepowered.api.block.tileentity.TileEntity; -import org.spongepowered.api.data.manipulator.mutable.tileentity.SignData; -import org.spongepowered.api.data.value.mutable.ListValue; -import org.spongepowered.api.text.Text; -import org.spongepowered.api.world.Location; - -import java.util.Currency; -import java.util.List; -import java.util.Optional; - -public class BuyNowSignUpdater implements Runnable { - private final BuycraftPlugin plugin; - - public BuyNowSignUpdater(final BuycraftPlugin plugin) { - this.plugin = plugin; - } - - @Override - public void run() { - for (SavedBuyNowSign sign : plugin.getBuyNowSignStorage().getSigns()) { - Package p = plugin.getListingUpdateTask().getPackageById(sign.getPackageId()); - if (p == null) { - plugin.getLogger().error(String.format("Sign at %d, %d, %d in world %s does not have a valid package assigned to it.", - sign.getLocation().getX(), sign.getLocation().getY(), sign.getLocation().getZ(), sign.getLocation().getWorld())); - continue; - } - Location location = SpongeSerializedBlockLocation.toSponge(sign.getLocation()); - BlockState b = location.getBlock(); - - if (!(b.getType().equals(BlockTypes.WALL_SIGN) || b.getType().equals(BlockTypes.STANDING_SIGN))) { - plugin.getLogger().error(String.format("Sign at %d, %d, %d in world %s is not a sign in the world!", - sign.getLocation().getX(), sign.getLocation().getY(), sign.getLocation().getZ(), sign.getLocation().getWorld())); - continue; - } - - Optional entity = location.getTileEntity(); - Currency currency = Currency.getInstance(plugin.getServerInformation().getAccount().getCurrency().getIso4217()); - List signLines = plugin.getBuyNowSignLayout().format(currency, p); - if (entity.isPresent() && entity.get().supports(SignData.class)) { - SignData signData = entity.get().getOrCreate(SignData.class).get(); - ListValue lines = signData.lines(); - for (int i = 0; i < 4; i++) { - if (i >= signLines.size()) { - lines.set(i, Text.EMPTY); - } else { - lines.set(i, Text.builder(signLines.get(i).replace("&", "ยง")).build()); - } - } - entity.get().offer(lines); - } - } - } -} diff --git a/sponge/src/main/java/net/buycraft/plugin/sponge/tasks/SendCheckoutLinkTask.java b/sponge/src/main/java/net/buycraft/plugin/sponge/tasks/SendCheckoutLinkTask.java deleted file mode 100644 index e8043905..00000000 --- a/sponge/src/main/java/net/buycraft/plugin/sponge/tasks/SendCheckoutLinkTask.java +++ /dev/null @@ -1,53 +0,0 @@ -package net.buycraft.plugin.sponge.tasks; - -import net.buycraft.plugin.data.responses.CheckoutUrlResponse; -import net.buycraft.plugin.sponge.BuycraftPlugin; -import org.jetbrains.annotations.NotNull; -import org.spongepowered.api.entity.living.player.Player; -import org.spongepowered.api.text.Text; -import org.spongepowered.api.text.action.TextActions; -import org.spongepowered.api.text.format.TextColors; -import org.spongepowered.api.text.format.TextStyles; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Objects; - -public class SendCheckoutLinkTask implements Runnable { - @NotNull - private final BuycraftPlugin plugin; - private final int pkgId; - @NotNull - private final Player player; - - public SendCheckoutLinkTask(@NotNull final BuycraftPlugin plugin, final int pkgId, @NotNull final Player player) { - this.plugin = Objects.requireNonNull(plugin); - this.pkgId = pkgId; - this.player = Objects.requireNonNull(player); - } - - @Override - public void run() { - CheckoutUrlResponse response; - try { - response = plugin.getApiClient().getCheckoutUri(player.getName(), pkgId).execute().body(); - } catch (IOException e) { - player.sendMessage( - Text.builder(plugin.getI18n().get("cant_check_out")).color(TextColors.RED).build()); - return; - } - if (response != null) { - player.sendMessage(Text.builder(" ").style(TextStyles.STRIKETHROUGH).build()); - try { - player.sendMessages( - Text.builder(plugin.getI18n().get("to_buy_this_package")).color(TextColors.GREEN).build(), - Text.builder(response.getUrl()).color(TextColors.BLUE).style(TextStyles.UNDERLINE) - .onClick(TextActions.openUrl(new URL(response.getUrl()))).build()); - } catch (MalformedURLException e) { - e.printStackTrace(); - } - player.sendMessage(Text.builder(" ").style(TextStyles.STRIKETHROUGH).build()); - } - } -} diff --git a/sponge/src/main/java/net/buycraft/plugin/sponge/tasks/SignUpdateApplication.java b/sponge/src/main/java/net/buycraft/plugin/sponge/tasks/SignUpdateApplication.java deleted file mode 100644 index e63002db..00000000 --- a/sponge/src/main/java/net/buycraft/plugin/sponge/tasks/SignUpdateApplication.java +++ /dev/null @@ -1,91 +0,0 @@ -package net.buycraft.plugin.sponge.tasks; - -import com.google.common.collect.ImmutableList; -import net.buycraft.plugin.data.RecentPayment; -import net.buycraft.plugin.shared.config.signs.storage.RecentPurchaseSignPosition; -import net.buycraft.plugin.sponge.BuycraftPlugin; -import net.buycraft.plugin.sponge.util.SpongeSerializedBlockLocation; -import org.spongepowered.api.block.tileentity.Skull; -import org.spongepowered.api.block.tileentity.TileEntity; -import org.spongepowered.api.block.tileentity.TileEntityTypes; -import org.spongepowered.api.data.key.Keys; -import org.spongepowered.api.data.manipulator.mutable.tileentity.SignData; -import org.spongepowered.api.data.type.SkullTypes; -import org.spongepowered.api.data.value.mutable.ListValue; -import org.spongepowered.api.profile.GameProfile; -import org.spongepowered.api.text.Text; -import org.spongepowered.api.util.Direction; -import org.spongepowered.api.world.Location; -import org.spongepowered.api.world.World; - -import java.text.NumberFormat; -import java.util.*; - -public class SignUpdateApplication implements Runnable { - public static final List SKULL_CHECK = ImmutableList.of(Direction.NORTH, Direction.SOUTH, Direction.EAST, Direction.WEST, Direction.NONE); - private final BuycraftPlugin plugin; - private final Map paymentMap; - private final Map resolvedProfiles; - - public SignUpdateApplication(final BuycraftPlugin plugin, final Map paymentMap, final Map resolvedProfiles) { - this.plugin = plugin; - this.paymentMap = paymentMap; - this.resolvedProfiles = resolvedProfiles; - } - - private Optional findSkull(Location start) { - for (Direction direction : SKULL_CHECK) { - Optional entity = start.getRelative(direction).getTileEntity(); - if (entity.isPresent()) { - if (entity.get().getType().equals(TileEntityTypes.SKULL)) { - return Optional.of((Skull) entity.get()); - } - } - } - return Optional.empty(); - } - - @Override - public void run() { - for (Map.Entry entry : paymentMap.entrySet()) { - Location location = SpongeSerializedBlockLocation.toSponge(entry.getKey().getLocation()); - Optional entity = location.getTileEntity(); - if (entity.isPresent() && entity.get().supports(SignData.class)) { - SignData signData = entity.get().getOrCreate(SignData.class).get(); - ListValue lines = signData.lines(); - - if (entry.getValue() != null) { - lines.set(0, Text.EMPTY); - lines.set(1, Text.of(entry.getValue().getPlayer().getName())); - NumberFormat format = NumberFormat.getCurrencyInstance(Locale.US); - format.setCurrency(Currency.getInstance(entry.getValue().getCurrency().getIso4217())); - lines.set(2, Text.of(format.format(entry.getValue().getAmount()))); - lines.set(3, Text.EMPTY); - } else { - for (int i = 0; i < 4; i++) { - lines.set(i, Text.EMPTY); - } - } - - entity.get().offer(lines); - Location supportedBy = location.getRelative(Direction.UP); - - Optional skullOptional = findSkull(supportedBy); - if (skullOptional.isPresent()) { - Skull skull = skullOptional.get(); - if (!skull.supports(Keys.REPRESENTED_PLAYER)) { - skull.offer(Keys.SKULL_TYPE, SkullTypes.PLAYER); - } - GameProfile profile = entry.getValue() != null ? - resolvedProfiles.getOrDefault(entry.getValue().getPlayer().getName(), resolvedProfiles.get("MHF_Question")) : - resolvedProfiles.get("MHF_Question"); - if (profile != null) { - skull.offer(Keys.REPRESENTED_PLAYER, profile); - } - } - } else { - plugin.getLogger().error("Location " + entry.getKey() + " doesn't have a tile entity! (Sign missing?)"); - } - } - } -} diff --git a/sponge/src/main/java/net/buycraft/plugin/sponge/tasks/SignUpdater.java b/sponge/src/main/java/net/buycraft/plugin/sponge/tasks/SignUpdater.java deleted file mode 100644 index 0308930c..00000000 --- a/sponge/src/main/java/net/buycraft/plugin/sponge/tasks/SignUpdater.java +++ /dev/null @@ -1,73 +0,0 @@ -package net.buycraft.plugin.sponge.tasks; - -import net.buycraft.plugin.data.RecentPayment; -import net.buycraft.plugin.shared.config.signs.storage.RecentPurchaseSignPosition; -import net.buycraft.plugin.sponge.BuycraftPlugin; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.profile.GameProfile; - -import java.io.IOException; -import java.util.*; -import java.util.concurrent.CompletableFuture; -import java.util.function.Function; -import java.util.stream.Collectors; - -public class SignUpdater implements Runnable { - private final BuycraftPlugin plugin; - - public SignUpdater(final BuycraftPlugin plugin) { - this.plugin = plugin; - } - - @Override - public void run() { - List signs = plugin.getRecentPurchaseSignStorage().getSigns(); - OptionalInt maxPos = signs.stream().mapToInt(RecentPurchaseSignPosition::getPosition).max(); - - if (!maxPos.isPresent()) { - // Nothing to do - return; - } - - if (plugin.getApiClient() == null) { - // Can't use API client - return; - } - - List payments; - try { - payments = plugin.getApiClient().getRecentPayments(Math.min(100, maxPos.getAsInt())).execute().body(); - } catch (IOException e) { - plugin.getLogger().error("Could not fetch recent purchases", e); - return; - } - - Map signToPurchases = new HashMap<>(); - for (RecentPurchaseSignPosition sign : signs) { - if (sign.getPosition() > payments.size()) { - signToPurchases.put(sign, null); - } else { - signToPurchases.put(sign, payments.get(sign.getPosition() - 1)); - } - } - - // Now look up game profiles so that heads can be properly displayed. - Set usernames = payments.stream().map(payment -> payment.getPlayer().getName()).collect(Collectors.toSet()); - // Add MHF_Question too. - usernames.add("MHF_Question"); - CompletableFuture> future = Sponge.getServer().getGameProfileManager().getAllByName(usernames, true); - future.whenComplete((result, throwable) -> { - if (throwable != null) { - plugin.getLogger().error("Unable to fetch player profiles", throwable); - return; - } - - Map profileMap = result.stream().filter(p -> p.getName().isPresent()) - .collect(Collectors.toMap(p -> p.getName().get(), Function.identity())); - - Sponge.getScheduler().createTaskBuilder() - .execute(new SignUpdateApplication(plugin, signToPurchases, profileMap)) - .submit(plugin); - }); - } -} diff --git a/sponge/src/main/java/net/buycraft/plugin/sponge/util/SpongeSerializedBlockLocation.java b/sponge/src/main/java/net/buycraft/plugin/sponge/util/SpongeSerializedBlockLocation.java deleted file mode 100644 index b6305bc1..00000000 --- a/sponge/src/main/java/net/buycraft/plugin/sponge/util/SpongeSerializedBlockLocation.java +++ /dev/null @@ -1,28 +0,0 @@ -package net.buycraft.plugin.sponge.util; - -import net.buycraft.plugin.shared.config.signs.storage.SerializedBlockLocation; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.world.Location; -import org.spongepowered.api.world.World; - -import java.util.Optional; -import java.util.UUID; - -public final class SpongeSerializedBlockLocation { - private SpongeSerializedBlockLocation() { - throw new UnsupportedOperationException("This is a utility class and cannot be instantiated"); - } - - public static SerializedBlockLocation create(Location location) { - return new SerializedBlockLocation(location.getExtent().getUniqueId().toString(), location.getBlockX(), location.getBlockY(), - location.getBlockZ()); - } - - public static Location toSponge(SerializedBlockLocation location) { - Optional world = Sponge.getServer().getWorld(UUID.fromString(location.getWorld())); - if (!world.isPresent()) { - throw new IllegalStateException(); - } - return new Location<>(world.get(), location.getX(), location.getY(), location.getZ()); - } -} diff --git a/sponge/src/main/java/net/buycraft/plugin/sponge/util/VersionCheck.java b/sponge/src/main/java/net/buycraft/plugin/sponge/util/VersionCheck.java deleted file mode 100644 index 74e58eb1..00000000 --- a/sponge/src/main/java/net/buycraft/plugin/sponge/util/VersionCheck.java +++ /dev/null @@ -1,77 +0,0 @@ -package net.buycraft.plugin.sponge.util; - -import net.buycraft.plugin.data.responses.Version; -import net.buycraft.plugin.shared.util.VersionUtil; -import net.buycraft.plugin.sponge.BuycraftPlugin; -import org.spongepowered.api.event.Listener; -import org.spongepowered.api.event.network.ClientConnectionEvent; -import org.spongepowered.api.text.Text; -import org.spongepowered.api.text.action.TextActions; -import org.spongepowered.api.text.format.TextColors; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.concurrent.TimeUnit; - -import static net.buycraft.plugin.shared.util.VersionUtil.isVersionGreater; - -public class VersionCheck { - private final BuycraftPlugin plugin; - private final String pluginVersion; - private final String secret; - private Version lastKnownVersion; - private boolean upToDate = true; - - public VersionCheck(final BuycraftPlugin plugin, final String pluginVersion, final String secret) { - this.plugin = plugin; - this.pluginVersion = pluginVersion; - this.secret = secret; - } - - public void verify() throws IOException { - if (pluginVersion.endsWith("-SNAPSHOT")) { - return; // SNAPSHOT versions ignore updates - } - - lastKnownVersion = VersionUtil.getVersion(plugin.getHttpClient(), "sponge", secret); - if (lastKnownVersion == null) { - return; - } - - // Compare versions - String latestVersionString = lastKnownVersion.getVersion(); - if (!latestVersionString.equals(pluginVersion)) { - upToDate = !isVersionGreater(pluginVersion, latestVersionString); - if (!upToDate) { - plugin.getLogger().info(plugin.getI18n().get("update_available", lastKnownVersion.getVersion())); - } - } - } - - @Listener - public void onPlayerJoinEvent(ClientConnectionEvent.Join event) { - if (event.getTargetEntity().hasPermission("buycraft.admin") && !upToDate) { - plugin.getPlatform().executeAsyncLater(() -> { - try { - event.getTargetEntity().sendMessage( - Text.builder() - .append(Text.of(plugin.getI18n().get("update_available", lastKnownVersion.getVersion()))) - .onClick(TextActions.openUrl(new URL("https://server.tebex.io"))) - .color(TextColors.YELLOW) - .build()); - } catch (MalformedURLException e) { - throw new AssertionError(e); // seriously? - } - }, 3, TimeUnit.SECONDS); - } - } - - public Version getLastKnownVersion() { - return this.lastKnownVersion; - } - - public boolean isUpToDate() { - return this.upToDate; - } -} diff --git a/sponge/src/main/java/org/kitteh/craftirc/sponge/util/versioning/Transform.java b/sponge/src/main/java/org/kitteh/craftirc/sponge/util/versioning/Transform.java deleted file mode 100644 index 1aceb137..00000000 --- a/sponge/src/main/java/org/kitteh/craftirc/sponge/util/versioning/Transform.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * * Copyright (C) 2015 Matt Baxter http://kitteh.org - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package org.kitteh.craftirc.sponge.util.versioning; - -import de.icongmbh.oss.maven.plugin.javassist.ClassTransformer; -import javassist.ClassPool; -import javassist.CtClass; -import javassist.NotFoundException; -import javassist.bytecode.AnnotationsAttribute; -import javassist.bytecode.annotation.Annotation; -import javassist.bytecode.annotation.StringMemberValue; -import net.buycraft.plugin.sponge.BuycraftPlugin; - -import java.util.Properties; - -/** - * Used purely to set the version value on the Plugin. Don't bother touching. - */ -public class Transform extends ClassTransformer { - private String version; - - @Override - protected boolean shouldTransform(final CtClass clazz) throws NotFoundException { - CtClass buycraftPlugin = ClassPool.getDefault().get(BuycraftPlugin.class.getName()); - return !clazz.equals(buycraftPlugin) && clazz.subtypeOf(buycraftPlugin); - } - - @Override - protected void applyTransformations(CtClass clazz) throws Exception { - AnnotationsAttribute attribute = (AnnotationsAttribute) clazz.getClassFile().getAttribute(AnnotationsAttribute.visibleTag); - Annotation annotation = attribute.getAnnotation("org.spongepowered.api.plugin.Plugin"); - StringMemberValue version = (StringMemberValue) annotation.getMemberValue("version"); - version.setValue(this.version); - attribute.setAnnotation(annotation); - } - - @Override - public void configure(final Properties properties) { - if (properties == null || (this.version = properties.getProperty("version")) == null) { - throw new AssertionError("Version not set!"); - } - } -} \ No newline at end of file diff --git a/velocity/pom.xml b/velocity/pom.xml deleted file mode 100644 index fc3ee991..00000000 --- a/velocity/pom.xml +++ /dev/null @@ -1,141 +0,0 @@ - - - - BuycraftX - net.buycraft - 12.0.7 - - 4.0.0 - - buycraftx-velocity - - - - - velocity - https://repo.velocitypowered.com/snapshots/ - - - - - - - src/main/resources - true - - - - - org.apache.maven.plugins - maven-shade-plugin - 2.4 - - - - com.google.code.gson - com.google.guava - - - - - okhttp3 - net.buycraft.plugin.internal.okhttp3 - - - okio - net.buycraft.plugin.internal.okio - - - com.fasterxml.jackson - net.buycraft.plugin.internal.jackson - - - - - - package - - shade - - - - - - de.icongmbh.oss.maven.plugins - javassist-maven-plugin - 1.1.0 - - false - - - org.kitteh.craftirc.sponge.util.versioning.Transform - - - version - ${project.version} - - - - - - - - process-classes - - javassist - - - - - - net.buycraft - buycraftx-velocity - ${project.version} - - - - - com.google.code.maven-replacer-plugin - replacer - 1.5.3 - - - prepare-package - - replace - - - ${project.basedir}/target/classes/velocity-plugin.json - SET_BY_MAGIC - ${project.version} - - - - - - - - - - net.buycraft - buycraftx-plugin-shared - ${project.parent.version} - compile - - - com.velocitypowered - velocity-api - 1.0.0-SNAPSHOT - provided - - - de.icongmbh.oss.maven.plugins - javassist-maven-plugin - 1.1.0 - provided - - - - \ No newline at end of file diff --git a/velocity/src/main/java/net/buycraft/plugin/velocity/BuycraftCommand.java b/velocity/src/main/java/net/buycraft/plugin/velocity/BuycraftCommand.java deleted file mode 100644 index cfb3e749..00000000 --- a/velocity/src/main/java/net/buycraft/plugin/velocity/BuycraftCommand.java +++ /dev/null @@ -1,55 +0,0 @@ -package net.buycraft.plugin.velocity; - -import com.velocitypowered.api.command.Command; -import com.velocitypowered.api.command.CommandSource; -import net.buycraft.plugin.velocity.command.Subcommand; -import net.kyori.text.TextComponent; -import net.kyori.text.format.TextColor; -import net.kyori.text.format.TextDecoration; - -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.Map; - -public class BuycraftCommand implements Command { - private final Map subcommandMap = new LinkedHashMap<>(); - private final BuycraftPlugin plugin; - - public BuycraftCommand(BuycraftPlugin plugin) { - this.plugin = plugin; - } - - @Override - public void execute(CommandSource sender, String[] args) { - if (!sender.hasPermission("buycraft.admin")) { - sender.sendMessage(TextComponent.of(plugin.getI18n().get("no_permission")).color(TextColor.RED)); - return; - } - - if (args.length == 0) { - showHelp(sender); - return; - } - - for (Map.Entry entry : subcommandMap.entrySet()) { - if (entry.getKey().equalsIgnoreCase(args[0])) { - String[] withoutSubcommand = Arrays.copyOfRange(args, 1, args.length); - entry.getValue().execute(sender, withoutSubcommand); - return; - } - } - - showHelp(sender); - } - - private void showHelp(CommandSource sender) { - sender.sendMessage(TextComponent.of(plugin.getI18n().get("usage")).color(TextColor.DARK_AQUA).decoration(TextDecoration.BOLD, true)); - for (Map.Entry entry : subcommandMap.entrySet()) { - sender.sendMessage(TextComponent.of("/tebex " + entry.getKey()).color(TextColor.GREEN).append(TextComponent.of(": " + entry.getValue().getDescription()))); - } - } - - public Map getSubcommandMap() { - return this.subcommandMap; - } -} diff --git a/velocity/src/main/java/net/buycraft/plugin/velocity/BuycraftPlugin.java b/velocity/src/main/java/net/buycraft/plugin/velocity/BuycraftPlugin.java deleted file mode 100644 index 56c1d943..00000000 --- a/velocity/src/main/java/net/buycraft/plugin/velocity/BuycraftPlugin.java +++ /dev/null @@ -1,338 +0,0 @@ -package net.buycraft.plugin.velocity; - -import com.google.common.util.concurrent.ThreadFactoryBuilder; -import com.google.inject.Inject; -import com.velocitypowered.api.event.Subscribe; -import com.velocitypowered.api.event.connection.DisconnectEvent; -import com.velocitypowered.api.event.connection.PostLoginEvent; -import com.velocitypowered.api.event.proxy.ProxyInitializeEvent; -import com.velocitypowered.api.event.proxy.ProxyShutdownEvent; -import com.velocitypowered.api.plugin.Plugin; -import com.velocitypowered.api.plugin.annotation.DataDirectory; -import com.velocitypowered.api.proxy.ProxyServer; -import net.buycraft.plugin.BuyCraftAPI; -import net.buycraft.plugin.IBuycraftPlatform; -import net.buycraft.plugin.data.QueuedPlayer; -import net.buycraft.plugin.data.ServerEvent; -import net.buycraft.plugin.data.responses.ServerInformation; -import net.buycraft.plugin.execution.DuePlayerFetcher; -import net.buycraft.plugin.execution.ServerEventSenderTask; -import net.buycraft.plugin.execution.placeholder.NamePlaceholder; -import net.buycraft.plugin.execution.placeholder.PlaceholderManager; -import net.buycraft.plugin.execution.placeholder.UuidPlaceholder; -import net.buycraft.plugin.execution.strategy.CommandExecutor; -import net.buycraft.plugin.execution.strategy.PostCompletedCommandsTask; -import net.buycraft.plugin.execution.strategy.QueuedCommandExecutor; -import net.buycraft.plugin.shared.Setup; -import net.buycraft.plugin.shared.config.BuycraftConfiguration; -import net.buycraft.plugin.shared.config.BuycraftI18n; -import net.buycraft.plugin.shared.tasks.PlayerJoinCheckTask; -import net.buycraft.plugin.shared.util.AnalyticsSend; -import net.buycraft.plugin.velocity.command.*; -import net.buycraft.plugin.velocity.util.VersionCheck; -import okhttp3.Cache; -import okhttp3.ConnectionPool; -import okhttp3.Dispatcher; -import okhttp3.OkHttpClient; -import org.slf4j.Logger; - -import java.io.File; -import java.io.IOException; -import java.nio.file.NoSuchFileException; -import java.nio.file.Path; -import java.util.Date; -import java.util.concurrent.*; - -@Plugin(id = "buycraft", name = "BuycraftX", authors = {"Tebex", "theminecoder"}, version = BuycraftPlugin.MAGIC_VERSION) -public class BuycraftPlugin { - static final String MAGIC_VERSION = "SET_BY_MAGIC"; - - private final ProxyServer server; - private final Logger logger; - private final File dataFolder; - - private final PlaceholderManager placeholderManager = new PlaceholderManager(); - private final BuycraftConfiguration configuration = new BuycraftConfiguration(); - private BuyCraftAPI apiClient; - private DuePlayerFetcher duePlayerFetcher; - private ServerInformation serverInformation; - private OkHttpClient httpClient; - private IBuycraftPlatform platform; - private CommandExecutor commandExecutor; - private BuycraftI18n i18n; - private PostCompletedCommandsTask completedCommandsTask; - private PlayerJoinCheckTask playerJoinCheckTask; - private ServerEventSenderTask serverEventSenderTask; - private ExecutorService service; - - @Inject - public BuycraftPlugin(ProxyServer server, Logger logger, @DataDirectory Path dataFolder) { - this.server = server; - this.logger = logger; - this.dataFolder = dataFolder.toFile(); - } - - @Subscribe - public void onEnable(ProxyInitializeEvent event) { - // Pre-initialization. - platform = new VelocityBuycraftPlatform(this); - // Initialize configuration. - getDataFolder().mkdir(); - Path configPath = getDataFolder().toPath().resolve("config.properties"); - try { - try { - configuration.load(configPath); - } catch (NoSuchFileException e) { - // Save defaults - configuration.fillDefaults(); - configuration.save(configPath); - } - } catch (IOException e) { - throw new RuntimeException("Unable to load configuration", e); - } - - i18n = configuration.createI18n(); - - // This has to be done in a different thread due to the SecurityManager. - try { - httpClient = runSyncTaskOnAsyncThread(() -> Setup.okhttpBuilder() - .cache(new Cache(new File(getDataFolder(), "cache"), 1024 * 1024 * 10)) - .connectionPool(new ConnectionPool()) - .dispatcher(new Dispatcher(getExecutorService())) - .build()); - } catch (ExecutionException e) { - // We must bail early - throw new RuntimeException("Can't create HTTP client", e); - } - -// if (configuration.isPushCommandsEnabled()) { //TODO Find velocity netty injection path -// try { -// BungeeNettyChannelInjector.inject(this); -// } catch (Throwable t) { -// t.printStackTrace(); -// } -// } - - // Initialize API client. - final String serverKey = configuration.getServerKey(); - if (serverKey == null || serverKey.equals("INVALID")) { - getLogger().info("Looks like this is a fresh setup. Get started by using 'tebex secret ' in the console."); - } else { - getLogger().info("Validating your server key..."); - final BuyCraftAPI client = BuyCraftAPI.create(configuration.getServerKey(), httpClient); - // Hack due to SecurityManager shenanigans. - try { - runSyncTaskOnAsyncThread((Callable) () -> { - updateInformation(client); - return null; - }); - } catch (ExecutionException e) { - getLogger().error(String.format("We can't check if your server can connect to Tebex: %s", e.getMessage())); - } - apiClient = client; - } - - // Check for latest version. - if (configuration.isCheckForUpdates()) { - final VersionCheck check = new VersionCheck(this, platform.getPluginVersion(), configuration.getServerKey()); - try { - runSyncTaskOnAsyncThread((Callable) () -> { - check.verify(); - return null; - }); - } catch (ExecutionException e) { - getLogger().error("Can't check for updates", e); - } - getServer().getEventManager().register(this, check); - } - - // Initialize placeholders. - placeholderManager.addPlaceholder(new NamePlaceholder()); - placeholderManager.addPlaceholder(new UuidPlaceholder()); - - // Queueing tasks. - getServer().getScheduler() - .buildTask(this, duePlayerFetcher = new DuePlayerFetcher(platform, configuration.isVerbose())) - .delay(1, TimeUnit.SECONDS) - .schedule(); - completedCommandsTask = new PostCompletedCommandsTask(platform); - commandExecutor = new QueuedCommandExecutor(platform, completedCommandsTask); - getServer().getScheduler() - .buildTask(this, completedCommandsTask) - .delay(1, TimeUnit.SECONDS) - .repeat(1, TimeUnit.SECONDS) - .schedule(); - getServer().getScheduler() - .buildTask(this, (Runnable) commandExecutor) - .delay(50, TimeUnit.MILLISECONDS) - .repeat(1, TimeUnit.MILLISECONDS) - .schedule(); - playerJoinCheckTask = new PlayerJoinCheckTask(platform); - getServer().getScheduler() - .buildTask(this, playerJoinCheckTask) - .delay(1, TimeUnit.SECONDS) - .repeat(1, TimeUnit.SECONDS) - .schedule(); - serverEventSenderTask = new ServerEventSenderTask(platform, configuration.isVerbose()); - getServer().getScheduler() - .buildTask(this, serverEventSenderTask) - .delay(1, TimeUnit.MINUTES) - .repeat(1, TimeUnit.MINUTES) - .schedule(); - - // Initialize and register commands. - BuycraftCommand command = new BuycraftCommand(this); - command.getSubcommandMap().put("forcecheck", new ForceCheckSubcommand(this)); - command.getSubcommandMap().put("secret", new SecretSubcommand(this)); - command.getSubcommandMap().put("info", new InformationSubcommand(this)); - command.getSubcommandMap().put("report", new ReportCommand(this)); - command.getSubcommandMap().put("coupon", new CouponSubcommand(this)); - getServer().getCommandManager().register(command, "tebex", "buycraft"); - - // Send data to Keen IO - if (serverInformation != null) { - getServer().getScheduler().buildTask(this, () -> { - try { - AnalyticsSend.postServerInformation(httpClient, serverKey, platform, getServer().getConfiguration().isOnlineMode()); - } catch (IOException e) { - getLogger().warn("Can't send analytics", e); - } - }).repeat(1, TimeUnit.DAYS).schedule(); - } - } - - @Subscribe - public void onDisable(ProxyShutdownEvent event) { - if (completedCommandsTask != null) { - completedCommandsTask.flush(); - } - } - - @Subscribe - public void onPostLogin(PostLoginEvent event) { - if (getApiClient() == null) { - return; - } - - serverEventSenderTask.queueEvent(new ServerEvent( - event.getPlayer().getUniqueId().toString().replace("-", ""), - event.getPlayer().getUsername(), - event.getPlayer().getRemoteAddress().getAddress().getHostAddress(), - ServerEvent.JOIN_EVENT, - new Date() - )); - - QueuedPlayer qp = getDuePlayerFetcher().fetchAndRemoveDuePlayer(event.getPlayer().getUsername()); - if (qp != null) { - getPlayerJoinCheckTask().queue(qp); - } - } - - @Subscribe - public void onQuit(DisconnectEvent event) { - if (getApiClient() == null) { - return; - } - - serverEventSenderTask.queueEvent(new ServerEvent( - event.getPlayer().getUniqueId().toString().replace("-", ""), - event.getPlayer().getUsername(), - event.getPlayer().getRemoteAddress().getAddress().getHostAddress(), - ServerEvent.LEAVE_EVENT, - new Date() - )); - } - - public ProxyServer getServer() { - return server; - } - - public Logger getLogger() { - return logger; - } - - public File getDataFolder() { - return dataFolder; - } - - @Deprecated - public ExecutorService getExecutorService() { - if (service == null) { - ThreadGroup pluginThreadGroup = new ThreadGroup("BuycraftX"); - service = Executors.newCachedThreadPool(new ThreadFactoryBuilder() - .setNameFormat("BuycraftX Pool Thread #%1$d") - .setThreadFactory(r -> new Thread(pluginThreadGroup, r)) - .build()); - } - return service; - } - - private T runSyncTaskOnAsyncThread(Callable runnable) throws ExecutionException { - CompletableFuture future = new CompletableFuture<>(); - try { - server.getScheduler().buildTask(this, () -> { - try { - future.complete(runnable.call()); - } catch (Throwable e) { - future.completeExceptionally(e); - } - }).schedule(); - return future.get(); - } catch (InterruptedException e) { - throw new ExecutionException("interrupted", e); - } - } - - public void saveConfiguration() throws IOException { - Path configPath = getDataFolder().toPath().resolve("config.properties"); - configuration.save(configPath); - } - - public void updateInformation(BuyCraftAPI client) throws IOException { - serverInformation = client.getServerInformation().execute().body(); - } - - public PlaceholderManager getPlaceholderManager() { - return this.placeholderManager; - } - - public BuycraftConfiguration getConfiguration() { - return this.configuration; - } - - public BuyCraftAPI getApiClient() { - return this.apiClient; - } - - public void setApiClient(final BuyCraftAPI apiClient) { - this.apiClient = apiClient; - } - - public DuePlayerFetcher getDuePlayerFetcher() { - return this.duePlayerFetcher; - } - - public ServerInformation getServerInformation() { - return this.serverInformation; - } - - public OkHttpClient getHttpClient() { - return this.httpClient; - } - - public IBuycraftPlatform getPlatform() { - return this.platform; - } - - public CommandExecutor getCommandExecutor() { - return this.commandExecutor; - } - - public BuycraftI18n getI18n() { - return this.i18n; - } - - public PlayerJoinCheckTask getPlayerJoinCheckTask() { - return this.playerJoinCheckTask; - } -} diff --git a/velocity/src/main/java/net/buycraft/plugin/velocity/VelocityBuycraftPlatform.java b/velocity/src/main/java/net/buycraft/plugin/velocity/VelocityBuycraftPlatform.java deleted file mode 100644 index 9a9a1096..00000000 --- a/velocity/src/main/java/net/buycraft/plugin/velocity/VelocityBuycraftPlatform.java +++ /dev/null @@ -1,118 +0,0 @@ -package net.buycraft.plugin.velocity; - -import com.velocitypowered.api.proxy.Player; -import net.buycraft.plugin.BuyCraftAPI; -import net.buycraft.plugin.IBuycraftPlatform; -import net.buycraft.plugin.UuidUtil; -import net.buycraft.plugin.data.QueuedPlayer; -import net.buycraft.plugin.data.responses.ServerInformation; -import net.buycraft.plugin.execution.placeholder.PlaceholderManager; -import net.buycraft.plugin.execution.strategy.CommandExecutor; -import net.buycraft.plugin.platform.PlatformInformation; -import net.buycraft.plugin.platform.PlatformType; -import org.slf4j.Logger; - -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import java.util.function.BiConsumer; -import java.util.function.Function; -import java.util.logging.Level; - -public class VelocityBuycraftPlatform implements IBuycraftPlatform { - - private Map>> LOG_LEVEL_MAP = new HashMap>>() {{ - put(Level.INFO, l -> l::info); - put(Level.WARNING, l -> l::warn); - put(Level.SEVERE, l -> l::error); - }}; - - private final BuycraftPlugin plugin; - - public VelocityBuycraftPlatform(BuycraftPlugin plugin) { - this.plugin = plugin; - } - - @Override - public BuyCraftAPI getApiClient() { - return plugin.getApiClient(); - } - - @Override - public PlaceholderManager getPlaceholderManager() { - return plugin.getPlaceholderManager(); - } - - @Override - public void dispatchCommand(String command) { - plugin.getServer().getCommandManager().execute(plugin.getServer().getConsoleCommandSource(), command); - } - - @Override - public void executeAsync(Runnable runnable) { - plugin.getServer().getScheduler().buildTask(plugin, runnable).schedule(); - } - - @Override - public void executeAsyncLater(Runnable runnable, long time, TimeUnit unit) { - plugin.getServer().getScheduler().buildTask(plugin, runnable).delay(time, unit).schedule(); - } - - @Override - public void executeBlocking(Runnable runnable) { - executeAsync(runnable); - } - - @Override - public void executeBlockingLater(Runnable runnable, long time, TimeUnit unit) { - executeAsyncLater(runnable, time, unit); - } - - private Player getPlayer(QueuedPlayer player) { - if (player.getUuid() != null && plugin.getServer().getConfiguration().isOnlineMode()) { - return plugin.getServer().getPlayer(UuidUtil.mojangUuidToJavaUuid(player.getUuid())).orElse(null); - } - return plugin.getServer().getPlayer(player.getName()).orElse(null); - } - - @Override - public boolean isPlayerOnline(QueuedPlayer player) { - return getPlayer(player) != null; - } - - @Override - public int getFreeSlots(QueuedPlayer player) { - return 0; - } - - @Override - public void log(Level level, String message) { - LOG_LEVEL_MAP.get(level).apply(plugin.getLogger()).accept(message, null); - } - - @Override - public void log(Level level, String message, Throwable throwable) { - LOG_LEVEL_MAP.get(level).apply(plugin.getLogger()).accept(message, throwable); - } - - @Override - public CommandExecutor getExecutor() { - return plugin.getCommandExecutor(); - } - - @Override - public PlatformInformation getPlatformInformation() { - return new PlatformInformation(PlatformType.VELOCITY, plugin.getServer().getVersion().getVersion()); - } - - @Override - public String getPluginVersion() { - return plugin.getServer().getPluginManager().fromInstance(plugin).orElseThrow(IllegalStateException::new) - .getDescription().getVersion().orElse("UNKNOWN-SNAPSHOT"); - } - - @Override - public ServerInformation getServerInformation() { - return plugin.getServerInformation(); - } -} diff --git a/velocity/src/main/java/net/buycraft/plugin/velocity/command/CouponSubcommand.java b/velocity/src/main/java/net/buycraft/plugin/velocity/command/CouponSubcommand.java deleted file mode 100644 index 578c6fba..00000000 --- a/velocity/src/main/java/net/buycraft/plugin/velocity/command/CouponSubcommand.java +++ /dev/null @@ -1,83 +0,0 @@ -package net.buycraft.plugin.velocity.command; - -import com.velocitypowered.api.command.CommandSource; -import net.buycraft.plugin.data.Coupon; -import net.buycraft.plugin.shared.util.CouponUtil; -import net.buycraft.plugin.velocity.BuycraftPlugin; -import net.kyori.text.TextComponent; -import net.kyori.text.format.TextColor; - -import java.io.IOException; -import java.util.Arrays; - -public class CouponSubcommand implements Subcommand { - private static final int COUPON_PAGE_LIMIT = 10; - - private final BuycraftPlugin plugin; - - public CouponSubcommand(final BuycraftPlugin plugin) { - this.plugin = plugin; - } - - @Override - public void execute(CommandSource sender, String[] args) { - if (args.length == 0) { - sender.sendMessage(TextComponent.of(plugin.getI18n().get("usage_coupon_subcommands")).color(TextColor.RED)); - return; - } - - switch (args[0]) { - case "create": - createCoupon(sender, args); - break; - case "delete": - deleteCoupon(sender, args); - break; - default: - sender.sendMessage(TextComponent.of(plugin.getI18n().get("usage_coupon_subcommands")).color(TextColor.RED)); - break; - } - } - - private void createCoupon(final CommandSource sender, String[] args) { - String[] stripped = Arrays.copyOfRange(args, 1, args.length); - final Coupon coupon; - try { - coupon = CouponUtil.parseArguments(stripped); - } catch (Exception e) { - sender.sendMessage(TextComponent.of(plugin.getI18n().get("coupon_creation_arg_parse_failure", e.getMessage())).color(TextColor.RED)); - return; - } - - plugin.getPlatform().executeAsync(() -> { - try { - plugin.getApiClient().createCoupon(coupon).execute().body(); - sender.sendMessage(TextComponent.of(plugin.getI18n().get("coupon_creation_success", coupon.getCode())).color(TextColor.GREEN)); - } catch (IOException e) { - sender.sendMessage(TextComponent.of(plugin.getI18n().get("generic_api_operation_error")).color(TextColor.RED)); - } - }); - } - - private void deleteCoupon(final CommandSource sender, String[] args) { - if (args.length != 2) { - sender.sendMessage(TextComponent.of(plugin.getI18n().get("no_coupon_specified")).color(TextColor.RED)); - return; - } - - final String code = args[1]; - plugin.getPlatform().executeAsync(() -> { - try { - plugin.getApiClient().deleteCoupon(code).execute().body(); - sender.sendMessage(TextComponent.of(plugin.getI18n().get("coupon_deleted")).color(TextColor.GREEN)); - } catch (IOException e) { - sender.sendMessage(TextComponent.of(e.getMessage()).color(TextColor.RED)); - } - }); - } - - @Override - public String getDescription() { - return plugin.getI18n().get("usage_coupon"); - } -} diff --git a/velocity/src/main/java/net/buycraft/plugin/velocity/command/ForceCheckSubcommand.java b/velocity/src/main/java/net/buycraft/plugin/velocity/command/ForceCheckSubcommand.java deleted file mode 100644 index c3117c32..00000000 --- a/velocity/src/main/java/net/buycraft/plugin/velocity/command/ForceCheckSubcommand.java +++ /dev/null @@ -1,40 +0,0 @@ -package net.buycraft.plugin.velocity.command; - -import com.velocitypowered.api.command.CommandSource; -import net.buycraft.plugin.velocity.BuycraftPlugin; -import net.kyori.text.TextComponent; -import net.kyori.text.format.TextColor; - -public class ForceCheckSubcommand implements Subcommand { - private final BuycraftPlugin plugin; - - public ForceCheckSubcommand(final BuycraftPlugin plugin) { - this.plugin = plugin; - } - - @Override - public void execute(CommandSource sender, String[] args) { - if (args.length != 0) { - sender.sendMessage(TextComponent.of(plugin.getI18n().get("no_params")).color(TextColor.RED)); - return; - } - - if (plugin.getApiClient() == null) { - sender.sendMessage(TextComponent.of(plugin.getI18n().get("need_secret_key")).color(TextColor.RED)); - return; - } - - if (plugin.getDuePlayerFetcher().inProgress()) { - sender.sendMessage(TextComponent.of(plugin.getI18n().get("already_checking_for_purchases")).color(TextColor.RED)); - return; - } - - plugin.getPlatform().executeAsync(() -> plugin.getDuePlayerFetcher().run(false)); - sender.sendMessage(TextComponent.of(plugin.getI18n().get("forcecheck_queued")).color(TextColor.GREEN)); - } - - @Override - public String getDescription() { - return plugin.getI18n().get("usage_forcecheck"); - } -} diff --git a/velocity/src/main/java/net/buycraft/plugin/velocity/command/InformationSubcommand.java b/velocity/src/main/java/net/buycraft/plugin/velocity/command/InformationSubcommand.java deleted file mode 100644 index 955f3f85..00000000 --- a/velocity/src/main/java/net/buycraft/plugin/velocity/command/InformationSubcommand.java +++ /dev/null @@ -1,46 +0,0 @@ -package net.buycraft.plugin.velocity.command; - -import com.velocitypowered.api.command.CommandSource; -import net.buycraft.plugin.velocity.BuycraftPlugin; -import net.kyori.text.TextComponent; -import net.kyori.text.format.TextColor; - -public class InformationSubcommand implements Subcommand { - private final BuycraftPlugin plugin; - - public InformationSubcommand(final BuycraftPlugin plugin) { - this.plugin = plugin; - } - - @Override - public void execute(CommandSource sender, String[] args) { - if (args.length != 0) { - sender.sendMessage(TextComponent.of(plugin.getI18n().get("no_params")).color(TextColor.RED)); - return; - } - - if (plugin.getApiClient() == null) { - sender.sendMessage(TextComponent.of(plugin.getI18n().get("need_secret_key")).color(TextColor.RED)); - return; - } - - if (plugin.getServerInformation() == null) { - sender.sendMessage(TextComponent.of(plugin.getI18n().get("information_no_server")).color(TextColor.RED)); - return; - } - - sender.sendMessage(TextComponent.of(plugin.getI18n().get("information_title")).color(TextColor.GRAY)); - sender.sendMessage(TextComponent.of(plugin.getI18n().get("information_server", - plugin.getServerInformation().getServer().getName(), - plugin.getServerInformation().getAccount().getName())).color(TextColor.GRAY)); - sender.sendMessage(TextComponent.of(plugin.getI18n().get("information_currency", - plugin.getServerInformation().getAccount().getCurrency().getIso4217())).color(TextColor.GRAY)); - sender.sendMessage(TextComponent.of(plugin.getI18n().get("information_domain", - plugin.getServerInformation().getAccount().getDomain())).color(TextColor.GRAY)); - } - - @Override - public String getDescription() { - return plugin.getI18n().get("usage_information"); - } -} diff --git a/velocity/src/main/java/net/buycraft/plugin/velocity/command/ReportCommand.java b/velocity/src/main/java/net/buycraft/plugin/velocity/command/ReportCommand.java deleted file mode 100644 index 852a7d51..00000000 --- a/velocity/src/main/java/net/buycraft/plugin/velocity/command/ReportCommand.java +++ /dev/null @@ -1,60 +0,0 @@ -package net.buycraft.plugin.velocity.command; - -import com.velocitypowered.api.command.CommandSource; -import net.buycraft.plugin.shared.util.ReportBuilder; -import net.buycraft.plugin.velocity.BuycraftPlugin; -import net.kyori.text.TextComponent; -import net.kyori.text.format.TextColor; - -import java.io.BufferedWriter; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardOpenOption; -import java.text.SimpleDateFormat; -import java.util.Date; - -public class ReportCommand implements Subcommand { - private final BuycraftPlugin plugin; - - public ReportCommand(BuycraftPlugin plugin) { - this.plugin = plugin; - } - - @Override - public void execute(final CommandSource sender, String[] args) { - sender.sendMessage(TextComponent.of(plugin.getI18n().get("report_wait")).color(TextColor.YELLOW)); - - plugin.getPlatform().executeAsync(() -> { - InetSocketAddress listener = plugin.getServer().getBoundAddress(); - ReportBuilder builder = ReportBuilder.builder() - .client(plugin.getHttpClient()) - .configuration(plugin.getConfiguration()) - .platform(plugin.getPlatform()) - .duePlayerFetcher(plugin.getDuePlayerFetcher()) - .ip(listener.getAddress().toString()) - .port(listener.getPort()) - .serverOnlineMode(plugin.getServer().getConfiguration().isOnlineMode()) - .build(); - - SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss"); - String filename = "report-" + f.format(new Date()) + ".txt"; - Path p = plugin.getDataFolder().toPath().resolve(filename); - String generated = builder.generate(); - try (BufferedWriter w = Files.newBufferedWriter(p, StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW)) { - w.write(generated); - sender.sendMessage(TextComponent.of(plugin.getI18n().get("report_saved", p.toAbsolutePath().toString())).color(TextColor.YELLOW)); - } catch (IOException e) { - sender.sendMessage(TextComponent.of(plugin.getI18n().get("report_cant_save")).color(TextColor.RED)); - plugin.getLogger().info(generated); - } - }); - } - - @Override - public String getDescription() { - return plugin.getI18n().get("usage_report"); - } -} diff --git a/velocity/src/main/java/net/buycraft/plugin/velocity/command/SecretSubcommand.java b/velocity/src/main/java/net/buycraft/plugin/velocity/command/SecretSubcommand.java deleted file mode 100644 index f27c8572..00000000 --- a/velocity/src/main/java/net/buycraft/plugin/velocity/command/SecretSubcommand.java +++ /dev/null @@ -1,61 +0,0 @@ -package net.buycraft.plugin.velocity.command; - -import com.velocitypowered.api.command.CommandSource; -import net.buycraft.plugin.BuyCraftAPI; -import net.buycraft.plugin.data.responses.ServerInformation; -import net.buycraft.plugin.velocity.BuycraftPlugin; -import net.kyori.text.TextComponent; -import net.kyori.text.format.TextColor; - -import java.io.IOException; -import java.util.logging.Level; - -public class SecretSubcommand implements Subcommand { - private final BuycraftPlugin plugin; - - public SecretSubcommand(final BuycraftPlugin plugin) { - this.plugin = plugin; - } - - @Override - public void execute(final CommandSource sender, final String[] args) { - if (!sender.equals(plugin.getServer().getConsoleCommandSource())) { - sender.sendMessage(TextComponent.of(plugin.getI18n().get("secret_console_only")).color(TextColor.RED)); - return; - } - - if (args.length != 1) { - sender.sendMessage(TextComponent.of(plugin.getI18n().get("secret_need_key")).color(TextColor.RED)); - return; - } - - plugin.getPlatform().executeAsync(() -> { - BuyCraftAPI client = BuyCraftAPI.create(args[0], plugin.getHttpClient()); - try { - plugin.updateInformation(client); - } catch (IOException e) { - plugin.getLogger().error("Unable to verify secret", e); - sender.sendMessage(TextComponent.of(plugin.getI18n().get("secret_does_not_work")).color(TextColor.RED)); - return; - } - - ServerInformation information = plugin.getServerInformation(); - plugin.setApiClient(client); - plugin.getConfiguration().setServerKey(args[0]); - try { - plugin.saveConfiguration(); - } catch (IOException e) { - sender.sendMessage(TextComponent.of(plugin.getI18n().get("secret_cant_be_saved")).color(TextColor.RED)); - } - - sender.sendMessage(TextComponent.of(plugin.getI18n().get("secret_success", - information.getServer().getName(), information.getAccount().getName())).color(TextColor.GREEN)); - plugin.getPlatform().executeAsync(plugin.getDuePlayerFetcher()); - }); - } - - @Override - public String getDescription() { - return "Sets the secret key to use for this server."; - } -} diff --git a/velocity/src/main/java/net/buycraft/plugin/velocity/command/Subcommand.java b/velocity/src/main/java/net/buycraft/plugin/velocity/command/Subcommand.java deleted file mode 100644 index f13b8369..00000000 --- a/velocity/src/main/java/net/buycraft/plugin/velocity/command/Subcommand.java +++ /dev/null @@ -1,9 +0,0 @@ -package net.buycraft.plugin.velocity.command; - -import com.velocitypowered.api.command.CommandSource; - -public interface Subcommand { - void execute(CommandSource sender, String[] args); - - String getDescription(); -} diff --git a/velocity/src/main/java/net/buycraft/plugin/velocity/util/VersionCheck.java b/velocity/src/main/java/net/buycraft/plugin/velocity/util/VersionCheck.java deleted file mode 100644 index 6a98ed6d..00000000 --- a/velocity/src/main/java/net/buycraft/plugin/velocity/util/VersionCheck.java +++ /dev/null @@ -1,64 +0,0 @@ -package net.buycraft.plugin.velocity.util; - -import com.velocitypowered.api.event.Subscribe; -import com.velocitypowered.api.event.connection.PostLoginEvent; -import net.buycraft.plugin.data.responses.Version; -import net.buycraft.plugin.shared.util.VersionUtil; -import net.buycraft.plugin.velocity.BuycraftPlugin; -import net.kyori.text.TextComponent; -import net.kyori.text.format.TextColor; - -import java.io.IOException; -import java.util.concurrent.TimeUnit; - -import static net.buycraft.plugin.shared.util.VersionUtil.isVersionGreater; - -public class VersionCheck { - private final BuycraftPlugin plugin; - private final String pluginVersion; - private final String secret; - private Version lastKnownVersion; - private boolean upToDate = true; - - public VersionCheck(final BuycraftPlugin plugin, final String pluginVersion, final String secret) { - this.plugin = plugin; - this.pluginVersion = pluginVersion; - this.secret = secret; - } - - public void verify() throws IOException { - if (pluginVersion.endsWith("-SNAPSHOT")) { - return; // SNAPSHOT versions ignore updates - } - - lastKnownVersion = VersionUtil.getVersion(plugin.getHttpClient(), "bungeecord", secret); - if (lastKnownVersion == null) { - return; - } - - // Compare versions - String latestVersionString = lastKnownVersion.getVersion(); - if (!latestVersionString.equals(pluginVersion)) { - upToDate = !isVersionGreater(pluginVersion, latestVersionString); - if (!upToDate) { - plugin.getLogger().info(plugin.getI18n().get("update_available", lastKnownVersion.getVersion())); - } - } - } - - @Subscribe - public void onPlayerJoin(final PostLoginEvent event) { - if (event.getPlayer().hasPermission("buycraft.admin") && !upToDate) { - plugin.getPlatform().executeAsyncLater(() -> - event.getPlayer().sendMessage(TextComponent.of(plugin.getI18n().get("update_available", lastKnownVersion.getVersion())).color(TextColor.YELLOW)), 3, TimeUnit.SECONDS); - } - } - - public Version getLastKnownVersion() { - return this.lastKnownVersion; - } - - public boolean isUpToDate() { - return this.upToDate; - } -} diff --git a/velocity/src/main/java/org/kitteh/craftirc/sponge/util/versioning/Transform.java b/velocity/src/main/java/org/kitteh/craftirc/sponge/util/versioning/Transform.java deleted file mode 100644 index c96ef016..00000000 --- a/velocity/src/main/java/org/kitteh/craftirc/sponge/util/versioning/Transform.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * * Copyright (C) 2015 Matt Baxter http://kitteh.org - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, - * modify, merge, publish, distribute, sublicense, and/or sell copies - * of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package org.kitteh.craftirc.sponge.util.versioning; - -import de.icongmbh.oss.maven.plugin.javassist.ClassTransformer; -import javassist.ClassPool; -import javassist.CtClass; -import javassist.NotFoundException; -import javassist.bytecode.AnnotationsAttribute; -import javassist.bytecode.annotation.Annotation; -import javassist.bytecode.annotation.StringMemberValue; -import net.buycraft.plugin.velocity.BuycraftPlugin; - -import java.util.Properties; - -/** - * Used purely to set the version value on the Plugin. Don't bother touching. - */ -public class Transform extends ClassTransformer { - private String version; - - @Override - protected boolean shouldTransform(final CtClass clazz) throws NotFoundException { - CtClass buycraftPlugin = ClassPool.getDefault().get(BuycraftPlugin.class.getName()); - return !clazz.equals(buycraftPlugin) && clazz.subtypeOf(buycraftPlugin); - } - - @Override - protected void applyTransformations(CtClass clazz) throws Exception { - AnnotationsAttribute attribute = (AnnotationsAttribute) clazz.getClassFile().getAttribute(AnnotationsAttribute.visibleTag); - Annotation annotation = attribute.getAnnotation("com.velocitypowered.api.plugin.Plugin"); - StringMemberValue version = (StringMemberValue) annotation.getMemberValue("version"); - version.setValue(this.version); - attribute.setAnnotation(annotation); - } - - @Override - public void configure(final Properties properties) { - if (properties == null || (this.version = properties.getProperty("version")) == null) { - throw new AssertionError("Version not set!"); - } - } -} \ No newline at end of file