diff --git a/.github/workflows/javadocs.yml b/.github/workflows/javadocs.yml index 42003a2a..c6ece003 100644 --- a/.github/workflows/javadocs.yml +++ b/.github/workflows/javadocs.yml @@ -35,3 +35,6 @@ jobs: with: # Path of the directory containing the static assets. path: build/docs/javadoc + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v2 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index bf4f8df7..05ca4c63 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,4 +1,4 @@ -name: Deploy Release to Polymart +name: Build, Publish to Updater, and Publish API Package on: push: @@ -9,7 +9,7 @@ on: jobs: build: runs-on: ubuntu-latest - environment: polymart_deploy + environment: updater if: ${{ !github.event.pull_request.head.repo.fork }} steps: - uses: actions/checkout@v2 @@ -32,22 +32,37 @@ jobs: # The desired behavior if no files are found using the provided path. if-no-files-found: error retention-days: 2 - - name: Download changelogs - run: | - curl "https://ajg0702.us/pl/updater/changelogs.php?project=${{ github.repository }}" > changelogs.bb - curl "https://ajg0702.us/pl/updater/changelogs.php?project=${{ github.repository }}&format=html" > changelogs.html - - name: Deploy to Polymart +# - name: Download changelogs +# run: | +# curl "https://ajg0702.us/pl/updater/changelogs.php?project=${{ github.repository }}" > changelogs.bb +# curl "https://ajg0702.us/pl/updater/changelogs.php?project=${{ github.repository }}&format=html" > changelogs.html +# - name: Deploy to Polymart +# env: +# POLYMART_TOKEN: ${{ secrets.POLYMART_TOKEN }} +# MODRINTH_TOKEN: ${{ secrets.MODRINTH_TOKEN }} +# DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }} +# run: | +# export VERSION=`cat build.gradle.kts | grep "version " | awk -F'"' '{print $2}'` +# file build/libs/ajLeaderboards-$VERSION.jar +# curl --no-progress-meter -F "file=@build/libs/ajLeaderboards-$VERSION.jar" -F api_key=$POLYMART_TOKEN -F resource_id="2726" -F version="$VERSION" -F title="v$VERSION" -F message="$(cat changelogs.bb)" "https://api.polymart.org/v1/postUpdate" +# curl --no-progress-meter -A "AJUPDATER/1.0" -H "Authorization: $MODRINTH_TOKEN" -F data="{\"project_id\": \"C9BKEl8Y\", \"version_number\": \"$VERSION\", \"name\": \"v$VERSION\", \"changelog\": \"$(cat changelogs.html)\", \"file_parts\": [\"file\"], \"version_type\": \"release\", \"loaders\": [\"paper\", \"spigot\"], \"featured\": true, \"game_versions\": $(curl https://ajg0702.us/pl/updater/mc-versions.php), \"dependencies\": [], \"primary_file\": \"file\"}" -F "file=@build/libs/ajLeaderboards-$VERSION.jar" "https://api.modrinth.com/v2/version" +# curl -v --no-progress-meter -H "Content-Type: application/json" --request POST -d "{\"content\": \"<@&861713403080999003>\", \"embeds\": [{\"title\": \"${{ github.event.repository.name }} v$VERSION\", \"description\": \"Changelogs\n\n$(curl "https://ajg0702.us/pl/updater/changelogs.php?project=${{ github.repository }}&format=markdown")\n\n[Modrinth](https://modrinth.com/plugin/ajleaderboards/version/$VERSION)\n[Polymart](https://polymart.org/resource/ajleaderboards.2726/updates)\", \"color\": 14845503, \"thumbnail\": {\"url\": \"https://ajg0702.us/pl/icons/${{ github.event.repository.name }}.png\"}}]}" "$DISCORD_WEBHOOK" + - name: Upload to updater (plugin-updates) env: - POLYMART_TOKEN: ${{ secrets.POLYMART_TOKEN }} - MODRINTH_TOKEN: ${{ secrets.MODRINTH_TOKEN }} - DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }} + GH_TOKEN: ${{ secrets.GH_TOKEN }} run: | - export VERSION=`cat build.gradle.kts | grep "version " | awk -F'"' '{print $2}'` - file build/libs/ajLeaderboards-$VERSION.jar - curl --no-progress-meter -F "file=@build/libs/ajLeaderboards-$VERSION.jar" -F api_key=$POLYMART_TOKEN -F resource_id="2726" -F version="$VERSION" -F title="v$VERSION" -F message="$(cat changelogs.bb)" "https://api.polymart.org/v1/postUpdate" - curl --no-progress-meter -A "AJUPDATER/1.0" -H "Authorization: $MODRINTH_TOKEN" -F data="{\"project_id\": \"C9BKEl8Y\", \"version_number\": \"$VERSION\", \"name\": \"v$VERSION\", \"changelog\": \"$(cat changelogs.html)\", \"file_parts\": [\"file\"], \"version_type\": \"release\", \"loaders\": [\"paper\", \"spigot\"], \"featured\": true, \"game_versions\": $(curl https://ajg0702.us/pl/updater/mc-versions.php), \"dependencies\": [], \"primary_file\": \"file\"}" -F "file=@build/libs/ajLeaderboards-$VERSION.jar" "https://api.modrinth.com/v2/version" - curl -v --no-progress-meter -H "Content-Type: application/json" --request POST -d "{\"content\": \"<@&861713403080999003>\", \"embeds\": [{\"title\": \"${{ github.event.repository.name }} v$VERSION\", \"description\": \"Changelogs\n\n$(curl "https://ajg0702.us/pl/updater/changelogs.php?project=${{ github.repository }}&format=markdown")\n\n[Modrinth](https://modrinth.com/plugin/ajleaderboards/version/$VERSION)\n[Polymart](https://polymart.org/resource/ajleaderboards.2726/updates)\", \"color\": 14845503, \"thumbnail\": {\"url\": \"https://ajg0702.us/pl/icons/${{ github.event.repository.name }}.png\"}}]}" "$DISCORD_WEBHOOK" - - name: Upload to repo + VERSION=`cat build.gradle.kts | grep "version " | awk -F'"' '{print $2}'` + cd build/libs/ + echo -n "{ \"message\": \"Plugin Update: $(echo ajLeaderboards-*.jar) (jar)\", \"content\": \"" > file_upload.json + base64 ajLeaderboards-*.jar >> file_upload.json + echo -n "\" }" >> file_upload.json + curl -X PUT -H "Authorization: Bearer $GH_TOKEN" -H "Content-Type: application/json" -d @file_upload.json "https://api.github.com/repos/ajgeiss0702/plugin-updates/contents/jars/free/$(echo ajLeaderboards*.jar)" + + SHA=`curl -H "Authorization: Bearer $GH_TOKEN" -s "https://api.github.com/repos/ajgeiss0702/plugin-updates/contents/plugins/ajLeaderboards.json" | jq -r '.sha'` + NEW_JSON="{ \"latest\": \"$VERSION\", \"premium\": false }" + + curl -X PUT -H "Authorization: Bearer $GH_TOKEN" -H "Content-Type: application/json" -d "{ \"message\": \"Plugin Update: $(echo ajLeaderboards-*.jar) (json)\", \"content\": \"$(echo $NEW_JSON | base64)\", \"sha\": \"$SHA\" }" "https://api.github.com/repos/ajgeiss0702/plugin-updates/contents/plugins/ajLeaderboards.json" + - name: Publish API to repo env: REPO_TOKEN: ${{ secrets.REPO_TOKEN }} uses: gradle/gradle-build-action@937999e9cc2425eddc7fd62d1053baf041147db7 diff --git a/build.gradle.kts b/build.gradle.kts index 0b916164..5e5667b9 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -6,7 +6,7 @@ plugins { } group = "us.ajg0702" -version = "2.8.0" +version = "2.9.0" repositories { mavenCentral() @@ -20,6 +20,9 @@ repositories { maven { url = uri("https://repo.citizensnpcs.co/") } maven { url = uri("https://oss.sonatype.org/content/groups/public/") } maven { url = uri("https://s01.oss.sonatype.org/content/repositories/snapshots/") } + maven { url = uri("https://papermc.io/repo/repository/maven-public/") } + + mavenLocal() } dependencies { @@ -32,18 +35,20 @@ dependencies { compileOnly("org.xerial:sqlite-jdbc:3.32.3.2") compileOnly("org.spongepowered:configurate-yaml:4.0.0") - implementation("org.bstats:bstats-bukkit:1.7") - implementation("net.kyori:adventure-api:4.12.0") implementation("net.kyori:adventure-text-minimessage:4.12.0") - implementation("net.kyori:adventure-platform-bukkit:4.3.0") + implementation("net.kyori:adventure-platform-bukkit:4.3.3") - implementation("us.ajg0702:ajUtils:1.2.12") + implementation("us.ajg0702:ajUtils:1.2.27") implementation("us.ajg0702.commands.platforms.bukkit:bukkit:1.0.0") implementation("us.ajg0702.commands.api:api:1.0.0") + implementation("com.squareup.okhttp3:okhttp:4.11.0") + compileOnly("net.luckperms:api:5.4") + implementation("io.papermc:paperlib:1.0.7") + implementation(project(":nms:nms-legacy")) implementation(project(":nms:nms-19")) @@ -83,6 +88,13 @@ tasks.shadowJar { relocate("org.spongepowered", "us.ajg0702.leaderboards.libs") relocate("org.yaml", "us.ajg0702.leaderboards.libs") relocate("io.leangen", "us.ajg0702.leaderboards.libs") + relocate("io.papermc.lib", "us.ajg0702.leaderboards.libs.paperlib") + relocate("com.squareup", "us.ajg0702.leaderboards.libs") + relocate("okhttp3", "us.ajg0702.leaderboards.libs.okhttp3") + relocate("okio", "us.ajg0702.leaderboards.libs.okio") + relocate("org.intellij", "us.ajg0702.leaderboards.libs.intellij") + relocate("org.jetbrains", "us.ajg0702.leaderboards.libs.jetbrains") + relocate("kotlin", "us.ajg0702.leaderboards.kotlin") archiveBaseName.set("ajLeaderboards") archiveClassifier.set("") diff --git a/nms/nms-19/build.gradle.kts b/nms/nms-19/build.gradle.kts index e438a130..051f0fa8 100644 --- a/nms/nms-19/build.gradle.kts +++ b/nms/nms-19/build.gradle.kts @@ -21,7 +21,7 @@ dependencies { testImplementation("org.junit.jupiter:junit-jupiter-api:5.6.0") testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine") compileOnly(project(":nms:nms-legacy")) - compileOnly("us.ajg0702:ajUtils:1.1.36") + compileOnly("us.ajg0702:ajUtils:1.2.27") compileOnly("net.skinsrestorer:skinsrestorer-api:14.1.10") } diff --git a/nms/nms-19/src/main/java/us/ajg0702/leaderboards/nms/nms19/HeadUtils19.java b/nms/nms-19/src/main/java/us/ajg0702/leaderboards/nms/nms19/HeadUtils19.java index 13007308..b19a290b 100644 --- a/nms/nms-19/src/main/java/us/ajg0702/leaderboards/nms/nms19/HeadUtils19.java +++ b/nms/nms-19/src/main/java/us/ajg0702/leaderboards/nms/nms19/HeadUtils19.java @@ -2,18 +2,39 @@ import org.bukkit.Bukkit; import org.bukkit.Material; +import org.bukkit.OfflinePlayer; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.block.Skull; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.SkullMeta; +import org.bukkit.profile.PlayerProfile; +import us.ajg0702.leaderboards.nms.legacy.DebugWrapper; import us.ajg0702.leaderboards.nms.legacy.VersionedHeadUtils; +import us.ajg0702.utils.foliacompat.CompatScheduler; import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.logging.Level; +import java.util.logging.Logger; public class HeadUtils19 implements VersionedHeadUtils { + private final DebugWrapper debug; + + private final CompatScheduler scheduler; + + private final Logger logger; + + public HeadUtils19(DebugWrapper debug, CompatScheduler scheduler, Logger logger) { + this.debug = debug; + this.scheduler = scheduler; + this.logger = logger; + } + @Override public ItemStack getHeadItem(UUID uuid, String name) { ItemStack stack = new ItemStack(Material.PLAYER_HEAD); @@ -24,7 +45,9 @@ public ItemStack getHeadItem(UUID uuid, String name) { SkullMeta meta = (SkullMeta) itemMeta; - meta.setOwnerProfile(Bukkit.createPlayerProfile(uuid, name)); + PlayerProfile profile = getProfile(uuid, name); + + meta.setOwnerProfile(profile); stack.setItemMeta(meta); @@ -33,14 +56,39 @@ public ItemStack getHeadItem(UUID uuid, String name) { @Override public void setHeadBlock(Block block, UUID uuid, String name) { - BlockState blockState = block.getState(); - if(!(blockState instanceof Skull)) throw new IllegalArgumentException("Block is not a skull!"); + PlayerProfile profile = getProfile(uuid, name); + + scheduler.runSync(block.getLocation(), () -> { + BlockState blockState = block.getState(); + + if(!(blockState instanceof Skull)) throw new IllegalArgumentException("Block is not a skull! " + block); + + Skull skull = (Skull) blockState; + + skull.setOwnerProfile(profile); + skull.update(); + }); + } + + private PlayerProfile getProfile(UUID uuid, String name) { + PlayerProfile profile = Bukkit.getOfflinePlayer(uuid).getPlayerProfile(); - Skull skull = (Skull) blockState; + if(profile.getTextures().isEmpty()) { + debug.infoW("Fetching textures for " + profile + " because they were empty"); + if(Bukkit.isPrimaryThread()) { + Exception stack = new Exception("Texture fetch on the server thread! Contact aj!"); + logger.log(Level.WARNING, "Texture fetch on the server thread! This shouldn't happen!", stack); + } + try { + profile = profile.update().get(5, TimeUnit.SECONDS); + } catch (InterruptedException | ExecutionException | TimeoutException e) { + throw new RuntimeException(e); + } + } - skull.setOwnerProfile(Bukkit.createPlayerProfile(uuid, name)); + debug.infoW("Got profile for " + name + ": " + profile + " with textures" + profile.getTextures()); - skull.update(); + return profile; } } diff --git a/nms/nms-legacy/build.gradle.kts b/nms/nms-legacy/build.gradle.kts index 85ead208..66af1985 100644 --- a/nms/nms-legacy/build.gradle.kts +++ b/nms/nms-legacy/build.gradle.kts @@ -18,8 +18,9 @@ dependencies { compileOnly(group = "org.spigotmc", name = "spigot", version = "1.19-R0.1-SNAPSHOT") testImplementation("org.junit.jupiter:junit-jupiter-api:5.6.0") testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine") - compileOnly("us.ajg0702:ajUtils:1.1.36") + compileOnly("us.ajg0702:ajUtils:1.2.27") compileOnly("net.skinsrestorer:skinsrestorer-api:14.1.10") + compileOnly("com.squareup.okhttp3:okhttp:4.11.0") } publishing { diff --git a/nms/nms-legacy/src/main/java/us/ajg0702/leaderboards/nms/legacy/DebugWrapper.java b/nms/nms-legacy/src/main/java/us/ajg0702/leaderboards/nms/legacy/DebugWrapper.java new file mode 100644 index 00000000..cc2c9cc2 --- /dev/null +++ b/nms/nms-legacy/src/main/java/us/ajg0702/leaderboards/nms/legacy/DebugWrapper.java @@ -0,0 +1,7 @@ +package us.ajg0702.leaderboards.nms.legacy; + +public interface DebugWrapper { + + void infoW(String message); + boolean isDebugW(); +} diff --git a/nms/nms-legacy/src/main/java/us/ajg0702/leaderboards/nms/legacy/HeadUtils.java b/nms/nms-legacy/src/main/java/us/ajg0702/leaderboards/nms/legacy/HeadUtils.java index a6c4595a..e793fb55 100644 --- a/nms/nms-legacy/src/main/java/us/ajg0702/leaderboards/nms/legacy/HeadUtils.java +++ b/nms/nms-legacy/src/main/java/us/ajg0702/leaderboards/nms/legacy/HeadUtils.java @@ -4,22 +4,20 @@ import com.google.gson.JsonObject; import com.mojang.authlib.GameProfile; import com.mojang.authlib.properties.Property; -//import net.skinsrestorer.api.SkinsRestorerAPI; -import org.bukkit.*; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.bukkit.Bukkit; +import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; +import us.ajg0702.utils.foliacompat.CompatScheduler; import us.ajg0702.utils.spigot.VersionSupport; -import java.io.BufferedReader; import java.io.IOException; -import java.io.InputStreamReader; import java.lang.reflect.InvocationTargetException; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.Base64; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; +import java.util.*; import java.util.logging.Logger; public class HeadUtils { @@ -39,9 +37,14 @@ public class HeadUtils { private VersionedHeadUtils versionedHeadUtils = null; private final Logger logger; + private final DebugWrapper debug; - public HeadUtils(Logger logger) { + private final CompatScheduler scheduler; + + public HeadUtils(Logger logger, DebugWrapper debug, CompatScheduler scheduler) { this.logger = logger; + this.debug = debug; + this.scheduler = scheduler; /*if(Bukkit.getPluginManager().isPluginEnabled("SkinsRestorer")) { skinsRestorerAPI = SkinsRestorerAPI.getApi(); @@ -49,11 +52,16 @@ public HeadUtils(Logger logger) { skinsRestorerAPI = null; }*/ - if(VersionSupport.getMinorVersion() >= 19) { + int minorVersion = VersionSupport.getMinorVersion(); + + debug.infoW("Detected minor minecraft version: " + minorVersion); + + if(minorVersion >= 19) { try { versionedHeadUtils = (VersionedHeadUtils) Class.forName("us.ajg0702.leaderboards.nms.nms19.HeadUtils19") - .getDeclaredConstructor() - .newInstance(); + .getDeclaredConstructor(DebugWrapper.class, CompatScheduler.class, Logger.class) + .newInstance(debug, scheduler, logger); + debug.infoW("Using versioned head utils for >19 (" + minorVersion + ")"); } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException | ClassNotFoundException e) { logger.warning("Unable to find 1.19 nms class: "+e.getMessage()); @@ -76,7 +84,11 @@ public ItemStack getHeadItem(UUID uuid, String name) { } String value; //if(skinsRestorerAPI == null) { - value = getHeadValue(Bukkit.getOfflinePlayer(uuid).getName()); + if(uuid != null && Bukkit.getOnlineMode()) { + value = getHeadValue(uuid); + } else { + value = getHeadValue(name); + } /*} else { IProperty profile = skinsRestorerAPI.getProfile(uuid.toString()); if(profile == null) { @@ -98,34 +110,35 @@ public ItemStack getHeadItem(UUID uuid, String name) { Map> skinCache = new HashMap<>(); final long lastClear = System.currentTimeMillis(); - public String getHeadValue(String name) { - if(System.currentTimeMillis() - lastClear > 5400e3) { // completly wipe the cache every hour and a half + public String getHeadValue(String nameOrUUID) { + + if(System.currentTimeMillis() - lastClear > 5400e3) { // completely wipe the cache every hour and a half skinCache = new HashMap<>(); } - if(skinCache.containsKey(name) && skinCache.get(name).getTimeSince() < 300e3) { - return skinCache.get(name).getData(); + if(skinCache.containsKey(nameOrUUID) && skinCache.get(nameOrUUID).getTimeSince() < 300e3) { + return skinCache.get(nameOrUUID).getData(); } - String result = getURLContent("https://api.mojang.com/users/profiles/minecraft/" + name); - + String profile = getURLContent("https://api.ashcon.app/mojang/v2/user/" + nameOrUUID); + if(profile.isEmpty()) return ""; Gson g = new Gson(); - JsonObject jObj = g.fromJson(result, JsonObject.class); - if(jObj == null || jObj.get("id") == null) return ""; - String uuid = jObj.get("id").toString().replace("\"",""); - String signature = getURLContent("https://sessionserver.mojang.com/session/minecraft/profile/" + uuid); - jObj = g.fromJson(signature, JsonObject.class); - if(jObj == null || jObj.get("id") == null) return ""; - String value = jObj.getAsJsonArray("properties").get(0).getAsJsonObject().get("value").getAsString(); - String decoded = new String(Base64.getDecoder().decode(value)); - jObj = g.fromJson(decoded, JsonObject.class); - String skin = jObj.getAsJsonObject("textures").getAsJsonObject("SKIN").get("url").getAsString(); - byte[] skinByte = ("{\"textures\":{\"SKIN\":{\"url\":\"" + skin + "\"}}}").getBytes(); + JsonObject jObj = g.fromJson(profile, JsonObject.class); + if(jObj == null || jObj.get("textures") == null) return ""; + String url = jObj.getAsJsonObject("textures").getAsJsonObject("skin").get("url").getAsString(); +// String decoded = new String(Base64.getDecoder().decode(value)); +// jObj = g.fromJson(decoded, JsonObject.class); +// String skin = jObj.getAsJsonObject("textures").getAsJsonObject("SKIN").get("url").getAsString(); + byte[] skinByte = ("{\"textures\":{\"SKIN\":{\"url\":\"" + url + "\"}}}").getBytes(); String finalSkin = new String(Base64.getEncoder().encode(skinByte)); - skinCache.put(name, new CachedData<>(finalSkin)); + skinCache.put(nameOrUUID, new CachedData<>(finalSkin)); return finalSkin; } + public String getHeadValue(UUID uuid) { + return getHeadValue(uuid.toString()); + } + public static GameProfile getNonPlayerProfile(String skinURL) { GameProfile newSkinProfile = new GameProfile(UUID.randomUUID(), null); @@ -140,8 +153,14 @@ public static GameProfile getNonPlayerProfile(String skinURL) { } + private final OkHttpClient httpClient = new OkHttpClient.Builder() + .cache(null) + .build(); + final HashMap urlCache = new HashMap<>(); final HashMap urlLastget = new HashMap<>(); + final HashMap lastFail = new HashMap<>(); + private final Random random = new Random(); private String getURLContent(String urlStr) { if( urlLastget.containsKey(urlStr) && @@ -149,28 +168,41 @@ private String getURLContent(String urlStr) { ) { return urlCache.get(urlStr); } - URL url; - BufferedReader in = null; - StringBuilder sb = new StringBuilder(); - try{ - url = new URL(urlStr); - in = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8) ); - String str; - while((str = in.readLine()) != null) { - sb.append( str ); - } - } catch (Exception ignored) { } - finally{ - try{ - if(in!=null) { - in.close(); - } - }catch(IOException ignored) { } + + if(lastFail.containsKey(urlStr) && System.currentTimeMillis() - lastFail.get(urlStr) < 30e3) { + // dont retry too often + return ""; } - String r = sb.toString(); - urlCache.put(urlStr, r); - urlLastget.put(urlStr, System.currentTimeMillis()); - return r; + Request request = new Request.Builder() + .get() + .url(urlStr) + .header("user-agent", "ajLeaderboards/0") + .build(); + + + + try(Response response = httpClient.newCall(request).execute()) { + ResponseBody body = response.body(); + if(!response.isSuccessful() || body == null) { + /*if(body != null) { + logger.info("Unsuccessful (" + response.code() + ") with: " + body.string()); + } else { + logger.info("Null body with " + response.code()); + }*/ +// System.out.println("Unsuccessful for " + urlStr + ": " + response.code()); + + lastFail.put(urlStr, System.currentTimeMillis() + (random.nextInt(4_000)-2_000)); + return urlCache.getOrDefault(urlStr, ""); + } + String r = body.string(); + urlCache.put(urlStr, r); + urlLastget.put(urlStr, System.currentTimeMillis()); +// System.out.println("Succeeded for " + urlStr); + lastFail.remove(urlStr); + return r; + } catch (IOException e) { + throw new RuntimeException("Error while fetching " + urlStr + ":", e); + } } } diff --git a/src/main/java/us/ajg0702/leaderboards/Debug.java b/src/main/java/us/ajg0702/leaderboards/Debug.java index b7826a8a..f5f7cd87 100644 --- a/src/main/java/us/ajg0702/leaderboards/Debug.java +++ b/src/main/java/us/ajg0702/leaderboards/Debug.java @@ -1,10 +1,10 @@ package us.ajg0702.leaderboards; -import us.ajg0702.leaderboards.cache.Cache; +import us.ajg0702.leaderboards.nms.legacy.DebugWrapper; import java.util.logging.Logger; -public class Debug { +public class Debug implements DebugWrapper { private static boolean debug = false; private static Logger logger; @@ -22,6 +22,16 @@ public static void info(String message) { if(!debug) return; logger.info("[DEBUG] "+message); } + public void infoW(String message) { + Debug.info(message); + } + + public static boolean isDebug() { + return debug; + } + public boolean isDebugW() { + return debug; + } private static boolean particles = false; diff --git a/src/main/java/us/ajg0702/leaderboards/LeaderboardPlugin.java b/src/main/java/us/ajg0702/leaderboards/LeaderboardPlugin.java index d6307c3b..9681b889 100644 --- a/src/main/java/us/ajg0702/leaderboards/LeaderboardPlugin.java +++ b/src/main/java/us/ajg0702/leaderboards/LeaderboardPlugin.java @@ -8,8 +8,9 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.minimessage.MiniMessage; import net.milkbowl.vault.chat.Chat; -import org.bstats.bukkit.Metrics; import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; @@ -36,12 +37,13 @@ import us.ajg0702.leaderboards.loaders.MessageLoader; import us.ajg0702.leaderboards.nms.legacy.HeadUtils; import us.ajg0702.leaderboards.placeholders.PlaceholderExpansion; -import us.ajg0702.leaderboards.utils.Exporter; -import us.ajg0702.leaderboards.utils.OfflineUpdater; -import us.ajg0702.leaderboards.utils.ResetSaver; -import us.ajg0702.leaderboards.utils.SlimJarLogger; +import us.ajg0702.leaderboards.utils.*; import us.ajg0702.utils.common.Config; import us.ajg0702.utils.common.Messages; +import us.ajg0702.utils.common.UpdateManager; +import us.ajg0702.utils.common.UtilsLogger; +import us.ajg0702.utils.foliacompat.CompatScheduler; +import us.ajg0702.utils.foliacompat.Task; import java.io.File; import java.io.IOException; @@ -82,6 +84,10 @@ public class LeaderboardPlugin extends JavaPlugin { private boolean shuttingDown = false; + private UpdateManager updateManager = null; + + private final CompatScheduler compatScheduler = new CompatScheduler(this); + @Override public void onLoad() { try { @@ -150,7 +156,7 @@ public void onEnable() { TimeUtils.setStrings(messages); - Bukkit.getScheduler().runTaskAsynchronously(this, () -> { + getScheduler().runTaskAsynchronously(() -> { if(Bukkit.getPluginManager().isPluginEnabled("Vault")) { RegisteredServiceProvider rsp = getServer().getServicesManager().getRegistration(Chat.class); if(rsp == null) { @@ -165,7 +171,7 @@ public void onEnable() { signManager = new SignManager(this); headManager = new HeadManager(this); - headUtils = new HeadUtils(getLogger()); + headUtils = new HeadUtils(getLogger(), new Debug(), compatScheduler); armorStandManager = new ArmorStandManager(this); resetSaver = new ResetSaver(this); @@ -183,9 +189,8 @@ public void onEnable() { reloadInterval(); - Bukkit.getScheduler().runTaskTimerAsynchronously(this, this::scheduleResets, 0, 15 * 60 * 20); - Bukkit.getScheduler().runTaskTimerAsynchronously( - this, + getScheduler().runTaskTimerAsynchronously(this::scheduleResets, 0, 15 * 60 * 20); + getScheduler().runTaskTimerAsynchronously( () -> offlineUpdaters.forEach((b, u) -> u.progressLog()), 5 * 20, 30 * 20 @@ -206,6 +211,10 @@ public void onEnable() { Bukkit.getPluginManager().registerEvents(new Listeners(this), this); + if(config.getBoolean("enable-updater")) { + updateManager = new UpdateManager(utilsLogger, getDescription().getVersion(), "ajLeaderboards", "ajLeaderboards", null, getDataFolder().getParentFile(), "ajLeaderboards update"); + } + getLogger().info("ajLeaderboards v"+getDescription().getVersion()+" by ajgeiss0702 enabled!"); } @@ -218,9 +227,10 @@ private Iterable getSignPath(String end) { @Override public void onDisable() { + boolean fastShutdown = getAConfig().getBoolean("fast-shutdown"); shuttingDown = true; if(getContextLoader() != null) getContextLoader().checkReload(false); - Bukkit.getScheduler().cancelTasks(this); + getScheduler().cancelTasks(); if(getTopManager() != null) getTopManager().shutdown(); if(getCache() != null) { @@ -239,15 +249,20 @@ public void onDisable() { }catch(InterruptedException ignored){} } - getLogger().info("Killing remaining workers"); - killWorkers(1000); - Debug.info("1st kill pass done, retrying for remaining"); - killWorkers(5000); - getLogger().info("Remaining workers killed"); + if(!fastShutdown) { + getLogger().info("Killing remaining workers"); + killWorkers(1000); + Debug.info("1st kill pass done, retrying for remaining"); + killWorkers(5000); + getLogger().info("Remaining workers killed"); + } else { + killWorkers(100); + getLogger().warning("Fast shutdown is enabled! If you see warnings/errors to nag me about shutting down async tasks, you should be able to ignore them. Disable fast-shutdown if you don't want to see those warnings/errors or this message."); + } getLogger().info("ajLeaderboards v"+getDescription().getVersion()+" disabled."); - Bukkit.getScheduler().getActiveWorkers().forEach(bukkitWorker -> { + getScheduler().getActiveWorkers().forEach(bukkitWorker -> { Debug.info("Active worker: "+bukkitWorker.getOwner().getDescription().getName()+" "+bukkitWorker.getTaskId()); for (StackTraceElement stackTraceElement : bukkitWorker.getThread().getStackTrace()) { Debug.info(" - "+stackTraceElement); @@ -256,7 +271,7 @@ public void onDisable() { } private void killWorkers(int waitForDeath) { - List workers = new ArrayList<>(Bukkit.getScheduler().getActiveWorkers()); + List workers = new ArrayList<>(getScheduler().getActiveWorkers()); List killedWorkers = new ArrayList<>(); workers.forEach(bukkitWorker -> { if(!bukkitWorker.getOwner().equals(this)) return; @@ -341,15 +356,23 @@ public ResetSaver getResetSaver() { return resetSaver; } - int updateTaskId = -1; + public CompatScheduler getCompatScheduler() { + return compatScheduler; + } + + public CompatScheduler getScheduler() { + return getCompatScheduler(); + } + + Task updateTask; public void reloadInterval() { - if(updateTaskId != -1) { + if(updateTask != null) { try { - Bukkit.getScheduler().cancelTask(updateTaskId); + updateTask.cancel(); } catch(IllegalArgumentException ignored) {} - updateTaskId = -1; + updateTask = null; } - updateTaskId = Bukkit.getScheduler().runTaskTimerAsynchronously(this, () -> { + updateTask = getScheduler().runTaskTimerAsynchronously(() -> { if(!config.getBoolean("update-stats")) return; if(getTopManager().getFetchingAverage() > 100) { getLogger().warning("Database is overloaded! Skipping update of players."); @@ -359,21 +382,20 @@ public void reloadInterval() { if(isShuttingDown()) return; getTopManager().submit(() -> getCache().updatePlayerStats(p)); } - }, 10*20, config.getInt("stat-refresh")).getTaskId(); - Debug.info("Update task id is "+updateTaskId); + }, 10*20, config.getInt("stat-refresh")); } - final HashMap resetIds = new HashMap<>(); + final HashMap resetTasks = new HashMap<>(); public void scheduleResets() { - resetIds.values().forEach(Bukkit.getScheduler()::cancelTask); - resetIds.clear(); + resetTasks.values().forEach(Task::cancel); + resetTasks.clear(); for(TimedType type : TimedType.values()) { try { scheduleReset(type); } catch (ExecutionException | InterruptedException e) { if(isShuttingDown()) return; - getLogger().log(Level.WARNING, "Scheduling reset interupted:", e); + getLogger().log(Level.WARNING, "Scheduling reset interrupted:", e); } } } @@ -400,7 +422,7 @@ public void scheduleReset(TimedType type) throws ExecutionException, Interrupted } if(resetNow.size() > 0) { - Bukkit.getScheduler().runTaskAsynchronously(this, () -> { + getScheduler().runTaskAsynchronously(() -> { try { for (String board : resetNow) { cache.reset(board, type); @@ -424,8 +446,7 @@ public void scheduleReset(TimedType type) throws ExecutionException, Interrupted Debug.info(TimeUtils.formatTimeSeconds(secsTilNextReset)+" until the reset for "+type.lowerName()+" (next formatted: "+type.getNextReset().atOffset(ZoneOffset.UTC).format(DateTimeFormatter.RFC_1123_DATE_TIME)+" next: "+nextReset+")"); if(isShuttingDown()) return; - int taskId = Bukkit.getScheduler().runTaskLaterAsynchronously( - this, + Task task = getScheduler().runTaskLaterAsynchronously( () -> { try { for (String board : getTopManager().getBoards()) { @@ -437,8 +458,8 @@ public void scheduleReset(TimedType type) throws ExecutionException, Interrupted } }, secsTilNextReset*20L - ).getTaskId(); - resetIds.put(type, taskId); + ); + resetTasks.put(type, task); } public boolean validatePlaceholder(String placeholder, CommandSender sayOutput) { @@ -468,6 +489,10 @@ public static MiniMessage getMiniMessage() { return miniMessage; } + public UpdateManager getUpdateManager() { + return updateManager; + } + private static BukkitAudiences adventure; public BukkitAudiences getAdventure() { @@ -525,4 +550,44 @@ public void timePlaceholderUsed() { } doublePrevention = false; } + + public Future safeGetBlockType(Location location) { + CompletableFuture future = new CompletableFuture<>(); + Runnable runnable = () -> { + future.complete(location.getBlock().getType()); + }; + if(CompatScheduler.isFolia()) { + getScheduler().runSync(location, runnable); + } else { + runnable.run(); + } + return future; + } + + private UtilsLogger utilsLogger = new UtilsLogger() { + @Override + public void warn(String s) { + getLogger().warning(s); + } + + @Override + public void warning(String s) { + getLogger().warning(s); + } + + @Override + public void info(String s) { + getLogger().info(s); + } + + @Override + public void error(String s) { + getLogger().severe(s); + } + + @Override + public void severe(String s) { + getLogger().severe(s); + } + }; } diff --git a/src/main/java/us/ajg0702/leaderboards/Listeners.java b/src/main/java/us/ajg0702/leaderboards/Listeners.java index ab3384cb..47605c29 100644 --- a/src/main/java/us/ajg0702/leaderboards/Listeners.java +++ b/src/main/java/us/ajg0702/leaderboards/Listeners.java @@ -2,6 +2,7 @@ import org.bukkit.Bukkit; import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; @@ -20,7 +21,7 @@ public Listeners(LeaderboardPlugin plugin) { @EventHandler public void onJoin(PlayerJoinEvent e) { if(plugin.getCache().getMethod().getName().equals("sqlite") && e.getPlayer().hasPermission("ajleaderboards.use")) { - Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { + plugin.getScheduler().runTaskLaterAsynchronously(() -> { plugin.getAdventure().player(e.getPlayer()) .sendMessage(message( "\n&6[ajLeaderboards] &cSQLite is not recommended and will be removed! &7Please switch to h2 for a faster (and more stable) cache storage.\n" + @@ -36,13 +37,16 @@ public void onJoin(PlayerJoinEvent e) { } if(!plugin.getAConfig().getBoolean("update-stats")) return; if(!plugin.getAConfig().getBoolean("update-on-join")) return; - Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> plugin.getCache().updatePlayerStats(e.getPlayer())); + plugin.getScheduler().runTaskAsynchronously(() -> plugin.getCache().updatePlayerStats(e.getPlayer())); } @EventHandler public void onQuit(PlayerQuitEvent e) { plugin.getCache().cleanPlayer(e.getPlayer()); + } + @EventHandler(priority = EventPriority.LOWEST) // Lowest is run first + public void onQuitFirst(PlayerQuitEvent e) { if(!plugin.getAConfig().getBoolean("update-stats")) return; if(!plugin.getAConfig().getBoolean("update-on-leave")) return; plugin.getCache().updatePlayerStats(e.getPlayer()); diff --git a/src/main/java/us/ajg0702/leaderboards/api/events/PreTimedTypeResetEvent.java b/src/main/java/us/ajg0702/leaderboards/api/events/PreTimedTypeResetEvent.java new file mode 100644 index 00000000..7d1668c3 --- /dev/null +++ b/src/main/java/us/ajg0702/leaderboards/api/events/PreTimedTypeResetEvent.java @@ -0,0 +1,37 @@ +package us.ajg0702.leaderboards.api.events; + +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.jetbrains.annotations.NotNull; +import us.ajg0702.leaderboards.boards.TimedType; + +public class PreTimedTypeResetEvent extends Event { + + private final String board; + private final TimedType type; + + + public PreTimedTypeResetEvent(String board, TimedType type) { + super(true); + this.board = board; + this.type = type; + } + + public String getBoard() { + return board; + } + + public TimedType getType() { + return type; + } + + private static final HandlerList HANDLERS = new HandlerList(); + + public @NotNull HandlerList getHandlers() { + return HANDLERS; + } + + public static HandlerList getHandlerList() { + return HANDLERS; + } +} diff --git a/src/main/java/us/ajg0702/leaderboards/boards/StatEntry.java b/src/main/java/us/ajg0702/leaderboards/boards/StatEntry.java index 434d3b01..7fe21d07 100644 --- a/src/main/java/us/ajg0702/leaderboards/boards/StatEntry.java +++ b/src/main/java/us/ajg0702/leaderboards/boards/StatEntry.java @@ -3,6 +3,7 @@ import com.google.gson.JsonObject; import org.bukkit.OfflinePlayer; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import us.ajg0702.leaderboards.LeaderboardPlugin; import us.ajg0702.leaderboards.TimeUtils; import us.ajg0702.leaderboards.boards.keys.BoardType; @@ -22,7 +23,8 @@ public class StatEntry { public static final String AN_ERROR_OCCURRED = "An error occurred"; private static LeaderboardPlugin plugin; - + + @Nullable final String playerName; final String playerDisplayName; String prefix; @@ -54,7 +56,7 @@ public class StatEntry { double score; String scorePretty; - public StatEntry(int position, String board, String prefix, String playerName, String playerDisplayName, UUID playerID, String suffix, double score, TimedType type) { + public StatEntry(int position, String board, String prefix, @Nullable String playerName, String playerDisplayName, UUID playerID, String suffix, double score, TimedType type) { if(prefix == null) throw new IllegalArgumentException("Prefix cannot be null"); if(suffix == null) throw new IllegalArgumentException("Suffix cannot be null"); this.playerName = playerName == null ? "" : playerName; @@ -93,10 +95,10 @@ public StatEntry(int position, String board, String prefix, String playerName, S scorePretty = calcPrettyScore(); } private String calcPrettyScore() { - if(score == 0 && playerName.equals(BOARD_DOES_NOT_EXIST)) { + if(score == 0 && BOARD_DOES_NOT_EXIST.equals(playerName)) { return "BDNE"; } - if(score == 0 && playerName.equals(plugin.getMessages().getRawString("loading.text"))) { + if(score == 0 && plugin.getMessages().getRawString("loading.text").equals(playerName)) { return "..."; } Messages messages = cache.getPlugin().getMessages(); @@ -134,7 +136,7 @@ public String getSuffix() { } public String getPlayerName() { - return playerName; + return playerName == null ? "N/A" : playerName; } public String getSkin() { @@ -171,7 +173,7 @@ public double getScore() { } public String getScoreFormatted() { - if(score == 0 && playerName.equals(BOARD_DOES_NOT_EXIST)) { + if(score == 0 && BOARD_DOES_NOT_EXIST.equals(playerName)) { return "BDNE"; } if(!hasPlayer()) { @@ -262,7 +264,7 @@ public String getScorePretty() { } public String getTime() { - if(score == 0 && playerName.equals(BOARD_DOES_NOT_EXIST)) { + if(score == 0 && BOARD_DOES_NOT_EXIST.equals(playerName)) { return "BDNE"; } if(!hasPlayer()) { diff --git a/src/main/java/us/ajg0702/leaderboards/boards/TopManager.java b/src/main/java/us/ajg0702/leaderboards/boards/TopManager.java index e336ced8..e86ba4f7 100644 --- a/src/main/java/us/ajg0702/leaderboards/boards/TopManager.java +++ b/src/main/java/us/ajg0702/leaderboards/boards/TopManager.java @@ -51,7 +51,7 @@ public TopManager(LeaderboardPlugin pl, List initialBoards) { ThreadFactoryProxy.getDefaultThreadFactory("AJLBFETCH") ); fetchService.allowCoreThreadTimeOut(true); - Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, () -> { + plugin.getScheduler().runTaskTimerAsynchronously(() -> { rolling.add(getQueuedTasks()+getActiveFetchers()); if(rolling.size() > 50) { rolling.remove(0); @@ -158,7 +158,8 @@ private void cacheStatPosition(int position, BoardType boardType, UUID playerUUI @Override public @NotNull ListenableFuture reload(@NotNull PlayerBoardType key, @NotNull StatEntry oldValue) { - if(plugin.isShuttingDown() || System.currentTimeMillis() - statEntryLastRefresh.getOrDefault(key, 0L) < Math.max(cacheTime()*1.5, 5000)) { + long msSinceRefresh = System.currentTimeMillis() - statEntryLastRefresh.getOrDefault(key, 0L); + if(plugin.isShuttingDown() || msSinceRefresh < Math.max(cacheTime()*1.5, plugin.getAConfig().getInt("min-player-cache-time"))) { return Futures.immediateFuture(oldValue); } ListenableFutureTask task = ListenableFutureTask.create(() -> { @@ -270,6 +271,59 @@ public int getBoardSize(String board) { } + Map totalLastRefresh = new HashMap<>(); + LoadingCache totalCache = CacheBuilder.newBuilder() + .expireAfterAccess(24, TimeUnit.HOURS) + .refreshAfterWrite(1, TimeUnit.SECONDS) + .maximumSize(10000) + .removalListener(notification -> { + if(!notification.getCause().equals(RemovalCause.REPLACED)) totalLastRefresh.remove((BoardType) notification.getKey()); + }) + .build(new CacheLoader() { + @Override + public @NotNull Double load(@NotNull BoardType key) { + return plugin.getCache().getTotal(key.getBoard(), key.getType()); + } + + @Override + public @NotNull ListenableFuture reload(@NotNull BoardType key, @NotNull Double oldValue) { + if(plugin.isShuttingDown() || System.currentTimeMillis() - totalLastRefresh.getOrDefault(key, 0L) < Math.max(cacheTime()*2, 5000)) { + return Futures.immediateFuture(oldValue); + } + ListenableFutureTask task = ListenableFutureTask.create(() -> { + totalLastRefresh.put(key, System.currentTimeMillis()); + return plugin.getCache().getTotal(key.getBoard(), key.getType()); + }); + if(plugin.isShuttingDown()) return Futures.immediateFuture(oldValue); + fetchService.execute(task); + return task; + } + }); + + + /** + * Gets the sum of all players on the leaderboard + * @param board the board + * @param type the timed type + * @return the sum of all players in the specified board for the specified timed type + */ + public double getTotal(String board, TimedType type) { + BoardType boardType = new BoardType(board, type); + Double cached = totalCache.getIfPresent(boardType); + + if(cached == null) { + if(BlockingFetch.shouldBlock(plugin)) { + cached = totalCache.getUnchecked(boardType); + } else { + fetchService.submit(() -> totalCache.getUnchecked(boardType)); + return -2; + } + } + + return cached; + + } + List boardCache; long lastGetBoard = 0; @@ -416,8 +470,10 @@ private void checkWrong() { public int cacheTime() { boolean recentLargeAverage = System.currentTimeMillis() - lastLargeAverage < 30000; + boolean moreFetching = plugin.getAConfig().getBoolean("more-fetching"); - int r = recentLargeAverage ? 5000 : 1000; + + int r = moreFetching ? (recentLargeAverage ? 5000 : 1000) : 20000; int fetchingAverage = getFetchingAverage(); @@ -428,23 +484,25 @@ public int cacheTime() { int activeFetchers = getActiveFetchers(); int totalTasks = activeFetchers + getQueuedTasks(); - if(!recentLargeAverage) { - if(fetchingAverage == 0 && activeFetchers == 0) { - return 500; + if(moreFetching) { + if(!recentLargeAverage) { + if(fetchingAverage == 0 && activeFetchers == 0) { + return 500; + } + if(fetchingAverage > 0) { + r = 2000; + } + if(fetchingAverage >= 2) { + r = 5000; + } } - if(fetchingAverage > 0) { - r = 2000; + if((fetchingAverage >= 5 || totalTasks > 25) && activeFetchers > 0) { + r = 10000; } - if(fetchingAverage >= 2) { - r = 5000; + if((fetchingAverage > 10 || totalTasks > 59) && activeFetchers > 0) { + r = 15000; } } - if((fetchingAverage >= 5 || totalTasks > 25) && activeFetchers > 0) { - r = 10000; - } - if((fetchingAverage > 10 || totalTasks > 59) && activeFetchers > 0) { - r = 15000; - } if((fetchingAverage > 20 || totalTasks > 75) && activeFetchers > 0) { r = 30000; } diff --git a/src/main/java/us/ajg0702/leaderboards/cache/Cache.java b/src/main/java/us/ajg0702/leaderboards/cache/Cache.java index 747fa91d..c2afb7fd 100644 --- a/src/main/java/us/ajg0702/leaderboards/cache/Cache.java +++ b/src/main/java/us/ajg0702/leaderboards/cache/Cache.java @@ -8,6 +8,7 @@ import org.spongepowered.configurate.ConfigurateException; import us.ajg0702.leaderboards.Debug; import us.ajg0702.leaderboards.LeaderboardPlugin; +import us.ajg0702.leaderboards.api.events.PreTimedTypeResetEvent; import us.ajg0702.leaderboards.api.events.UpdatePlayerEvent; import us.ajg0702.leaderboards.boards.StatEntry; import us.ajg0702.leaderboards.boards.TimedType; @@ -37,8 +38,8 @@ public class Cache { private final String GET_POSITION = "/*%s*/with N as (select *,ROW_NUMBER() OVER (order by '%s' %s, namecache desc) as position from '%s') select 'id','value','namecache','prefixcache','suffixcache','displaynamecache',position,"+deltaBuilder()+" from N where 'id'=?"; private final Map CREATE_TABLE = ImmutableMap.of( "sqlite", "create table if not exists '%s' (id TEXT PRIMARY KEY, value DECIMAL(65, 2)"+columnBuilder("DECIMAL(65, 2)")+", namecache TEXT, prefixcache TEXT, suffixcache TEXT, displaynamecache TEXT)", - "h2", "create table if not exists '%s' ('id' VARCHAR(36) PRIMARY KEY, 'value' DECIMAL(65, 2)"+columnBuilder("DECIMAL(65, 2)")+", 'namecache' VARCHAR(16), 'prefixcache' VARCHAR(255), 'suffixcache' VARCHAR(255), 'displaynamecache' VARCHAR(512))", - "mysql", "create table if not exists '%s' ('id' VARCHAR(36) PRIMARY KEY, 'value' DECIMAL(65, 2)"+columnBuilder("DECIMAL(65, 2)")+", 'namecache' VARCHAR(16), 'prefixcache' TINYTEXT, 'suffixcache' TINYTEXT, 'displaynamecache' VARCHAR(512))" + "h2", "create table if not exists '%s' ('id' VARCHAR(36) PRIMARY KEY, 'value' DECIMAL(65, 2)"+columnBuilder("DECIMAL(65, 2)")+", 'namecache' VARCHAR(16), 'prefixcache' VARCHAR(1024), 'suffixcache' VARCHAR(1024), 'displaynamecache' VARCHAR(2048))", + "mysql", "create table if not exists '%s' ('id' VARCHAR(36) PRIMARY KEY, 'value' DECIMAL(65, 2)"+columnBuilder("DECIMAL(65, 2)")+", 'namecache' VARCHAR(16), 'prefixcache' VARCHAR(1024), 'suffixcache' VARCHAR(1024), 'displaynamecache' VARCHAR(2048))" ); private final String REMOVE_PLAYER = "delete from '%s' where 'namecache'=?"; private final Map LIST_TABLES = ImmutableMap.of( @@ -102,7 +103,7 @@ public Cache(LeaderboardPlugin plugin) { } /** - * Get a stat. It is reccomended you use TopManager#getStat instead of this, + * Get a stat. It is recommended you use TopManager#getStat instead of this, * unless it is of absolute importance that you have the most up-to-date information * @param position The position to get * @param board The board @@ -277,6 +278,58 @@ public int getBoardSize(String board) { return size; } + public double getTotal(String board, TimedType type) { + if(!plugin.getTopManager().boardExists(board)) { + if(!nonExistantBoards.contains(board)) { + nonExistantBoards.add(board); + } + return -3; + } + + Connection connection = null; + ResultSet rs = null; + + int size; + + try { + connection = method.getConnection(); + + PreparedStatement ps = connection.prepareStatement(String.format( + method.formatStatement("select SUM(%s) as total from '%s'"), + type == TimedType.ALLTIME ? "\"value\"" : type.lowerName() + "_delta", + tablePrefix+board + )); + + rs = ps.executeQuery(); + + rs.next(); + + size = rs.getInt(1); + + } catch (SQLException e) { + if( + !e.getMessage().contains("ResultSet closed") && + !e.getMessage().contains("empty result set") && + !e.getMessage().contains("[2000-") + ) { + plugin.getLogger().log(Level.WARNING, "Unable to get total of board:", e); + return -1; + } else { + return 0; + } + } finally { + try { + if(connection != null) method.close(connection); + if(rs != null) rs.close(); + } catch (SQLException e) { + plugin.getLogger().log(Level.WARNING, "Error while closing resources from board size fetch:", e); + } + + } + + return size; + } + public boolean createBoard(String name) { try { Connection conn = method.getConnection(); @@ -735,13 +788,16 @@ public void reset(String board, TimedType type) throws ExecutionException, Inter List updatableBoards = plugin.getAConfig().getStringList("only-update"); if(!updatableBoards.isEmpty() && !updatableBoards.contains(board)) return; + if(type.equals(TimedType.ALLTIME)) { + throw new IllegalArgumentException("Cannot reset ALLTIME!"); + } + + Bukkit.getPluginManager().callEvent(new PreTimedTypeResetEvent(board, type)); + long startTime = System.currentTimeMillis(); LocalDateTime startDateTime = LocalDateTime.now(); long newTime = startDateTime.atOffset(ZoneOffset.UTC).toEpochSecond()*1000; Debug.info(board+" "+type+" "+startDateTime.atOffset(ZoneOffset.UTC).format(DateTimeFormatter.RFC_1123_DATE_TIME)+" "+newTime); - if(type.equals(TimedType.ALLTIME)) { - throw new IllegalArgumentException("Cannot reset ALLTIME!"); - } List saveableTypes = plugin.getAConfig().getStringList("reset-save-types"); @@ -981,7 +1037,7 @@ private StatEntry processData(ResultSet r, String sortBy, int position, String b r.close(); if(prefix == null) prefix = ""; - if(suffix == null) prefix = ""; + if(suffix == null) suffix = ""; if(displayName == null) displayName = name; if(uuidRaw == null) { diff --git a/src/main/java/us/ajg0702/leaderboards/commands/main/MainCommand.java b/src/main/java/us/ajg0702/leaderboards/commands/main/MainCommand.java index ee460fcd..f75e4a38 100644 --- a/src/main/java/us/ajg0702/leaderboards/commands/main/MainCommand.java +++ b/src/main/java/us/ajg0702/leaderboards/commands/main/MainCommand.java @@ -13,7 +13,6 @@ import java.util.Arrays; import java.util.Collections; -import java.util.List; import static us.ajg0702.leaderboards.LeaderboardPlugin.message; @@ -29,13 +28,14 @@ public MainCommand(LeaderboardPlugin plugin) { addSubCommand(new UpdatePlayer(plugin)); addSubCommand(new RemovePlayer(plugin)); addSubCommand(new Remove(plugin)); - addSubCommand(new ListBoards(plugin)); + addSubCommand(new ListCommand(plugin)); addSubCommand(new Signs(plugin)); addSubCommand(new Export(plugin)); addSubCommand(new Import(plugin)); addSubCommand(new Viewer(plugin)); addSubCommand(new Reset(plugin)); addSubCommand(new UpdateAllOffline(plugin)); + addSubCommand(new Update(plugin)); // Debug commands addSubCommand(new Time()); @@ -45,7 +45,7 @@ public MainCommand(LeaderboardPlugin plugin) { } @Override - public List autoComplete(CommandSender sender, String[] args) { + public java.util.List autoComplete(CommandSender sender, String[] args) { if(!checkPermission(sender)) { return Collections.emptyList(); } @@ -66,7 +66,7 @@ public void execute(CommandSender sender, String[] args, String label) { sendHelp(sender, label, getSubCommands()); } - public static void sendHelp(CommandSender sender, String label, List subCommands) { + public static void sendHelp(CommandSender sender, String label, java.util.List subCommands) { sender.sendMessage(message("")); for(SubCommand subCommand : subCommands) { if(!subCommand.showInTabComplete()) continue; diff --git a/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/Add.java b/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/Add.java index 8ac97676..57eee065 100644 --- a/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/Add.java +++ b/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/Add.java @@ -27,7 +27,7 @@ public List autoComplete(CommandSender commandSender, String[] args) { @Override public void execute(CommandSender sender, String[] args, String label) { - Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + plugin.getScheduler().runTaskAsynchronously(() -> { if(args.length < 1) { sender.sendMessage(message("&cPlease provide a placeholder to track.\n&7Usage: /"+label+" add ")); return; @@ -38,6 +38,21 @@ public void execute(CommandSender sender, String[] args, String label) { sender.sendMessage(message("&cYou cannot create a leaderboard out of an ajLeaderboards placeholder!\n&7See how to set up the plugin &rhere")); return; } + if(placeholder.length() > 200) { + sender.sendMessage(message( + "&cThat board name is too long! &7Please use a shorter placeholder.\n" + + "&aI recommend using the " + + "" + + "" + + "" + + "" + + "Shortcut expansion" + + "" + + "" + + " &ato make the placeholder shorter\n" + )); + return; + } if(!plugin.validatePlaceholder(placeholder, sender)) { String lowerPlaceholder = placeholder.toLowerCase(Locale.ROOT); sender.sendMessage(message("&cThe placeholder '"+placeholder+"' does not give a numerical value. Make sure that the placeholder returns a number that is not formatted.")); diff --git a/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/Export.java b/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/Export.java index 2b5cea5e..1dba98e6 100644 --- a/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/Export.java +++ b/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/Export.java @@ -1,16 +1,12 @@ package us.ajg0702.leaderboards.commands.main.subcommands; import com.google.gson.Gson; -import com.google.gson.JsonArray; import com.google.gson.JsonObject; -import org.bukkit.Bukkit; import us.ajg0702.commands.CommandSender; import us.ajg0702.commands.SubCommand; import us.ajg0702.leaderboards.LeaderboardPlugin; -import us.ajg0702.leaderboards.cache.helpers.DbRow; import java.io.*; -import java.sql.SQLException; import java.util.*; import java.util.logging.Level; @@ -37,7 +33,7 @@ public void execute(CommandSender sender, String[] args, String label) { sender.sendMessage(message("&cPlease provide a file name.\n&7Usage: /"+label+" export ")); return; } - Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + plugin.getScheduler().runTaskAsynchronously(() -> { String fileName = addJsonEnding(args[0]); File file = new File(plugin.getDataFolder(), fileName); diff --git a/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/Import.java b/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/Import.java index c235cf5e..749b4f24 100644 --- a/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/Import.java +++ b/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/Import.java @@ -4,7 +4,6 @@ import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import org.bukkit.Bukkit; import us.ajg0702.commands.CommandSender; import us.ajg0702.commands.SubCommand; import us.ajg0702.leaderboards.Debug; @@ -42,7 +41,7 @@ public void execute(CommandSender sender, String[] args, String label) { sender.sendMessage(message("&cPlease provide a file name.\n&7Usage: /"+label+" import ")); return; } - Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + plugin.getScheduler().runTaskAsynchronously(() -> { File file = new File(plugin.getDataFolder(), args[0]); if(!file.exists()) { sender.sendMessage(plugin.getMessages().getComponent("commands.import.nofile", "FILE:"+file.getName())); diff --git a/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/ListBoards.java b/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/ListCommand.java similarity index 70% rename from src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/ListBoards.java rename to src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/ListCommand.java index 5b398388..11eee6a5 100644 --- a/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/ListBoards.java +++ b/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/ListCommand.java @@ -1,6 +1,5 @@ package us.ajg0702.leaderboards.commands.main.subcommands; -import org.bukkit.Bukkit; import us.ajg0702.commands.CommandSender; import us.ajg0702.commands.SubCommand; import us.ajg0702.leaderboards.LeaderboardPlugin; @@ -11,22 +10,28 @@ import static us.ajg0702.leaderboards.LeaderboardPlugin.message; -public class ListBoards extends SubCommand { +public class ListCommand extends SubCommand { private final LeaderboardPlugin plugin; - public ListBoards(LeaderboardPlugin plugin) { + public ListCommand(LeaderboardPlugin plugin) { super("list", Collections.emptyList(), "ajleaderboards.use", "List all boards in ajleaderboards, or list the top 10 players in a certain board."); this.plugin = plugin; } @Override public java.util.List autoComplete(CommandSender commandSender, String[] args) { - return filterCompletion(plugin.getTopManager().getBoards(), args[0]); + if(args.length <= 1) { + return filterCompletion(plugin.getTopManager().getBoards(), args[0]); + } else if(args.length == 2) { + return filterCompletion(TimedType.lowerNames(), args[1]); + } else { + return Collections.emptyList(); + } } @Override public void execute(CommandSender sender, String[] args, String label) { - Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + plugin.getScheduler().runTaskAsynchronously(() -> { if(args.length < 1) { StringBuilder list = new StringBuilder("&6Boards"); for(String boardn : plugin.getTopManager().getBoards()) { @@ -35,14 +40,15 @@ public void execute(CommandSender sender, String[] args, String label) { sender.sendMessage(message(list.toString())); return; } - String boardn = args[0]; - if(!plugin.getCache().boardExists(boardn)) { - sender.sendMessage(message("&cThe board '"+boardn+"' does not exist.")); + String board = args[0]; + TimedType timedType = args.length > 1 ? TimedType.of(args[1]) : TimedType.ALLTIME; + if(!plugin.getCache().boardExists(board)) { + sender.sendMessage(message("&cThe board '"+board+"' does not exist.")); return; } - StringBuilder list = new StringBuilder("&6Top for " + boardn); + StringBuilder list = new StringBuilder("&6Top for " + board + " " + timedType.lowerName()); for(int i = 1;i<=10;i++) { - StatEntry e = plugin.getCache().getStat(i, boardn, TimedType.ALLTIME); + StatEntry e = plugin.getCache().getStat(i, board, timedType); list.append("\n&6").append(i).append(". &e").append(e.getPlayerName()).append(" &7- &e").append(e.getScorePretty()); } sender.sendMessage(message(list.toString())); diff --git a/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/Remove.java b/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/Remove.java index 6b9d0d7c..4cc10cba 100644 --- a/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/Remove.java +++ b/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/Remove.java @@ -50,7 +50,7 @@ public void execute(CommandSender sender, String[] args, String label) { "")); confirmDeletes.put(sender.getHandle(), board); Debug.info("Added confirmDelete: "+confirmDeletes.keySet().size()); - Bukkit.getScheduler().runTaskLater(plugin, () -> { + plugin.getScheduler().runTaskLaterAsynchronously(() -> { Debug.info("Removing confirmDelete"); if(confirmDeletes.containsKey(sender.getHandle()) && confirmDeletes.get(sender.getHandle()).equals(board)) { confirmDeletes.remove(sender.getHandle()); diff --git a/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/RemovePlayer.java b/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/RemovePlayer.java index a4178a9e..29416d47 100644 --- a/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/RemovePlayer.java +++ b/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/RemovePlayer.java @@ -54,7 +54,7 @@ public void execute(CommandSender sender, String[] args, String label) { boards = plugin.getCache().getBoards(); } List finalBoards = boards; - Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + plugin.getScheduler().runTaskAsynchronously(() -> { for(String b : finalBoards) { if(plugin.getCache().removePlayer(b, playername)) { sender.sendMessage(message("&aRemoved "+playername+" from "+b+"!")); diff --git a/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/Reset.java b/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/Reset.java index a02538a6..bea5c5bb 100644 --- a/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/Reset.java +++ b/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/Reset.java @@ -53,7 +53,7 @@ public void execute(CommandSender sender, String[] args, String label) { "")); confirmResets.put(sender.getHandle(), board); Debug.info("Added confirmDelete: "+ confirmResets.keySet().size()); - Bukkit.getScheduler().runTaskLater(plugin, () -> { + plugin.getScheduler().runTaskLaterAsynchronously(() -> { if(confirmResets.containsKey(sender.getHandle()) && confirmResets.get(sender.getHandle()).equals(board)) { confirmResets.remove(sender.getHandle()); } diff --git a/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/Update.java b/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/Update.java new file mode 100644 index 00000000..b0d620d2 --- /dev/null +++ b/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/Update.java @@ -0,0 +1,79 @@ +package us.ajg0702.leaderboards.commands.main.subcommands; + +import us.ajg0702.commands.CommandSender; +import us.ajg0702.commands.SubCommand; +import us.ajg0702.leaderboards.LeaderboardPlugin; +import us.ajg0702.utils.common.UpdateManager; + +import java.util.Collections; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; + +public class Update extends SubCommand { + private final LeaderboardPlugin plugin; + public Update(LeaderboardPlugin plugin) { + super("update", Collections.singletonList("updateplugin"), "ajLeaderboards.use", "Download an update for ajLeaderboards (if it is available)"); + this.plugin = plugin; + } + + @Override + public List autoComplete(CommandSender commandSender, String[] strings) { + return Collections.emptyList(); + } + + @Override + public void execute(CommandSender commandSender, String[] strings, String s) { + + UpdateManager updater = plugin.getUpdateManager(); + + if(updater == null) { + commandSender.sendMessage( + plugin.getMessages().getComponent("updater.disabled") + ); + return; + } + + AtomicBoolean done = new AtomicBoolean(false); + plugin.getScheduler().runTaskAsynchronously(() -> { + try { + UpdateManager.DownloadCompleteStatus result = updater.downloadUpdate(); + + done.set(true); + + switch(result) { + case SUCCESS: + commandSender.sendMessage(plugin.getMessages().getComponent("updater.success")); + break; + case WARNING_COULD_NOT_DELETE_OLD_JAR: + commandSender.sendMessage(plugin.getMessages().getComponent("updater.warnings.could-not-delete-old-jar")); + break; + case ERROR_NO_UPDATE_AVAILABLE: + commandSender.sendMessage(plugin.getMessages().getComponent("updater.errors.no-update-available")); + break; + case ERROR_WHILE_CHECKING: + commandSender.sendMessage(plugin.getMessages().getComponent("updater.errors.while-checking")); + break; + case ERROR_ALREADY_DOWNLOADED: + commandSender.sendMessage(plugin.getMessages().getComponent("updater.errors.already-downloaded")); + break; + case ERROR_WHILE_DOWNLOADING: + commandSender.sendMessage(plugin.getMessages().getComponent("updater.errors.while-downloading")); + break; + default: + commandSender.sendMessage(plugin.getMessages().getComponent("updater.errors.unknown", "ERROR:" + result)); + break; + } + } catch(Exception e) { + commandSender.sendMessage(plugin.getMessages().getComponent("updater.errors.uncaught")); + } + }); + plugin.getScheduler().runTaskLaterAsynchronously(() -> { + if(done.get()) return; + + commandSender.sendMessage( + plugin.getMessages().getComponent("updater.slow-feedback") + ); + + }, 20); + } +} diff --git a/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/UpdatePlayer.java b/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/UpdatePlayer.java index 5a53ec87..b649638d 100644 --- a/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/UpdatePlayer.java +++ b/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/UpdatePlayer.java @@ -37,7 +37,7 @@ public void execute(CommandSender sender, String[] args, String label) { sender.sendMessage(message("&cPlease provide a board and player to update\n&7Usage: /"+label+" update ")); return; } - Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + plugin.getScheduler().runTaskAsynchronously(() -> { String board = args[0]; if(!plugin.getCache().boardExists(board) && !board.equals("*")) { sender.sendMessage(message("&cThe board '"+board+"' does not exist.")); diff --git a/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/Viewer.java b/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/Viewer.java index 98e3a8eb..983ab231 100644 --- a/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/Viewer.java +++ b/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/Viewer.java @@ -35,7 +35,7 @@ public List autoComplete(CommandSender sender, String[] args) { @Override public void execute(CommandSender sender, String[] args, String label) { - Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + plugin.getScheduler().runTaskAsynchronously(() -> { JsonObject obj = plugin.getExporter().export(sender); if(obj == null) { sender.sendMessage(plugin.getMessages().getComponent("commands.export.fail")); diff --git a/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/signs/Teleport.java b/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/signs/Teleport.java index d39faf25..b4cdde2d 100644 --- a/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/signs/Teleport.java +++ b/src/main/java/us/ajg0702/leaderboards/commands/main/subcommands/signs/Teleport.java @@ -1,5 +1,6 @@ package us.ajg0702.leaderboards.commands.main.subcommands.signs; +import io.papermc.lib.PaperLib; import org.bukkit.Location; import org.bukkit.entity.Player; import us.ajg0702.commands.CommandSender; @@ -65,6 +66,6 @@ public void execute(CommandSender sender, String[] args, String label) { loc.setX(loc.getBlockX()+0.5); loc.setZ(loc.getBlockZ()+0.5); - player.teleport(loc); + PaperLib.teleportAsync(player, loc); } } diff --git a/src/main/java/us/ajg0702/leaderboards/displays/armorstands/ArmorStandManager.java b/src/main/java/us/ajg0702/leaderboards/displays/armorstands/ArmorStandManager.java index ed1efdba..a542f874 100644 --- a/src/main/java/us/ajg0702/leaderboards/displays/armorstands/ArmorStandManager.java +++ b/src/main/java/us/ajg0702/leaderboards/displays/armorstands/ArmorStandManager.java @@ -14,6 +14,7 @@ import us.ajg0702.leaderboards.Debug; import us.ajg0702.leaderboards.LeaderboardPlugin; import us.ajg0702.leaderboards.displays.signs.BoardSign; +import us.ajg0702.utils.foliacompat.CompatScheduler; import us.ajg0702.utils.spigot.VersionSupport; import java.util.*; @@ -58,46 +59,53 @@ private void checkArmorstand(BoardSign sign, Location loc, String name, UUID id) private void setArmorstandHead(ArmorStand stand, String name, UUID uuid) { Debug.info("Updating armorstand"); - if(VersionSupport.getMinorVersion() >= 10) { - stand.setSilent(true); - } ItemStack item; if(plugin.getHeadUtils().getVersionedHeadUtils() != null) { item = plugin.getHeadUtils().getVersionedHeadUtils().getHeadItem(uuid, name); } else { item = plugin.getHeadUtils().getHeadItem(uuid, name); } - //noinspection deprecation - stand.setHelmet(item); - } - public void search(BoardSign sign, String name, UUID id) { - if(!sign.getLocation().getBlock().getType().toString().contains("SIGN")) return; - if(!plugin.getTopManager().getBoards().contains(sign.getBoard())) return; - if(id == null) return; - Sign ss = sign.getSign(); - if(ss == null) return; - BlockFace face; - if(VersionSupport.getMinorVersion() > 12) { - BlockData bd = ss.getBlockData(); - if(bd instanceof org.bukkit.block.data.type.Sign) { - org.bukkit.block.data.type.Sign bs = (org.bukkit.block.data.type.Sign) bd; - face = bs.getRotation(); - } else if(bd instanceof WallSign) { - WallSign bs = (WallSign) bd; - face = bs.getFacing(); - } else { - Debug.info("Skipping getting face for sign because it is an unknown type! " + bd.getClass()); - return; + Runnable runnable = () -> { + if(VersionSupport.getMinorVersion() >= 10) { + stand.setSilent(true); } + //noinspection deprecation + stand.setHelmet(item); + }; + if(CompatScheduler.isFolia()) { + plugin.getScheduler().runSync(stand, runnable); } else { - @SuppressWarnings("deprecation") org.bukkit.material.Sign bs = (org.bukkit.material.Sign) ss.getData(); - face = bs.getFacing(); + runnable.run(); } + } - Location sl = sign.getLocation(); - + public void search(BoardSign sign, String name, UUID id) { try { + if(!plugin.safeGetBlockType(sign.getLocation()).get(1, TimeUnit.SECONDS).toString().contains("SIGN")) return; + if(!plugin.getTopManager().getBoards().contains(sign.getBoard())) return; + if(id == null) return; + Sign ss = sign.getSign(); + if(ss == null) return; + BlockFace face; + if(VersionSupport.getMinorVersion() > 12) { + BlockData bd = ss.getBlockData(); + if(bd instanceof org.bukkit.block.data.type.Sign) { + org.bukkit.block.data.type.Sign bs = (org.bukkit.block.data.type.Sign) bd; + face = bs.getRotation(); + } else if(bd instanceof WallSign) { + WallSign bs = (WallSign) bd; + face = bs.getFacing(); + } else { + Debug.info("Skipping getting face for sign because it is an unknown type! " + bd.getClass()); + return; + } + } else { + @SuppressWarnings("deprecation") org.bukkit.material.Sign bs = (org.bukkit.material.Sign) ss.getData(); + face = bs.getFacing(); + } + + Location sl = sign.getLocation(); switch(face) { case NORTH: @@ -176,12 +184,13 @@ private Future> getNearbyEntities(Location loc) { if(world == null) { throw new IllegalArgumentException("Invalid world"); } - Bukkit.getScheduler().runTask( - plugin, + plugin.getScheduler().runSync( + loc, () -> future.complete(world.getNearbyEntities(loc, 1, 1, 1)) ); return future; } + public static void debugParticles(Location curloc) { if(!Debug.particles()) return; World world = curloc.getWorld(); diff --git a/src/main/java/us/ajg0702/leaderboards/displays/heads/HeadManager.java b/src/main/java/us/ajg0702/leaderboards/displays/heads/HeadManager.java index ccf3e27b..4f785264 100644 --- a/src/main/java/us/ajg0702/leaderboards/displays/heads/HeadManager.java +++ b/src/main/java/us/ajg0702/leaderboards/displays/heads/HeadManager.java @@ -140,10 +140,12 @@ public void checkHead(Location loc, String name, UUID id) { OfflinePlayer op = VersionSupport.getMinorVersion() > 9 ? Bukkit.getOfflinePlayer(id) : null; - Bukkit.getScheduler().runTask(plugin, () -> { - if(plugin.getHeadUtils().getVersionedHeadUtils() != null) { - plugin.getHeadUtils().getVersionedHeadUtils().setHeadBlock(loc.getBlock(), id, name); - } else { + if(plugin.getHeadUtils().getVersionedHeadUtils() != null) { + plugin.getScheduler().runTaskAsynchronously( + () -> plugin.getHeadUtils().getVersionedHeadUtils().setHeadBlock(loc.getBlock(), id, name) + ); + } else { + plugin.getScheduler().runSync(loc, () -> { BlockState bs = loc.getBlock().getState(); if(!(bs instanceof Skull)) return; @@ -156,8 +158,8 @@ public void checkHead(Location loc, String name, UUID id) { skull.setOwner(name); } skull.update(); - } - headLocationCache.put(loc, id); - }); + }); + } + headLocationCache.put(loc, id); } } diff --git a/src/main/java/us/ajg0702/leaderboards/displays/signs/BoardSign.java b/src/main/java/us/ajg0702/leaderboards/displays/signs/BoardSign.java index 2faf1512..1f2121f7 100644 --- a/src/main/java/us/ajg0702/leaderboards/displays/signs/BoardSign.java +++ b/src/main/java/us/ajg0702/leaderboards/displays/signs/BoardSign.java @@ -6,6 +6,7 @@ import org.bukkit.block.BlockState; import org.bukkit.block.Sign; import org.bukkit.plugin.Plugin; +import us.ajg0702.leaderboards.Debug; import us.ajg0702.leaderboards.LeaderboardPlugin; import us.ajg0702.leaderboards.boards.TimedType; import us.ajg0702.utils.spigot.LocUtils; @@ -34,8 +35,8 @@ public BoardSign(Location location, String board, int position, TimedType type) this.board = board; this.position = position; - this.x = location.getChunk().getX(); - this.z = location.getChunk().getZ(); + this.x = location.getBlockX() >> 4; + this.z = location.getBlockZ() >> 4; this.world = location.getWorld(); this.type = type; @@ -47,7 +48,7 @@ public BoardSign(Location location, String board, int position, TimedType type) private Future setSign() { CompletableFuture future = new CompletableFuture<>(); - Bukkit.getScheduler().runTask(plugin, () -> { + plugin.getScheduler().runSync(location, () -> { BlockState state = location.getBlock().getState(); if(!(state instanceof Sign)) { sign = null; @@ -112,7 +113,7 @@ private Future getBlockType(Location location) { future.completeExceptionally(new InterruptedException()); return future; } - Bukkit.getScheduler().runTask(plugin, () -> future.complete(location.getBlock().getType().toString())); + plugin.getScheduler().runSync(location, () -> future.complete(location.getBlock().getType().toString())); return future; } diff --git a/src/main/java/us/ajg0702/leaderboards/displays/signs/SignManager.java b/src/main/java/us/ajg0702/leaderboards/displays/signs/SignManager.java index 095d1279..cd839e85 100644 --- a/src/main/java/us/ajg0702/leaderboards/displays/signs/SignManager.java +++ b/src/main/java/us/ajg0702/leaderboards/displays/signs/SignManager.java @@ -5,10 +5,12 @@ import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.configuration.file.YamlConfiguration; +import us.ajg0702.leaderboards.Debug; import us.ajg0702.leaderboards.LeaderboardPlugin; import us.ajg0702.leaderboards.boards.StatEntry; import us.ajg0702.leaderboards.boards.TimedType; import us.ajg0702.utils.common.Messages; +import us.ajg0702.utils.foliacompat.Task; import us.ajg0702.utils.spigot.VersionSupport; import java.io.File; @@ -33,7 +35,7 @@ public class SignManager { public SignManager(LeaderboardPlugin plugin) { this.plugin = plugin; - Bukkit.getScheduler().runTask(plugin, this::reload); + plugin.getScheduler().runTaskAsynchronously(this::reload); } @@ -42,7 +44,7 @@ public List getSigns() { return signs; } - int updateIntervalId = -1; + Task updateInterval; public void reload() { cfgFile = new File(plugin.getDataFolder(), "displays.yml"); @@ -68,15 +70,15 @@ public void reload() { } updateNameCache(); - if(updateIntervalId != -1) { + if(updateInterval != null) { try { - Bukkit.getScheduler().cancelTask(updateIntervalId); - updateIntervalId = -1; + updateInterval.cancel(); + updateInterval = null; } catch(IllegalStateException e) { - updateIntervalId = -1; + updateInterval = null; } } - updateIntervalId = Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, this::updateSigns, 10*20, plugin.getAConfig().getInt("sign-update")).getTaskId(); + updateInterval = plugin.getScheduler().runTaskTimerAsynchronously(this::updateSigns, 10*20, plugin.getAConfig().getInt("sign-update")); } /** @@ -103,7 +105,7 @@ public boolean removeSign(Location l, boolean removeText) { signs.remove(s); save = true; s.setRemoved(true); - if(removeText) Bukkit.getScheduler().runTask(plugin, () -> s.setText("", "", "", "")); + if(removeText) plugin.getScheduler().runSync(l, () -> s.setText("", "", "", "")); break; } } @@ -166,7 +168,9 @@ public Map getNames() { } public void updateSign(BoardSign sign) { - if(!isSignChunkLoaded(sign)) return; + if(!isSignChunkLoaded(sign)) { + return; + } try { if(!sign.isPlaced()) return; @@ -205,15 +209,21 @@ public void updateSign(BoardSign sign) { List pLines = new ArrayList<>(); lines.forEach(c -> pLines.add(LEGACY_SIGN_SERIALIZER.serialize(c))); + while(pLines.size() < 4) { // If the user removed one of the lines, add an empty line so it doesnt break + pLines.add(""); + } - if(plugin.isShuttingDown()) return; if(r.hasPlayer()) { - plugin.getHeadManager().search(sign, r.getPlayerName(), r.getPlayerID()); - if(plugin.isShuttingDown()) return; plugin.getArmorStandManager().search(sign, r.getPlayerName(), r.getPlayerID()); } + if(plugin.isShuttingDown()) return; - Bukkit.getScheduler().runTask(plugin, () -> sign.setText(pLines.get(0), pLines.get(1), pLines.get(2), pLines.get(3))); + plugin.getScheduler().runSync(sign.getLocation(), () -> { + sign.setText(pLines.get(0), pLines.get(1), pLines.get(2), pLines.get(3)); + if(r.hasPlayer()) { + plugin.getHeadManager().search(sign, r.getPlayerName(), r.getPlayerID()); + } + }); } public boolean isSignChunkLoaded(BoardSign sign) { diff --git a/src/main/java/us/ajg0702/leaderboards/formatting/PlaceholderFormatter.java b/src/main/java/us/ajg0702/leaderboards/formatting/PlaceholderFormatter.java index 6401f2a6..1c04da6b 100644 --- a/src/main/java/us/ajg0702/leaderboards/formatting/PlaceholderFormatter.java +++ b/src/main/java/us/ajg0702/leaderboards/formatting/PlaceholderFormatter.java @@ -16,10 +16,7 @@ public class PlaceholderFormatter { private final Format defaultFormat = new Default(); private final List formats; - private final LeaderboardPlugin plugin; - public PlaceholderFormatter(LeaderboardPlugin plugin) { - this.plugin = plugin; formats = Arrays.asList( new Time(plugin), new ColonTime(), @@ -38,13 +35,13 @@ public Format getFormatFor(@Nullable String output, String board) { for (Format format : formats) { if(format.equals(defaultFormat)) continue; if(format.matches(null, board)) { - Debug.info("[Formatter] Putting " + format.getName() + " in formatCache for " + board); +// Debug.info("[Formatter] Putting " + format.getName() + " in formatCache for " + board); possibleMatch = format; } } } if(possibleMatch == null) { - Debug.info("[Formatter] No possible match for " + board + ". Using default"); +// Debug.info("[Formatter] No possible match for " + board + ". Using default"); return defaultFormat; } return possibleMatch; diff --git a/src/main/java/us/ajg0702/leaderboards/formatting/formats/ColonTime.java b/src/main/java/us/ajg0702/leaderboards/formatting/formats/ColonTime.java index 5a18058b..e8b5f7b9 100644 --- a/src/main/java/us/ajg0702/leaderboards/formatting/formats/ColonTime.java +++ b/src/main/java/us/ajg0702/leaderboards/formatting/formats/ColonTime.java @@ -9,7 +9,7 @@ public class ColonTime extends Format { - private final Pattern pattern = Pattern.compile("(([0-9]*):)?([0-9]*):([0-9]*)(:|.)?([0-9]*)?"); + private final Pattern pattern = Pattern.compile("(([0-9]*):)?([0-9][0-9]?):([0-9][0-9]?)((:|\\.)([0-9][0-9]?[0-9]?))?$"); @Override public boolean matches(String output, String placeholder) { if(output == null) return false; @@ -30,8 +30,8 @@ public double toDouble(String input) throws NumberFormatException { int minutes = Integer.parseInt(matcher.group(3)); int seconds = Integer.parseInt(matcher.group(4)); - String secondSeparator = matcher.group(5); - String milliseconds = matcher.group(6); + String secondSeparator = matcher.group(6); + String milliseconds = matcher.group(7); double result = 0; @@ -47,6 +47,7 @@ public double toDouble(String input) throws NumberFormatException { } } + Debug.info(input + ": " + result); return result; } diff --git a/src/main/java/us/ajg0702/leaderboards/formatting/formats/Time.java b/src/main/java/us/ajg0702/leaderboards/formatting/formats/Time.java index 248c1afd..0833ff74 100644 --- a/src/main/java/us/ajg0702/leaderboards/formatting/formats/Time.java +++ b/src/main/java/us/ajg0702/leaderboards/formatting/formats/Time.java @@ -11,13 +11,13 @@ import java.util.regex.Pattern; public class Time extends Format { - private final static Pattern weekPattern = Pattern.compile("([1-9][0-9]*)w"); - private final static Pattern dayPattern = Pattern.compile("([1-9][0-9]*)d"); - private final static Pattern hourPattern = Pattern.compile("([1-9][0-9]*)h"); - private final static Pattern minutePattern = Pattern.compile("([1-9][0-9]*)m"); - private final static Pattern secondPattern = Pattern.compile("([1-9][0-9]*)s"); + private final static Pattern weekPattern = Pattern.compile("([0-9]*)w"); + private final static Pattern dayPattern = Pattern.compile("([0-9]*)d"); + private final static Pattern hourPattern = Pattern.compile("([0-9]*)h"); + private final static Pattern minutePattern = Pattern.compile("([0-9]*)m"); + private final static Pattern secondPattern = Pattern.compile("([0-9]*)s"); - private final static Pattern fullPattern = Pattern.compile("(([1-9][0-9]*)w)?(([1-9][0-9]*)d)?(([1-9][0-9]*)h)?(([1-9][0-9]*)m)?(([1-9][0-9]*)s)?"); + private final static Pattern fullPattern = Pattern.compile("(([0-9]*)w)?(([0-9]*)d)?(([0-9]*)h)?(([0-9]*)m)?(([0-9]*)s)?"); private final static Map replaces = new HashMap<>(); static { @@ -40,9 +40,24 @@ public class Time extends Format { private static final List knownTimePlaceholders = Arrays.asList( "statistic_time_played", "statistic_time_since_death", - "mbedwars_stats-play_time" + "mbedwars_stats-play_time", + "formatter_number_time_*" ); + private boolean isKnownTimePlaceholder(String placeholder) { + boolean is = false; + for (String knownTimePlaceholder : knownTimePlaceholders) { + if(knownTimePlaceholder.endsWith("*")) { + is = placeholder.startsWith(knownTimePlaceholder.substring(0, knownTimePlaceholder.length() - 1)); + } else { + is = placeholder.equals(knownTimePlaceholder); + } + if(is) break; + } + + return is; + } + public final LeaderboardPlugin plugin; public Time(@Nullable LeaderboardPlugin plugin) { @@ -51,11 +66,12 @@ public Time(@Nullable LeaderboardPlugin plugin) { @Override public boolean matches(String output, String placeholder) { - if(knownTimePlaceholders.contains(placeholder.toLowerCase(Locale.ROOT))) { + if(isKnownTimePlaceholder(placeholder.toLowerCase(Locale.ROOT))) { // don't bother with more expensive checks below if we know it's a time placeholder // let me know about any other placeholders that should be here! return true; } + if(output == null) return false; if(output.isEmpty()) return false; String temp = output.replaceAll(",", ""); @@ -95,7 +111,7 @@ private static int getSeconds(String output, int multiplier, int seconds, Patter @Override public String toFormat(double input) { - return TimeUtils.formatTimeSeconds(Math.round(input)); + return TimeUtils.formatTimeSeconds(Math.round(input), withSeconds()); } @Override diff --git a/src/main/java/us/ajg0702/leaderboards/loaders/MessageLoader.java b/src/main/java/us/ajg0702/leaderboards/loaders/MessageLoader.java index a7adb9fa..5c7be328 100644 --- a/src/main/java/us/ajg0702/leaderboards/loaders/MessageLoader.java +++ b/src/main/java/us/ajg0702/leaderboards/loaders/MessageLoader.java @@ -77,7 +77,18 @@ public static Messages loadMessages(LeaderboardPlugin plugin) { "loading.text", "Loading", "loading.short", "-?-", "loading.position", "..", - "loading.size", "..." + "loading.size", "...", + + "updater.slow-feedback", "&7Checking for update and downloading...", + "updater.disabled", "&cThe updater is disabled! &7Please enable it in the config to download updates.", + "updater.success", "&aUpdate downloaded! &7Restart the server to apply the update.", + "updater.warnings.could-not-delete-old-jar", "&aUpdate downloaded&e but the old jar could not be deleted. &7Please delete the old jar before restarting the server.", + "updater.errors.no-update-available", "&aYou are already up to date!", + "updater.errors.while-checking", "&eAn error occurred while checking for an update. &7See the console for more info.", + "updater.errors.already-downloaded", "&aYou have already downloaded an update! &7Restart the server to apply it.", + "updater.errors.while-downloading", "&eAn error occurred while downloading an update. &7See the console for more info.", + "updater.errors.unknown", "&eAn unknown error occurred: {ERROR}", + "updater.errors.uncaught", "&cAn error occurred while executing this command. &7See the console." )); } diff --git a/src/main/java/us/ajg0702/leaderboards/placeholders/PlaceholderExpansion.java b/src/main/java/us/ajg0702/leaderboards/placeholders/PlaceholderExpansion.java index 680a5a07..2ab6998f 100644 --- a/src/main/java/us/ajg0702/leaderboards/placeholders/PlaceholderExpansion.java +++ b/src/main/java/us/ajg0702/leaderboards/placeholders/PlaceholderExpansion.java @@ -3,8 +3,7 @@ import org.bukkit.OfflinePlayer; import org.jetbrains.annotations.NotNull; import us.ajg0702.leaderboards.LeaderboardPlugin; -import us.ajg0702.leaderboards.placeholders.placeholders.Reset; -import us.ajg0702.leaderboards.placeholders.placeholders.Size; +import us.ajg0702.leaderboards.placeholders.placeholders.*; import us.ajg0702.leaderboards.placeholders.placeholders.debug.Fetching; import us.ajg0702.leaderboards.placeholders.placeholders.debug.Rolling; import us.ajg0702.leaderboards.placeholders.placeholders.lb.*; @@ -66,6 +65,9 @@ public PlaceholderExpansion(LeaderboardPlugin plugin) { placeholders.add(new Reset(plugin)); placeholders.add(new Size(plugin)); + placeholders.add(new TotalFormatted(plugin)); + placeholders.add(new TotalRaw(plugin)); + placeholders.add(new Total(plugin)); placeholders.add(new Fetching(plugin)); placeholders.add(new Rolling(plugin)); diff --git a/src/main/java/us/ajg0702/leaderboards/placeholders/placeholders/Total.java b/src/main/java/us/ajg0702/leaderboards/placeholders/placeholders/Total.java new file mode 100644 index 00000000..32a11e1e --- /dev/null +++ b/src/main/java/us/ajg0702/leaderboards/placeholders/placeholders/Total.java @@ -0,0 +1,32 @@ +package us.ajg0702.leaderboards.placeholders.placeholders; + +import org.bukkit.OfflinePlayer; +import us.ajg0702.leaderboards.LeaderboardPlugin; +import us.ajg0702.leaderboards.boards.TimedType; +import us.ajg0702.leaderboards.placeholders.Placeholder; + +import java.util.Locale; +import java.util.regex.Matcher; + +public class Total extends Placeholder { + public Total(LeaderboardPlugin plugin) { + super(plugin); + } + + @Override + public String getRegex() { + return "total_(.*)_(.*)"; + } + + @Override + public String parse(Matcher matcher, OfflinePlayer p) { + String board = matcher.group(1); + String typeRaw = matcher.group(2).toUpperCase(Locale.ROOT); + TimedType type = TimedType.of(typeRaw); + if(type == null) { + return "Invalid TimedType '" + typeRaw + "'"; + } + double total = plugin.getTopManager().getTotal(board, type); + return plugin.getPlaceholderFormatter().toFormat(total, board); + } +} diff --git a/src/main/java/us/ajg0702/leaderboards/placeholders/placeholders/TotalFormatted.java b/src/main/java/us/ajg0702/leaderboards/placeholders/placeholders/TotalFormatted.java new file mode 100644 index 00000000..0ea3cc03 --- /dev/null +++ b/src/main/java/us/ajg0702/leaderboards/placeholders/placeholders/TotalFormatted.java @@ -0,0 +1,34 @@ +package us.ajg0702.leaderboards.placeholders.placeholders; + +import org.bukkit.OfflinePlayer; +import us.ajg0702.leaderboards.LeaderboardPlugin; +import us.ajg0702.leaderboards.boards.TimedType; +import us.ajg0702.leaderboards.placeholders.Placeholder; + +import java.util.Locale; +import java.util.regex.Matcher; + +import static us.ajg0702.leaderboards.boards.StatEntry.formatDouble; + +public class TotalFormatted extends Placeholder { + public TotalFormatted(LeaderboardPlugin plugin) { + super(plugin); + } + + @Override + public String getRegex() { + return "total_(.*)_(.*)_formatted"; + } + + @Override + public String parse(Matcher matcher, OfflinePlayer p) { + String board = matcher.group(1); + String typeRaw = matcher.group(2).toUpperCase(Locale.ROOT); + TimedType type = TimedType.of(typeRaw); + if(type == null) { + return "Invalid TimedType '" + typeRaw + "'"; + } + double total = plugin.getTopManager().getTotal(board, type); + return formatDouble(total); + } +} diff --git a/src/main/java/us/ajg0702/leaderboards/placeholders/placeholders/TotalRaw.java b/src/main/java/us/ajg0702/leaderboards/placeholders/placeholders/TotalRaw.java new file mode 100644 index 00000000..34831b33 --- /dev/null +++ b/src/main/java/us/ajg0702/leaderboards/placeholders/placeholders/TotalRaw.java @@ -0,0 +1,34 @@ +package us.ajg0702.leaderboards.placeholders.placeholders; + +import org.bukkit.OfflinePlayer; +import us.ajg0702.leaderboards.LeaderboardPlugin; +import us.ajg0702.leaderboards.boards.TimedType; +import us.ajg0702.leaderboards.placeholders.Placeholder; + +import java.text.DecimalFormat; +import java.util.Locale; +import java.util.regex.Matcher; + +public class TotalRaw extends Placeholder { + public TotalRaw(LeaderboardPlugin plugin) { + super(plugin); + } + + @Override + public String getRegex() { + return "total_(.*)_(.*)_raw"; + } + + @Override + public String parse(Matcher matcher, OfflinePlayer p) { + String board = matcher.group(1); + String typeRaw = matcher.group(2).toUpperCase(Locale.ROOT); + TimedType type = TimedType.of(typeRaw); + if(type == null) { + return "Invalid TimedType '" + typeRaw + "'"; + } + double total = plugin.getTopManager().getTotal(board, type); + DecimalFormat df = new DecimalFormat("#.##"); + return df.format(total); + } +} diff --git a/src/main/java/us/ajg0702/leaderboards/utils/Metrics.java b/src/main/java/us/ajg0702/leaderboards/utils/Metrics.java new file mode 100644 index 00000000..5d505eb5 --- /dev/null +++ b/src/main/java/us/ajg0702/leaderboards/utils/Metrics.java @@ -0,0 +1,882 @@ +/* + * This Metrics class was auto-generated and can be copied into your project if you are + * not using a build tool like Gradle or Maven for dependency management. + * + * IMPORTANT: You are not allowed to modify this class, except changing the package. + * + * Disallowed modifications include but are not limited to: + * - Remove the option for users to opt-out + * - Change the frequency for data submission + * - Obfuscate the code (every obfuscator should allow you to make an exception for specific files) + * - Reformat the code (if you use a linter, add an exception) + * + * Violations will result in a ban of your plugin and account from bStats. + */ +package us.ajg0702.leaderboards.utils; + +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.lang.reflect.Method; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.stream.Collectors; +import java.util.zip.GZIPOutputStream; +import javax.net.ssl.HttpsURLConnection; +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import us.ajg0702.leaderboards.LeaderboardPlugin; + +public class Metrics { + + private final LeaderboardPlugin plugin; + + private final MetricsBase metricsBase; + + /** + * Creates a new Metrics instance. + * + * @param plugin Your plugin instance. + * @param serviceId The id of the service. It can be found at What is my plugin id? + */ + public Metrics(LeaderboardPlugin plugin, int serviceId) { + this.plugin = plugin; + // Get the config file + File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + File configFile = new File(bStatsFolder, "config.yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); + if (!config.isSet("serverUuid")) { + config.addDefault("enabled", true); + config.addDefault("serverUuid", UUID.randomUUID().toString()); + config.addDefault("logFailedRequests", false); + config.addDefault("logSentData", false); + config.addDefault("logResponseStatusText", false); + // Inform the server owners about bStats + config + .options() + .header( + "bStats (https://bStats.org) collects some basic information for plugin authors, like how\n" + + "many people use their plugin and their total player count. It's recommended to keep bStats\n" + + "enabled, but if you're not comfortable with this, you can turn this setting off. There is no\n" + + "performance penalty associated with having metrics enabled, and data sent to bStats is fully\n" + + "anonymous.") + .copyDefaults(true); + try { + config.save(configFile); + } catch (IOException ignored) { + } + } + // Load the data + boolean enabled = config.getBoolean("enabled", true); + String serverUUID = config.getString("serverUuid"); + boolean logErrors = config.getBoolean("logFailedRequests", false); + boolean logSentData = config.getBoolean("logSentData", false); + boolean logResponseStatusText = config.getBoolean("logResponseStatusText", false); + metricsBase = + new MetricsBase( + "bukkit", + serverUUID, + serviceId, + enabled, + this::appendPlatformData, + this::appendServiceData, + submitDataTask -> plugin.getScheduler().runTaskAsynchronously(submitDataTask), + plugin::isEnabled, + (message, error) -> this.plugin.getLogger().log(Level.WARNING, message, error), + (message) -> this.plugin.getLogger().log(Level.INFO, message), + logErrors, + logSentData, + logResponseStatusText); + } + + /** Shuts down the underlying scheduler service. */ + public void shutdown() { + metricsBase.shutdown(); + } + + /** + * Adds a custom chart. + * + * @param chart The chart to add. + */ + public void addCustomChart(CustomChart chart) { + metricsBase.addCustomChart(chart); + } + + private void appendPlatformData(JsonObjectBuilder builder) { + builder.appendField("playerAmount", getPlayerAmount()); + builder.appendField("onlineMode", Bukkit.getOnlineMode() ? 1 : 0); + builder.appendField("bukkitVersion", Bukkit.getVersion()); + builder.appendField("bukkitName", Bukkit.getName()); + builder.appendField("javaVersion", System.getProperty("java.version")); + builder.appendField("osName", System.getProperty("os.name")); + builder.appendField("osArch", System.getProperty("os.arch")); + builder.appendField("osVersion", System.getProperty("os.version")); + builder.appendField("coreCount", Runtime.getRuntime().availableProcessors()); + } + + private void appendServiceData(JsonObjectBuilder builder) { + builder.appendField("pluginVersion", plugin.getDescription().getVersion()); + } + + private int getPlayerAmount() { + try { + // Around MC 1.8 the return type was changed from an array to a collection, + // This fixes java.lang.NoSuchMethodError: + // org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; + Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); + return onlinePlayersMethod.getReturnType().equals(Collection.class) + ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() + : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; + } catch (Exception e) { + // Just use the new method if the reflection failed + return Bukkit.getOnlinePlayers().size(); + } + } + + public static class MetricsBase { + + /** The version of the Metrics class. */ + public static final String METRICS_VERSION = "3.0.2"; + + private static final String REPORT_URL = "https://bStats.org/api/v2/data/%s"; + + private final ScheduledExecutorService scheduler; + + private final String platform; + + private final String serverUuid; + + private final int serviceId; + + private final Consumer appendPlatformDataConsumer; + + private final Consumer appendServiceDataConsumer; + + private final Consumer submitTaskConsumer; + + private final Supplier checkServiceEnabledSupplier; + + private final BiConsumer errorLogger; + + private final Consumer infoLogger; + + private final boolean logErrors; + + private final boolean logSentData; + + private final boolean logResponseStatusText; + + private final Set customCharts = new HashSet<>(); + + private final boolean enabled; + + /** + * Creates a new MetricsBase class instance. + * + * @param platform The platform of the service. + * @param serviceId The id of the service. + * @param serverUuid The server uuid. + * @param enabled Whether or not data sending is enabled. + * @param appendPlatformDataConsumer A consumer that receives a {@code JsonObjectBuilder} and + * appends all platform-specific data. + * @param appendServiceDataConsumer A consumer that receives a {@code JsonObjectBuilder} and + * appends all service-specific data. + * @param submitTaskConsumer A consumer that takes a runnable with the submit task. This can be + * used to delegate the data collection to a another thread to prevent errors caused by + * concurrency. Can be {@code null}. + * @param checkServiceEnabledSupplier A supplier to check if the service is still enabled. + * @param errorLogger A consumer that accepts log message and an error. + * @param infoLogger A consumer that accepts info log messages. + * @param logErrors Whether or not errors should be logged. + * @param logSentData Whether or not the sent data should be logged. + * @param logResponseStatusText Whether or not the response status text should be logged. + */ + public MetricsBase( + String platform, + String serverUuid, + int serviceId, + boolean enabled, + Consumer appendPlatformDataConsumer, + Consumer appendServiceDataConsumer, + Consumer submitTaskConsumer, + Supplier checkServiceEnabledSupplier, + BiConsumer errorLogger, + Consumer infoLogger, + boolean logErrors, + boolean logSentData, + boolean logResponseStatusText) { + ScheduledThreadPoolExecutor scheduler = + new ScheduledThreadPoolExecutor(1, task -> new Thread(task, "bStats-Metrics")); + // We want delayed tasks (non-periodic) that will execute in the future to be + // cancelled when the scheduler is shutdown. + // Otherwise, we risk preventing the server from shutting down even when + // MetricsBase#shutdown() is called + scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); + this.scheduler = scheduler; + this.platform = platform; + this.serverUuid = serverUuid; + this.serviceId = serviceId; + this.enabled = enabled; + this.appendPlatformDataConsumer = appendPlatformDataConsumer; + this.appendServiceDataConsumer = appendServiceDataConsumer; + this.submitTaskConsumer = submitTaskConsumer; + this.checkServiceEnabledSupplier = checkServiceEnabledSupplier; + this.errorLogger = errorLogger; + this.infoLogger = infoLogger; + this.logErrors = logErrors; + this.logSentData = logSentData; + this.logResponseStatusText = logResponseStatusText; + checkRelocation(); + if (enabled) { + // WARNING: Removing the option to opt-out will get your plugin banned from + // bStats + startSubmitting(); + } + } + + public void addCustomChart(CustomChart chart) { + this.customCharts.add(chart); + } + + public void shutdown() { + scheduler.shutdown(); + } + + private void startSubmitting() { + final Runnable submitTask = + () -> { + if (!enabled || !checkServiceEnabledSupplier.get()) { + // Submitting data or service is disabled + scheduler.shutdown(); + return; + } + if (submitTaskConsumer != null) { + submitTaskConsumer.accept(this::submitData); + } else { + this.submitData(); + } + }; + // Many servers tend to restart at a fixed time at xx:00 which causes an uneven + // distribution of requests on the + // bStats backend. To circumvent this problem, we introduce some randomness into + // the initial and second delay. + // WARNING: You must not modify and part of this Metrics class, including the + // submit delay or frequency! + // WARNING: Modifying this code will get your plugin banned on bStats. Just + // don't do it! + long initialDelay = (long) (1000 * 60 * (3 + Math.random() * 3)); + long secondDelay = (long) (1000 * 60 * (Math.random() * 30)); + scheduler.schedule(submitTask, initialDelay, TimeUnit.MILLISECONDS); + scheduler.scheduleAtFixedRate( + submitTask, initialDelay + secondDelay, 1000 * 60 * 30, TimeUnit.MILLISECONDS); + } + + private void submitData() { + final JsonObjectBuilder baseJsonBuilder = new JsonObjectBuilder(); + appendPlatformDataConsumer.accept(baseJsonBuilder); + final JsonObjectBuilder serviceJsonBuilder = new JsonObjectBuilder(); + appendServiceDataConsumer.accept(serviceJsonBuilder); + JsonObjectBuilder.JsonObject[] chartData = + customCharts.stream() + .map(customChart -> customChart.getRequestJsonObject(errorLogger, logErrors)) + .filter(Objects::nonNull) + .toArray(JsonObjectBuilder.JsonObject[]::new); + serviceJsonBuilder.appendField("id", serviceId); + serviceJsonBuilder.appendField("customCharts", chartData); + baseJsonBuilder.appendField("service", serviceJsonBuilder.build()); + baseJsonBuilder.appendField("serverUUID", serverUuid); + baseJsonBuilder.appendField("metricsVersion", METRICS_VERSION); + JsonObjectBuilder.JsonObject data = baseJsonBuilder.build(); + scheduler.execute( + () -> { + try { + // Send the data + sendData(data); + } catch (Exception e) { + // Something went wrong! :( + if (logErrors) { + errorLogger.accept("Could not submit bStats metrics data", e); + } + } + }); + } + + private void sendData(JsonObjectBuilder.JsonObject data) throws Exception { + if (logSentData) { + infoLogger.accept("Sent bStats metrics data: " + data.toString()); + } + String url = String.format(REPORT_URL, platform); + HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection(); + // Compress the data to save bandwidth + byte[] compressedData = compress(data.toString()); + connection.setRequestMethod("POST"); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.addRequestProperty("Content-Encoding", "gzip"); + connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setRequestProperty("User-Agent", "Metrics-Service/1"); + connection.setDoOutput(true); + try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { + outputStream.write(compressedData); + } + StringBuilder builder = new StringBuilder(); + try (BufferedReader bufferedReader = + new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + builder.append(line); + } + } + if (logResponseStatusText) { + infoLogger.accept("Sent data to bStats and received response: " + builder); + } + } + + /** Checks that the class was properly relocated. */ + private void checkRelocation() { + // You can use the property to disable the check in your test environment + if (System.getProperty("bstats.relocatecheck") == null + || !System.getProperty("bstats.relocatecheck").equals("false")) { + // Maven's Relocate is clever and changes strings, too. So we have to use this + // little "trick" ... :D + final String defaultPackage = + new String(new byte[] {'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's'}); + final String examplePackage = + new String(new byte[] {'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); + // We want to make sure no one just copy & pastes the example and uses the wrong + // package names + if (MetricsBase.class.getPackage().getName().startsWith(defaultPackage) + || MetricsBase.class.getPackage().getName().startsWith(examplePackage)) { + throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); + } + } + } + + /** + * Gzips the given string. + * + * @param str The string to gzip. + * @return The gzipped string. + */ + private static byte[] compress(final String str) throws IOException { + if (str == null) { + return null; + } + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { + gzip.write(str.getBytes(StandardCharsets.UTF_8)); + } + return outputStream.toByteArray(); + } + } + + public static class SimplePie extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimplePie(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + String value = callable.call(); + if (value == null || value.isEmpty()) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("value", value).build(); + } + } + + public static class MultiLineChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public MultiLineChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } + } + + public static class AdvancedPie extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedPie(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } + } + + public static class SimpleBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimpleBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + for (Map.Entry entry : map.entrySet()) { + valuesBuilder.appendField(entry.getKey(), new int[] {entry.getValue()}); + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } + } + + public static class AdvancedBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue().length == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } + } + + public static class DrilldownPie extends CustomChart { + + private final Callable>> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public DrilldownPie(String chartId, Callable>> callable) { + super(chartId); + this.callable = callable; + } + + @Override + public JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map> map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean reallyAllSkipped = true; + for (Map.Entry> entryValues : map.entrySet()) { + JsonObjectBuilder valueBuilder = new JsonObjectBuilder(); + boolean allSkipped = true; + for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { + valueBuilder.appendField(valueEntry.getKey(), valueEntry.getValue()); + allSkipped = false; + } + if (!allSkipped) { + reallyAllSkipped = false; + valuesBuilder.appendField(entryValues.getKey(), valueBuilder.build()); + } + } + if (reallyAllSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } + } + + public abstract static class CustomChart { + + private final String chartId; + + protected CustomChart(String chartId) { + if (chartId == null) { + throw new IllegalArgumentException("chartId must not be null"); + } + this.chartId = chartId; + } + + public JsonObjectBuilder.JsonObject getRequestJsonObject( + BiConsumer errorLogger, boolean logErrors) { + JsonObjectBuilder builder = new JsonObjectBuilder(); + builder.appendField("chartId", chartId); + try { + JsonObjectBuilder.JsonObject data = getChartData(); + if (data == null) { + // If the data is null we don't send the chart. + return null; + } + builder.appendField("data", data); + } catch (Throwable t) { + if (logErrors) { + errorLogger.accept("Failed to get data for custom chart with id " + chartId, t); + } + return null; + } + return builder.build(); + } + + protected abstract JsonObjectBuilder.JsonObject getChartData() throws Exception; + } + + public static class SingleLineChart extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SingleLineChart(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + int value = callable.call(); + if (value == 0) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("value", value).build(); + } + } + + /** + * An extremely simple JSON builder. + * + *

