3
0
Fork 0

Moved to Polymart check, updated deps

This commit is contained in:
stijnb1234 2022-05-16 22:12:20 +02:00
parent d20f7376de
commit b2d7a03762
7 changed files with 236 additions and 421 deletions

View file

@ -6,7 +6,7 @@
<groupId>nl.SBDeveloper</groupId> <groupId>nl.SBDeveloper</groupId>
<artifactId>ThemeParkPlus</artifactId> <artifactId>ThemeParkPlus</artifactId>
<version>3.0.0</version> <version>3.1.0</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>ThemeParkPlus</name> <name>ThemeParkPlus</name>
@ -121,7 +121,7 @@
<dependency> <dependency>
<groupId>org.spigotmc</groupId> <groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId> <artifactId>spigot-api</artifactId>
<version>1.18.1-R0.1-SNAPSHOT</version> <version>1.18.2-R0.1-SNAPSHOT</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
@ -129,7 +129,7 @@
<artifactId>themepark</artifactId> <artifactId>themepark</artifactId>
<version>3.1.1</version> <version>3.1.1</version>
<scope>system</scope> <scope>system</scope>
<systemPath>${pom.basedir}/src/lib/themepark-3.1.1.jar</systemPath> <systemPath>${pom.basedir}/src/lib/ThemePark_v3.1.1.jar</systemPath>
</dependency> </dependency>
<dependency> <dependency>
<groupId>me.paradoxpixel</groupId> <groupId>me.paradoxpixel</groupId>
@ -147,7 +147,7 @@
<dependency> <dependency>
<groupId>de.tr7zw</groupId> <groupId>de.tr7zw</groupId>
<artifactId>item-nbt-api</artifactId> <artifactId>item-nbt-api</artifactId>
<version>2.8.0</version> <version>2.9.2</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.github.MilkBowl</groupId> <groupId>com.github.MilkBowl</groupId>

View file