While this class is neither feature-rich nor the most performant one, it's sufficient enough + * for its use-case. + */ + public static class JsonObjectBuilder { + + private StringBuilder builder = new StringBuilder(); + + private boolean hasAtLeastOneField = false; + + public JsonObjectBuilder() { + builder.append("{"); + } + + /** + * Appends a null field to the JSON. + * + * @param key The key of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendNull(String key) { + appendFieldUnescaped(key, "null"); + return this; + } + + /** + * Appends a string field to the JSON. + * + * @param key The key of the field. + * @param value The value of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, String value) { + if (value == null) { + throw new IllegalArgumentException("JSON value must not be null"); + } + appendFieldUnescaped(key, "\"" + escape(value) + "\""); + return this; + } + + /** + * Appends an integer field to the JSON. + * + * @param key The key of the field. + * @param value The value of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, int value) { + appendFieldUnescaped(key, String.valueOf(value)); + return this; + } + + /** + * Appends an object to the JSON. + * + * @param key The key of the field. + * @param object The object. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, JsonObject object) { + if (object == null) { + throw new IllegalArgumentException("JSON object must not be null"); + } + appendFieldUnescaped(key, object.toString()); + return this; + } + + /** + * Appends a string array to the JSON. + * + * @param key The key of the field. + * @param values The string array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, String[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values) + .map(value -> "\"" + escape(value) + "\"") + .collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends an integer array to the JSON. + * + * @param key The key of the field. + * @param values The integer array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, int[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values).mapToObj(String::valueOf).collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends an object array to the JSON. + * + * @param key The key of the field. + * @param values The integer array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, JsonObject[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values).map(JsonObject::toString).collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends a field to the object. + * + * @param key The key of the field. + * @param escapedValue The escaped value of the field. + */ + private void appendFieldUnescaped(String key, String escapedValue) { + if (builder == null) { + throw new IllegalStateException("JSON has already been built"); + } + if (key == null) { + throw new IllegalArgumentException("JSON key must not be null"); + } + if (hasAtLeastOneField) { + builder.append(","); + } + builder.append("\"").append(escape(key)).append("\":").append(escapedValue); + hasAtLeastOneField = true; + } + + /** + * Builds the JSON string and invalidates this builder. + * + * @return The built JSON string. + */ + public JsonObject build() { + if (builder == null) { + throw new IllegalStateException("JSON has already been built"); + } + JsonObject object = new JsonObject(builder.append("}").toString()); + builder = null; + return object; + } + + /** + * Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt. + * + *