@ -5,9 +5,9 @@ import nl.sbdeveloper.themeparkplus.commands.TPPCMD;
import nl.sbdeveloper.themeparkplus.listeners.*; import nl.sbdeveloper.themeparkplus.listeners.*;
import nl.sbdeveloper.themeparkplus.managers.DBManager; import nl.sbdeveloper.themeparkplus.managers.DBManager;
import nl.sbdeveloper.themeparkplus.sbutils.UpdateManager; import nl.sbdeveloper.themeparkplus.sbutils.UpdateManager;
import nl.sbdeveloper.themeparkplus.sbutils.Verify;
import nl.sbdeveloper.themeparkplus.sbutils.YamlFile; import nl.sbdeveloper.themeparkplus.sbutils.YamlFile;
import nl.sbdeveloper.themeparkplus.util.Inventory; import nl.sbdeveloper.themeparkplus.util.Inventory;
import nl.sbdeveloper.themeparkplus.util.License;
import org.bstats.bukkit.Metrics; import org.bstats.bukkit.Metrics;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
@ -80,7 +80,12 @@ public final class ThemeParkPlus extends JavaPlugin {
return; return;
} }
new License(this, "TP", license); getLogger().info("This copy is bought by %%__USERNAME__%% (%%__USER__%%).");
getLogger().info("Validating your purchase...");
Verify v = new Verify(this);
if (v.isValidated()) {
getLogger().info("Your purchase is valid. Thanks for your purchase!");
}
if (Bukkit.getPluginManager().getPlugin("WorldEdit") == null) { if (Bukkit.getPluginManager().getPlugin("WorldEdit") == null) {
Bukkit.getLogger().severe("[ThemeParkPlus] Missing WorldEdit! Please install it first."); Bukkit.getLogger().severe("[ThemeParkPlus] Missing WorldEdit! Please install it first.");
@ -153,7 +158,7 @@ public final class ThemeParkPlus extends JavaPlugin {
new Metrics(this, 5023); new Metrics(this, 5023);
if (getSConfig().getFile().getBoolean("UpdateChecker.Enabled")) { if (getSConfig().getFile().getBoolean("UpdateChecker.Enabled")) {
UpdateManager updateManager = new UpdateManager(this, 7, license); UpdateManager updateManager = new UpdateManager(this, UpdateManager.CheckType.POLYMART_PAID);
updateManager.handleResponse((versionResponse, version) -> { updateManager.handleResponse((versionResponse, version) -> {
switch (versionResponse) { switch (versionResponse) {

View file

@ -8,7 +8,7 @@ import nl.sbdeveloper.themeparkplus.api.objects.MalfunctionReport;
import nl.sbdeveloper.themeparkplus.api.objects.WaitingRow; import nl.sbdeveloper.themeparkplus.api.objects.WaitingRow;
import nl.sbdeveloper.themeparkplus.sbutils.LocationSerializer; import nl.sbdeveloper.themeparkplus.sbutils.LocationSerializer;
import nl.sbdeveloper.themeparkplus.sbutils.SQLiteDB; import nl.sbdeveloper.themeparkplus.sbutils.SQLiteDB;
import nl.sbdeveloper.themeparkplus.util.License; import nl.sbdeveloper.themeparkplus.sbutils.Verify;
import nl.sbdeveloper.themeparkplus.util.LocationGsonAdapter; import nl.sbdeveloper.themeparkplus.util.LocationGsonAdapter;
import org.bukkit.Location; import org.bukkit.Location;
@ -95,7 +95,7 @@ public class DBManager {
} }
public void save() { public void save() {
if (License.isValid() == null || !License.isValid()) return; if (Verify.isValid() == null || !Verify.isValid()) return;
for (Map.Entry<Location, Gate> entry : PlusAPI.getGates().entrySet()) { for (Map.Entry<Location, Gate> entry : PlusAPI.getGates().entrySet()) {
Gson gson = getGson(); Gson gson = getGson();

View file

@ -1,8 +1,13 @@
/*
* This file is part of TPRidecountAddon.
* Copyright (c) 2018-2022. SBDevelopment - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
* Written by Stijn Bannink <stijnbannink23@gmail.com>, April 2022
*/
package nl.sbdeveloper.themeparkplus.sbutils; package nl.sbdeveloper.themeparkplus.sbutils;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
@ -10,66 +15,62 @@ import org.bukkit.plugin.java.JavaPlugin;
import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.HttpsURLConnection;
import java.io.*; import java.io.*;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.nio.channels.Channels; import java.nio.channels.Channels;
import java.nio.channels.FileChannel; import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel; import java.nio.channels.ReadableByteChannel;
import java.nio.charset.StandardCharsets;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
/** /**
* Update class for SBDevelopment * Update checker class
*
* @author Stijn [SBDeveloper] * @author Stijn [SBDeveloper]
* @since 05-03-2020 * @since 05-03-2020
* @version 2.0 [26-12-2020] - This class supports the v2 Update API * @version 2.2 [17-04-2022] - Added Polymart support
*
* <p>&copy; Stijn Bannink [stijnbannink23@gmail.com] - All rights reserved.</p>
*/ */
public class UpdateManager { public class UpdateManager {
private static final String SPIGOT_API = "https://api.spigotmc.org/legacy/update.php?resource=%d"; private static final String SPIGOT_API = "https://api.spigotmc.org/legacy/update.php?resource=%d";
private static final String SPIGOT_DOWNLOAD = "http://api.spiget.org/v2/resources/%s/download"; private static final String SPIGOT_DOWNLOAD = "https://api.spiget.org/v2/resources/%s/download";
private static final String SBDPLUGINS_API = "https://updates.sbdplugins.nl/api/v2/plugins/%d"; private static final String POLYMART_API = "https://api.polymart.org/v1/getResourceInfoSimple/?resource_id=%d&key=version";
private static final String SBDPLUGINS_DOWNLOAD = "https://updates.sbdplugins.nl/api/v2/download/%d"; private static final String POLYMART_DOWNLOAD = "https://api.polymart.org/v1/requestUpdateURL/?inject_version=%d&resource_id=%d&user_id=%d&nonce=%d&download_agent=%d&download_time=%d&download_token=%s";
private final Plugin plugin; private final Plugin plugin;
private final Version currentVersion; private final Version currentVersion;
private final int resourceID;
private final CheckType type; private final CheckType type;
private final String license;
//Spigot & Polymart
private final int resourceID;
//Polymart only
private int injector_version;
private int user_id;
private int nonce;
private int download_agent;
private int download_time;
private String download_token;
private BiConsumer<VersionResponse, Version> versionResponse; private BiConsumer<VersionResponse, Version> versionResponse;
private BiConsumer<DownloadResponse, String> downloadResponse; private BiConsumer<DownloadResponse, String> downloadResponse;
/** /**
* Construct a new UpdateManager for Spigot * Construct a new UpdateManager
* *
* @param plugin The javaplugin (Main class) * @param plugin The plugin instance
* @param resourceID The resourceID on spigot/sbdplugins
*/ */
public UpdateManager(Plugin plugin, int resourceID) { public UpdateManager(Plugin plugin, CheckType type) {
this.plugin = plugin; this.plugin = plugin;
this.currentVersion = new Version(plugin.getDescription().getVersion()); this.currentVersion = new Version(plugin.getDescription().getVersion());
this.resourceID = resourceID; this.type = type;
this.type = CheckType.SPIGOT; this.resourceID = Integer.parseInt("%%__RESOURCE__%%");
this.license = null; if (type == CheckType.POLYMART_PAID) {
} this.injector_version = Integer.parseInt("%%__INJECT_VER__%%");
this.user_id = Integer.parseInt("%%__USER__%%");
/** this.nonce = Integer.parseInt("%%__NONCE__%%");
* Construct a new UpdateManager for SBDPlugins this.download_agent = Integer.parseInt("%%__AGENT__%%");
* this.download_time = Integer.parseInt("%%__TIMESTAMP__%%");
* @param plugin The javaplugin (Main class) this.download_token = "%%__VERIFY_TOKEN__%%";
* @param resourceID The resourceID on spigot/sbdplugins }
* @param license The license for the download
*/
public UpdateManager(Plugin plugin, int resourceID, String license) {
this.plugin = plugin;
this.currentVersion = new Version(plugin.getDescription().getVersion());
this.resourceID = resourceID;
this.type = CheckType.SBDPLUGINS;
this.license = license;
} }
/** /**
@ -93,25 +94,16 @@ public class UpdateManager {
public void check() { public void check() {
Bukkit.getScheduler().runTaskAsynchronously(this.plugin, () -> { Bukkit.getScheduler().runTaskAsynchronously(this.plugin, () -> {
try { try {
BufferedReader in = null; HttpsURLConnection con;
if (type == CheckType.SPIGOT) { if (type == CheckType.POLYMART_PAID) {
HttpsURLConnection con = (HttpsURLConnection) new URL(String.format(SPIGOT_API, this.resourceID)).openConnection(); con = (HttpsURLConnection) new URL(String.format(POLYMART_API, this.resourceID)).openConnection();
con.setRequestMethod("GET"); } else {
con.setRequestProperty("User-Agent", "Mozilla/5.0"); con = (HttpsURLConnection) new URL(String.format(SPIGOT_API, this.resourceID)).openConnection();
in = new BufferedReader(new InputStreamReader(con.getInputStream()));
} else if (type == CheckType.SBDPLUGINS) {
HttpsURLConnection con = (HttpsURLConnection) new URL(String.format(SBDPLUGINS_API, this.resourceID)).openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
in = new BufferedReader(new InputStreamReader(con.getInputStream()));
} }
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "SBDChecker/2.1");
if (in == null) return; BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String version;
String inputLine; String inputLine;
StringBuilder response = new StringBuilder(); StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) { while ((inputLine = in.readLine()) != null) {
@ -119,21 +111,7 @@ public class UpdateManager {
} }
in.close(); in.close();
JsonParser parser = new JsonParser(); Version onlineVersion = new Version(response.toString());
if (type == CheckType.SPIGOT) {
JsonArray array = parser.parse(response.toString()).getAsJsonArray();
version = array.get(0).getAsJsonObject().get("name").getAsString();
} else {
JsonObject object = parser.parse(response.toString()).getAsJsonObject();
version = object.get("version").getAsString();
}
if (version == null) return;
Version onlineVersion = new Version(version);
VersionResponse verRes = this.currentVersion.check(onlineVersion); VersionResponse verRes = this.currentVersion.check(onlineVersion);
@ -166,37 +144,16 @@ public class UpdateManager {
ReadableByteChannel channel; ReadableByteChannel channel;
try { try {
//https://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-using-java //https://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-using-java
int response; HttpsURLConnection connection;
InputStream stream; if (type == CheckType.POLYMART_PAID) {
if (type == CheckType.SBDPLUGINS) { connection = (HttpsURLConnection) new URL(String.format(POLYMART_DOWNLOAD, this.injector_version, this.resourceID, this.user_id, this.nonce, this.download_agent, this.download_time, this.download_token)).openConnection();
HttpURLConnection connection = (HttpURLConnection) new URL(String.format(SBDPLUGINS_DOWNLOAD, this.resourceID)).openConnection();
String urlParameters = "license=" + license + "&port=" + Bukkit.getPort();
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.write(postData);
wr.close();
response = connection.getResponseCode();
stream = connection.getInputStream();
} else { } else {
HttpsURLConnection connection = (HttpsURLConnection) new URL(String.format(SPIGOT_DOWNLOAD, this.resourceID)).openConnection(); connection = (HttpsURLConnection) new URL(String.format(SPIGOT_DOWNLOAD, this.resourceID)).openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
response = connection.getResponseCode();
stream = connection.getInputStream();
} }
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
if (response != 200) { InputStream stream = connection.getInputStream();
if (connection.getResponseCode() != 200) {
BufferedReader in = new BufferedReader(new InputStreamReader(stream)); BufferedReader in = new BufferedReader(new InputStreamReader(stream));
String inputLine; String inputLine;
@ -206,7 +163,7 @@ public class UpdateManager {
} }
in.close(); in.close();
throw new RuntimeException("Download returned status #" + response, new Throwable(responsestr.toString())); throw new RuntimeException("Download returned status #" + connection.getResponseCode(), new Throwable(responsestr.toString()));
} }
channel = Channels.newChannel(stream); channel = Channels.newChannel(stream);
@ -259,8 +216,8 @@ public class UpdateManager {
} }
} }
private enum CheckType { public enum CheckType {
SPIGOT, SBDPLUGINS SPIGOT, POLYMART_PAID
} }
public enum VersionResponse { public enum VersionResponse {

View file

@ -0,0 +1,165 @@
/*
* This file is part of ActionFoto.
* Copyright (c) 2018-2022. SBDevelopment - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
* Written by Stijn Bannink <stijnbannink23@gmail.com>, April 2022
*/
package nl.sbdeveloper.themeparkplus.sbutils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Purchase verification class
*
* @author Stijn [SBDeveloper]
* @version 2.0 [17-04-2022] - Updated to Polymart
* @since 23-12-2019
*/
public class Verify implements Listener {
private static final String endpointURL = "https://api.polymart.org/v1/verifyPurchase/?inject_version=%d&resource_id=%d&user_id=%d&nonce=%d&download_agent=%d&download_time=%d&download_token=%s";
private final JavaPlugin plugin; // The plugin instance
private final int resourceID;
private final int injector_version;
private final int user_id;
private final int nonce;
private final int download_agent;
private final int download_time;
private final String download_token;
private String invalidReason = null; // The reason the license is invalid, if null it's not invalid!
private static Boolean valid = null; // If true, it's valid, if false, it's not valid, if null it's not checked!
/**
* Construct a new license
*
* @param plugin The plugin
*/
public Verify(JavaPlugin plugin) {
this.plugin = plugin;
this.resourceID = Integer.parseInt("%%__RESOURCE__%%");
this.injector_version = Integer.parseInt("%%__INJECT_VER__%%");
this.user_id = Integer.parseInt("%%__USER__%%");
this.nonce = Integer.parseInt("%%__NONCE__%%");
this.download_agent = Integer.parseInt("%%__AGENT__%%");
this.download_time = Integer.parseInt("%%__TIMESTAMP__%%");
this.download_token = "%%__VERIFY_TOKEN__%%";
Bukkit.getPluginManager().registerEvents(this, plugin);
validate();
}
@EventHandler
public void onJoin(PlayerJoinEvent e) {
if (this.invalidReason == null) return;
Player p = e.getPlayer();
if (p.isOp() || p.hasPermission("sbd.licensemessages")) {
Bukkit.getScheduler().runTaskLater(this.plugin, () -> p.sendMessage(ChatColor.GOLD + "[" + ChatColor.RED + this.plugin.getName() + ChatColor.GOLD + "] " + ChatColor.RED + "The license is incorrect! Reason: " + ChatColor.GOLD + this.invalidReason), 5 * 20L /* 5 sec */);
}
}
/**
* Validate the purchase
*/
private void validate() {
try {
URL url = new URL(String.format(endpointURL, this.injector_version, this.resourceID, this.user_id, this.nonce, this.download_agent, this.download_time, this.download_token));
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "SBDVerify/2.0");
con.setConnectTimeout(5000); //Timeout after 5 sec.
con.setReadTimeout(5000); //Timeout after 5 sec.
int code = con.getResponseCode();
if (code != 200) {
disable("Could not send the validating request.");
return;
}
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JsonObject json = new JsonParser().parse(response.toString()).getAsJsonObject();
if (json == null) {
disable("Could not send the validating request.");
return;
}
if (!json.has("response")) {
disable("An invalid response was returned by the validating request.");
return;
}
JsonObject resp = json.get("response").getAsJsonObject();
if (!resp.has("success")) {
disable("An invalid response was returned by the validating request.");
return;
}
if (!resp.get("success").getAsBoolean()) {
disable("The purchase of this plugin could not be verified.");
}
} catch (IOException e) {
disable("Could not send the validating request.");
}
}
/**
* Disable the plugin (private)
*
* @param reason The disabling reason
*/
private void disable(String reason) {
this.invalidReason = reason;
Bukkit.getScheduler().runTask(this.plugin, () -> {
valid = false;
plugin.getLogger().severe("Stopping plugin because licensing system check failed.");
plugin.getLogger().severe("Reason: " + reason);
plugin.getLogger().severe("Contact the developer if you believe something is wrong on their side.");
Bukkit.getPluginManager().disablePlugin(this.plugin);
});
}
/**
* Check if the license is valid
*
* @return true = VALID, false = INVALID, null = UNCHECKED
*/
public Boolean isValidated() {
return this.invalidReason == null;
}
/**
* Check if the license is valid
*
* @return true = VALID, false = INVALID, null = UNCHECKED
*/
public static Boolean isValid() {
return valid;
}
}

View file

@ -1,312 +0,0 @@
package nl.sbdeveloper.themeparkplus.util;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* License class for SBDevelopment
*
* v1.6 - Changed on 06-08-2020
*
* @author Stijn [SBDeveloper]
* @since 23-12-2019
*/
public class License implements Listener {
/*
This file is part of ThemeParkRidecountAddon.
Copyright (c) 2018-2020 SBDevelopment - All Rights Reserved
Unauthorized copying of this file, via any medium is strictly prohibited
Proprietary and confidential
Written by Stijn Bannink <stijnbannink23@gmail.com>, January 2020
*/
private final JavaPlugin plugin; // The plugin instance
private final String license; // The license code
private final String prefix; // The correct prefix for this plugin
private String invalidReason; // The reason the license is invalid, if null it's not invalid!
private static Boolean valid; // If true, it's valid, if false, it's not valid, if null it's not checked!
/**
* Construct a new license
* @param plugin The Main class [Javaplugin]
* @param prefix The prefix, like TPP or AF
* @param license The license from the config
*/
public License(JavaPlugin plugin, String prefix, String license) {
this.prefix = prefix;
this.plugin = plugin;
this.license = license;
Bukkit.getPluginManager().registerEvents(this, plugin);
validateLicense();
}
@EventHandler
public void onJoin(PlayerJoinEvent e) {
if (this.invalidReason == null) return;
Player p = e.getPlayer();
if (p.isOp() || p.hasPermission("sbd.licensemessages")) {
Bukkit.getScheduler().runTaskLater(this.plugin, () -> p.sendMessage(ChatColor.GOLD + "[" + ChatColor.RED + this.plugin.getName() + ChatColor.GOLD + "] " + ChatColor.RED + "The license is incorrect! Reason: " + ChatColor.GOLD + this.invalidReason), 3 * 20L /* 3 sec */);
}
}
/**
* Check a license
*
*/
private void validateLicense() {
//STEP 1: Check prefix
if (!this.license.split("-")[0].contains(this.prefix)) {
disable("You used the wrong license for this product.");
return;
}
//STEP 2: Send license request
String url = "https://sbdplugins.nl/wp-json/lmfwc/v2/licenses/" + this.license;
JsonObject response;
try {
response = sendGETRequestJSON(url);
} catch (IOException e) {
disable("Something went wrong while sending the request.");
return;
}
if (response == null) {
disable("Something went wrong while sending the request. Did you even fill out a license?");
return;
}
JsonObject dataObject = response.get("data").getAsJsonObject();
//STEP 3: Check status
switch(dataObject.get("status").getAsString()) {
case "2":
//Delivered -> Try to activate (double check timesActivated)
break;
case "3":
//Activated!
break;
default:
disable("Your license has a wrong status.");
return;
}
//STEP 4: Check times activated, and if not activated, activate.
if (dataObject.get("timesActivated").isJsonNull() || dataObject.get("timesActivated").getAsString().equalsIgnoreCase("0")) {
activate();
return;
}
//STEP 5: Check expire date
if (dataObject.get("expiresAt").isJsonNull()) {
disable("Your license has no expire date.");
return;
}
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date;
try {
date = format.parse(dataObject.get("expiresAt").getAsString());
} catch (ParseException e) {
e.printStackTrace();
disable("Your license has a wrong expire date.");
return;
}
if (date == null) {
disable("Your license has a wrong expire date.");
return;
}
if (!(date.after(new Date()))) {
disable("Your license has expired.");
return;
}
//STEP 6: Check IP and port.
if (!dataObject.get("ipcheck").getAsBoolean()) {
disable("Your license has been used with another IP. Update it in our Discord.");
return;
}
if (dataObject.get("port").isJsonNull()) {
disable("Your license has no port.");
return;
}
String por = dataObject.get("port").getAsString();
if (!checkPortValue(Bukkit.getServer().getPort(), por)) {
disable("Your license has been used with another Port. Update it in our Discord.");
return;
}
valid = true;
}
/**
* Activate the license
*
*/
private void activate() {
//STEP 1: Send license activate request
String url = "https://sbdplugins.nl/wp-json/lmfwc/v2/licenses/activate/" + this.license + "?port=" + Bukkit.getServer().getPort();
@Nullable JsonObject response;
try {
response = sendGETRequestJSON(url);
} catch (IOException e) {
disable("Something went wrong while sending the request.");
return;
}
if (response == null) {
disable("Something went wrong while sending the request. Did you even fill out a license?");
return;
}
JsonObject dataObject = response.get("data").getAsJsonObject();
//STEP 2: Check status
switch(dataObject.get("status").getAsString()) {
case "2":
//Delivered -> STILL NOT ACTIVATED?! -> Double check
break;
case "3":
//Activated!
break;
default:
disable("Your license has a wrong status.");
return;
}
//STEP 3: Check times activated, and if still not activated, disable.
if (dataObject.get("timesActivated").isJsonNull() || dataObject.get("timesActivated").getAsString().equalsIgnoreCase("0")) {
disable("Couldn't activate the license.");
}
}
/**
* Disable the plugin (private)
*
* @param reason The disabling reason
*/
private void disable(String reason) {
this.invalidReason = reason;
Bukkit.getScheduler().runTask(this.plugin, () -> {
valid = false;
Bukkit.getLogger().severe("[" + this.plugin.getName() + "] Stopping plugin because licensing system check failed.");
Bukkit.getLogger().severe("[" + this.plugin.getName() + "] Reason: " + reason);
Bukkit.getLogger().severe("[" + this.plugin.getName() + "] Contact the developer if you believe something is wrong on their side.");
Bukkit.getPluginManager().disablePlugin(this.plugin);
});
}
/**
* Send an GET request with JSONObject response
*
* @param uri The URL
*
* @return The JSONObject
* @throws IOException URL errors
*/
private JsonObject sendGETRequestJSON(String uri) throws IOException {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
String authStringEnc = "Y2tfMGEzNWEzMWE2NzExNmM3NDg2MGEwYTJhNjUxNGVjZjM4NTBmM2JmMDpjc185NmYxZGNlYjI4MWRkZDExOTBjMzQ3ZjJjYzMwMGNjZTIzYWNhODI1";
con.setRequestProperty("Authorization", "Basic " + authStringEnc);
int code = con.getResponseCode();
if (code == 404) {
return null;
}
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
String inputLine;
boolean firstLine = true;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
if (firstLine) { inputLine = removeUTF8BOM(inputLine); firstLine = false; }
response.append(inputLine);
}
in.close();
JsonParser parser = new JsonParser();
return parser.parse(response.toString()).getAsJsonObject();
}
private boolean checkPortValue(int input, String dataValue) {
//STEP 1: Check wildcard
if (dataValue.equals("*")) return true;
//STEP 2: Check if equals
try {
int dataVal = Integer.parseInt(dataValue);
return input == dataVal;
} catch (NumberFormatException ignored) {}
//STEP 3: Check if range
if (dataValue.contains("-")) {
String[] dataSplit = dataValue.split("-");
//STEP 3.1: Check if min or max is wildcard
if (dataSplit[0].equals("*") && !dataSplit[1].equals("*")) {
int max = Integer.parseInt(dataSplit[1]);
return input <= max;
} else if (dataSplit[1].equals("*") && !dataSplit[0].equals("*")) {
int min = Integer.parseInt(dataSplit[0]);
return min <= input;
} else {
try {
int min = Integer.parseInt(dataSplit[0]);
int max = Integer.parseInt(dataSplit[1]);
return (min <= input) && (input <= max);
} catch (NumberFormatException ex) {
return false;
}
}
}
//Else, invalid value
return false;
}
private String removeUTF8BOM(String s) {
String UTF8_BOM = "\uFEFF";
if (s.startsWith(UTF8_BOM)) {
s = s.substring(1);
}
return s;
}
/**
* Check if the license is valid
*
* @return true -> VALID, false -> INVALID, null -> UNCHECKED
*/
public static Boolean isValid() {
return valid;
}
}