This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'. + * Compact escapes are not used (e.g., '\n' is escaped as "\u000a" and not as "\n"). + * + * @param value The value to escape. + * @return The escaped value. + */ + private static String escape(String value) { + final StringBuilder builder = new StringBuilder(); + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (c == '"') { + builder.append("\\\""); + } else if (c == '\\') { + builder.append("\\\\"); + } else if (c <= '\u000F') { + builder.append("\\u000").append(Integer.toHexString(c)); + } else if (c <= '\u001F') { + builder.append("\\u00").append(Integer.toHexString(c)); + } else { + builder.append(c); + } + } + return builder.toString(); + } + + /** + * A super simple representation of a JSON object. + * + *

This class only exists to make methods of the {@link JsonObjectBuilder} type-safe and not + * allow a raw string inputs for methods like {@link JsonObjectBuilder#appendField(String, + * JsonObject)}. + */ + public static class JsonObject { + + private final String value; + + private JsonObject(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } + } + } +} + diff --git a/src/main/java/us/ajg0702/leaderboards/utils/OfflineUpdater.java b/src/main/java/us/ajg0702/leaderboards/utils/OfflineUpdater.java index efe008ea..8277a1c4 100644 --- a/src/main/java/us/ajg0702/leaderboards/utils/OfflineUpdater.java +++ b/src/main/java/us/ajg0702/leaderboards/utils/OfflineUpdater.java @@ -25,7 +25,7 @@ public OfflineUpdater(LeaderboardPlugin plugin, String board, OfflinePlayer[] pl offlinePlayerQueue.addAll(Arrays.asList(players)); started = offlinePlayerQueue.size(); - Bukkit.getScheduler().runTaskAsynchronously(this.plugin, () -> { + plugin.getScheduler().runTaskAsynchronously(() -> { startedTime = System.currentTimeMillis(); while(!offlinePlayerQueue.isEmpty() && !plugin.isShuttingDown()) { OfflinePlayer player = offlinePlayerQueue.pop(); diff --git a/src/main/java/us/ajg0702/leaderboards/utils/ResetSaver.java b/src/main/java/us/ajg0702/leaderboards/utils/ResetSaver.java index 8f26dbdc..0bb82c60 100644 --- a/src/main/java/us/ajg0702/leaderboards/utils/ResetSaver.java +++ b/src/main/java/us/ajg0702/leaderboards/utils/ResetSaver.java @@ -16,10 +16,12 @@ import java.nio.file.Path; import java.text.SimpleDateFormat; import java.util.ArrayList; +import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.logging.Level; import java.util.regex.Matcher; +import java.util.stream.Collectors; public class ResetSaver { @@ -30,7 +32,9 @@ public ResetSaver(LeaderboardPlugin plugin) { } private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - private final SimpleDateFormat timeDateFormat = new SimpleDateFormat("yyyy-MM-dd_HH:mm"); + private final SimpleDateFormat timeDateFormat = new SimpleDateFormat("yyyy-MM-dd_'h'HH'm'mm"); + + private final List illegalFileNameChars = Arrays.asList(":", ",", File.separator); public void save(String board, TimedType type) { @@ -72,7 +76,10 @@ public void save(String board, TimedType type) { File.separator + type.lowerName() + File.separator ); File file = new File(folder, - board.replaceAll(Matcher.quoteReplacement(File.separator), "_") + + board.replaceAll( + "(" + illegalFileNameChars.stream().map(Matcher::quoteReplacement).collect(Collectors.joining("|")) + ")", + "_" + ) + "_" + type.lowerName() + "_" + date + ".json" ); if(folder.mkdirs()) { @@ -92,7 +99,7 @@ public void save(String board, TimedType type) { new Gson().toJson(obj, writer); writer.close(); } catch (IOException e) { - plugin.getLogger().log(Level.SEVERE, "An error occurred while writing reset save:", e); + plugin.getLogger().log(Level.SEVERE, "An error occurred while writing reset save to '" + file.getPath() +"':", e); } } } diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 04296b33..3a87ff7c 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -180,6 +180,31 @@ fetching-de-bug: false # Default: true check-cache-on-update: true +# Should we fetch from the database more often? +# ajLeaderboards will always fetch from the database more when the db responds quickly, and less when it is slower. +# Disabling this will make it so ajLeaderboards will fetch from the database less often when the database is fast +# The default is fine for most servers, but you may want to disable this if your database is getting too many requests +# Default: true +more-fetching: true + +# Should we check for updates? +# The updater will also let you update just by doing /ajLeaderboards update +# Changing this requires a restart +enable-updater: true + +# Should we skip some steps when shutting down the plugin to make it faster? +# If you enable this, it can cause warnings after the server shuts down, +# but can also speed up the speed that the server shuts down a lot +# Enabling this *shouldn't* break anything, but unless you have a very good reason to enable this, +# you should probably keep it disabled +# Default: false +fast-shutdown: false + +# What is the minimum time (in milliseconds) we should keep specific player info (e.g. fetching position) +# The cached data may be used for longer if the database is slow at responding to requests. +# Default: 5000 +min-player-cache-time: 5000 + # What maximum number of threads should ajLeaderboards be allowed to use for fetching from the db? # Most of the time, the number of threads used will be far less than this. # This is ignored on mysql (and maxConnections is used for this instead) @@ -201,7 +226,7 @@ fetching-thread-pool-keep-alive: 500 # # # # # # # # # # # # # # # # # # # # # # # # # -# End of config. Happy leaderboard-ing :) # +# End of config. Happy leaderboard-ingmore-fetching :) # # # # # # # # # # # # # # # # # # # # # # # # # # @@ -209,7 +234,7 @@ fetching-thread-pool-keep-alive: 500 # Don't touch this -config-version: 30 +config-version: 34 # ----- THESE OPTIONS HAVE MOVED ----- # to messages.yml. They will be removed from here in the future. diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 6386fbfc..447ec53f 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,6 +1,7 @@ name: ajLeaderboards version: "@VERSION@" main: us.ajg0702.leaderboards.LeaderboardPlugin +folia-supported: true author: ajgeiss0702 depend: [PlaceholderAPI] softdepend: [Vault, SkinsRestorer] diff --git a/src/test/java/us/ajg0702/leaderboards/formatting/formats/ColonTimeTest.java b/src/test/java/us/ajg0702/leaderboards/formatting/formats/ColonTimeTest.java index 5755c656..0799e137 100644 --- a/src/test/java/us/ajg0702/leaderboards/formatting/formats/ColonTimeTest.java +++ b/src/test/java/us/ajg0702/leaderboards/formatting/formats/ColonTimeTest.java @@ -15,7 +15,8 @@ public void testMatches() throws Exception { "1:2:3.4", "11:22:33:44", "11:22:33.44", - "12:3:15.735" + "12:3:15.735", + "00:02:30.95" ); List shouldNotMatch = Arrays.asList( "hello there", diff --git a/src/test/java/us/ajg0702/leaderboards/formatting/formats/TimeTest.java b/src/test/java/us/ajg0702/leaderboards/formatting/formats/TimeTest.java index dbd5838e..f4a61ae2 100644 --- a/src/test/java/us/ajg0702/leaderboards/formatting/formats/TimeTest.java +++ b/src/test/java/us/ajg0702/leaderboards/formatting/formats/TimeTest.java @@ -15,6 +15,12 @@ public void testMatches() throws Exception { "13 hours 21 minutes 15 seconds", "6d 15h 46m 8s", "9h 21m 44s", + "2h 8m 37s", + "9h 21m 44s", + "2s", + "1d 14h 40m", + "0d 14h 40m", + "9h 21m 44s", "2h 8m 37s" ); List shouldNotMatch = Arrays.asList( diff --git a/update.md b/update.md new file mode 100644 index 00000000..53ef2eda --- /dev/null +++ b/update.md @@ -0,0 +1,17 @@ +# Update checklist + +This is for me when releasing updates, because otherwise I forget things + +1. Update version in build.gradle.kts & commit +2. Create tag for update (e.g. 2.8.0) +3. Push tag & ver bump commit (ensure to select checkbox to push tag) +4. Merge dev -> master +5. Create release (draft release notes in release) + * Use github compare for reference: https://github.com/ajgeiss0702/ajLeaderboards/compare/2.7.0...2.8.0 +6. Double-check release notes +7. Release ajLeaderboards on + * Modrinth + * Hangar + * Polymart + * Spigot +8. Announce on discord \ No newline at end of file