Compare commits

...
18 Commits
Author SHA1 Message Date
NotAlexNoyle c9680efb0f Exclude CODEOWNERS from language statistics 2026-10-28 08:31:44 -04:00
NotAlexNoyle 4512c1869d Add CODEOWNERS (one staff approval) 2026-10-28 08:31:44 -04:00
NotAlexNoyle 93a1d85400 Maven -> Gradle 2026-04-21 13:07:20 -04:00
Gabriel Dumitru bb468e3f65 Merge pull request #44 from Kqliber/fix/13
Fix duplicating statistics
2025-03-31 13:21:36 +03:00
Kqliber de058e6ec8 update to 2.11.6 2025-03-29 15:17:04 +00:00
Kqliber 9bf9437f1b fix duplicating statistics 2025-03-28 23:13:05 +00:00
Kqliber 26838520b6 fix Initialization error message 2025-03-28 23:12:10 +00:00
Kqliber 46d8b8c3de update version + repo 2025-03-28 23:11:23 +00:00
Kqliber db4a86ff54 delete target folder 2025-03-28 23:11:01 +00:00
Gabriel Dumitru ae4a6eb7bf Merge pull request #36 from PlaceholderAPI/add-server-version 2022-10-06 19:50:46 +03:00
Gabriel Dumitru d8ec42a7e5 add ServerVersion and clean some code 2022-10-02 01:07:12 +03:00
Gabriel Dumitru 06a17464ec Merge pull request #35 from PlaceholderAPI/change-format-time-method 2022-10-02 00:40:06 +03:00
Gabriel Dumitru 75860d81fa change StatisticUtils#formatTime 2022-10-02 00:32:55 +03:00
Gabriel Dumitru 3acaba152c Merge pull request #28 from Iaiao/offline-player
Support offline players on 1.15 and higher
2021-10-01 12:47:32 +03:00
PiggyPiglet 28928b6901 Increment version number 2021-09-05 09:54:08 +08:00
Iaiao db540510f3 Support offline players on 1.15.2 and higher 2021-05-28 02:46:06 +03:00
PiggyPiglet 1ccc68a7cc Merge pull request #21 from PlaceholderAPI/iGabyTM-patch-1
Updated the formatTime() method
2020-09-23 17:22:46 +08:00
Gabriel Dumitru af33de1ef7 Updated the formatTime() method 2020-09-23 12:19:57 +03:00
16 changed files with 609 additions and 201 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
.gitea/CODEOWNERS linguist-detectable=false
+3
View File
@@ -0,0 +1,3 @@
# Pull requests request review from the eligible staff team(s).
# One approval from either an Admin or Developer satisfies branch protection.
* @trueog/Admins @trueog/Developers
+4 -16
View File
@@ -1,21 +1,9 @@
/target/
.settings
.settings/
.classpath
.project
/.idea/
*.iml
dependency-reduced-pom.xml
.floo*
# Ignore Gradle project-specific cache directory
.gradle
# Ignore Gradle build output directory
build
# IntelliJ
.idea
out
### Maven ###
target/*
.gradle/
build/
out/
+9 -3
View File
@@ -1,3 +1,9 @@
# Statistics-Expansion
Adds placeholders for minecraft statistics
[![Build Status](http://ci.extendedclip.com/buildStatus/icon?job=Statistics-Expansion)](http://ci.extendedclip.com/job/Statistics-Expansion)
# Statistics-PAPI
PlaceholderAPI plugin for Minecraft statistic placeholders.
## Build
```bash
./gradlew build
```
+59
View File
@@ -0,0 +1,59 @@
plugins {
id("java")
id("java-library")
eclipse
}
group = "com.extendedclip.papi.expansion.mcstatistics"
version = "2.0.2"
description = "PlaceholderAPI plugin for Minecraft statistic placeholders"
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
toolchain {
languageVersion.set(JavaLanguageVersion.of(17))
vendor.set(JvmVendorSpec.GRAAL_VM)
}
}
tasks.named<ProcessResources>("processResources") {
from("LICENSE") { into("/") }
}
repositories {
mavenCentral()
maven { url = uri("https://repo.purpurmc.org/snapshots") }
maven { url = uri("https://repo.helpch.at/releases") }
}
dependencies {
compileOnly("org.purpurmc.purpur:purpur-api:1.19.4-R0.1-SNAPSHOT")
compileOnly("me.clip:placeholderapi:2.11.6")
}
apply(from = "eclipse.gradle.kts")
tasks.withType<AbstractArchiveTask>().configureEach {
isPreserveFileTimestamps = false
isReproducibleFileOrder = true
}
tasks.withType<Jar>().configureEach {
archiveBaseName.set(rootProject.name)
manifest {
attributes(
"Implementation-Title" to rootProject.name,
"Implementation-Version" to project.version,
"Specification-Title" to rootProject.name,
"Specification-Version" to project.version,
)
}
}
tasks.withType<JavaCompile>().configureEach {
options.encoding = "UTF-8"
options.release.set(17)
options.isFork = true
options.compilerArgs.add("-parameters")
}
+17
View File
@@ -0,0 +1,17 @@
import org.gradle.plugins.ide.eclipse.model.EclipseModel
val eclipseCompileOnly =
configurations.create("eclipseCompileOnly") {
extendsFrom(configurations.getByName("compileOnly"))
isCanBeResolved = true
isCanBeConsumed = false
}
configure<EclipseModel> {
project {
name = "${rootProject.name}-Plugin"
}
classpath {
plusConfigurations.add(eclipseCompileOnly)
}
}
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+251
View File
@@ -0,0 +1,251 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
Vendored
+94
View File
@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
-66
View File
@@ -1,66 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.extendedclip.papi.expansion.mcstatistics</groupId>
<artifactId>statistics-expansion</artifactId>
<version>2.0.0</version>
<name>PAPI-Expansion-Statistic</name>
<description>PlaceholderAPI expansion for minecraft statistic placeholders</description>
<repositories>
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
<repository>
<id>placeholderapi</id>
<url>https://repo.extendedclip.com/content/repositories/dev/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.15.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
<version>2.10.8-DEV-86</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<finalName>${name}</finalName>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<target>1.8</target>
<source>1.8</source>
<encoding>UTF-8</encoding>
<useIncrementalCompilation>false</useIncrementalCompilation>
</configuration>
</plugin>
</plugins>
</build>
</project>
+1
View File
@@ -0,0 +1 @@
rootProject.name = "Statistics-PAPI"
@@ -0,0 +1,53 @@
package com.extendedclip.papi.expansion.mcstatistics;
import com.google.common.primitives.Ints;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.Statistic;
import org.bukkit.entity.EntityType;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Class for detecting server version for legacy support :(
* @author Matt
*/
public final class ServerVersion {
public static final String AS_STRING = Bukkit.getBukkitVersion().split("-")[0];
private static final int CURRENT_VERSION = getCurrentVersion();
private static final int LATEST_VERSION = 1_19_4;
public static final boolean IS_LEGACY = CURRENT_VERSION < 1_13_0;
/**
* {@link org.bukkit.OfflinePlayer#getStatistic(Statistic)} was added in 1.15
* @see org.bukkit.OfflinePlayer#getStatistic(Statistic, Material)
* @see org.bukkit.OfflinePlayer#getStatistic(Statistic, EntityType)
*/
public static final boolean SUPPORT_OFFLINE_PLAYERS = CURRENT_VERSION >= 1_15_0;
public static final boolean IS_LATEST = CURRENT_VERSION >= LATEST_VERSION;
private static int getCurrentVersion() {
// No need to cache since will only run once
final Matcher matcher = Pattern.compile("(?<version>\\d+\\.\\d+)(?<patch>\\.\\d+)?").matcher(AS_STRING);
final StringBuilder stringBuilder = new StringBuilder();
if (matcher.find()) {
stringBuilder.append(matcher.group("version").replace(".", ""));
final String patch = matcher.group("patch");
if (patch == null) stringBuilder.append("0");
else stringBuilder.append(patch.replace(".", ""));
}
//noinspection UnstableApiUsage
final Integer version = Ints.tryParse(stringBuilder.toString());
// Should never fail
if (version == null) throw new IllegalArgumentException("Could not retrieve server version!");
return version;
}
}
@@ -20,65 +20,54 @@
*/
package com.extendedclip.papi.expansion.mcstatistics;
import com.google.common.base.Enums;
import com.google.common.base.Optional;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import me.clip.placeholderapi.PlaceholderAPIPlugin;
import me.clip.placeholderapi.expansion.Cacheable;
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.Statistic;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
public class StatisticsExpansion extends PlaceholderExpansion implements Cacheable {
private final ListMultimap<Statistic, Material> ignoredMaterials = ArrayListMultimap.create();
private final String VERSION = getClass().getPackage().getImplementationVersion();
private final boolean isLegacy = !Enums.getIfPresent(Material.class, "TURTLE_HELMET").isPresent();
public static final String SERVER_VERSION = Bukkit.getBukkitVersion().split("-")[0];
@Override
public String getAuthor() {
return "clip";
}
import com.google.common.base.Enums;
import com.google.common.base.Optional;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import me.clip.placeholderapi.PlaceholderAPIPlugin;
import me.clip.placeholderapi.expansion.Cacheable;
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.Statistic;
import org.bukkit.entity.EntityType;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
public class StatisticsExpansion extends PlaceholderExpansion implements Cacheable {
private final ListMultimap<Statistic, Material> ignoredMaterials = ArrayListMultimap.create();
private final String version = getClass().getPackage().getImplementationVersion();
@Override
public String getAuthor() {
return "clip";
}
@Override
public String getIdentifier() {
return "statistic";
}
@Override
public String getVersion() {
return VERSION;
}
@Override
public String getVersion() {
return version == null ? "2.0.2" : version;
}
@SuppressWarnings({"DuplicatedCode", "Guava"})
@Override
public String onRequest(final OfflinePlayer offlinePlayer, String identifier) {
if (offlinePlayer == null) {
public String onRequest(OfflinePlayer player, String identifier) {
if (player == null) {
return "";
}
if (!offlinePlayer.isOnline()) {
if (!ServerVersion.SUPPORT_OFFLINE_PLAYERS && !player.isOnline()) {
return "";
}
final Player player = offlinePlayer.getPlayer();
final int secondsPlayed = StatisticsUtils.getSecondsPlayed(player, isLegacy);
final int secondsSinceLastDeath = StatisticsUtils.getSecondsSinceLastDeath(player, isLegacy);
switch (identifier.toLowerCase()) {
case "mine_block": {
return calculateTotal(player, Statistic.MINE_BLOCK);
@@ -100,62 +89,59 @@ public class StatisticsExpansion extends PlaceholderExpansion implements Cacheab
* Time played
*/
case "time_played": {
return StatisticsUtils.formatTime(Duration.of(secondsPlayed, ChronoUnit.SECONDS));
return StatisticsUtils.formatTime(StatisticsUtils.getSecondsPlayed(player));
}
case "time_played:seconds": {
//return seconds != 0 ? Long.toString(TimeUnit.MINUTES.toSeconds(1) - seconds) : "0";
return Integer.toString(secondsPlayed % 60);
return Integer.toString(StatisticsUtils.getSecondsPlayed(player) % 60);
}
case "time_played:minutes": {
//return minutes != 0 ? Long.toString(TimeUnit.HOURS.toMinutes(1) - minutes) : "0";
return Long.toString(TimeUnit.SECONDS.toMinutes(secondsPlayed) % 60);
return Long.toString(TimeUnit.SECONDS.toMinutes(StatisticsUtils.getSecondsPlayed(player)) % 60);
}
case "time_played:hours": {
//return hours != 0 ? Long.toString(TimeUnit.DAYS.toHours(1) - hours) : "0";
return Long.toString(TimeUnit.SECONDS.toHours(secondsPlayed) % 24);
return Long.toString(TimeUnit.SECONDS.toHours(StatisticsUtils.getSecondsPlayed(player)) % 24);
}
case "seconds_played": {
return Integer.toString(secondsPlayed);
return Integer.toString(StatisticsUtils.getSecondsPlayed(player));
}
case "minutes_played": {
return Long.toString(TimeUnit.SECONDS.toMinutes(secondsPlayed));
return Long.toString(TimeUnit.SECONDS.toMinutes(StatisticsUtils.getSecondsPlayed(player)));
}
case "hours_played": {
return Long.toString(TimeUnit.SECONDS.toHours(secondsPlayed));
return Long.toString(TimeUnit.SECONDS.toHours(StatisticsUtils.getSecondsPlayed(player)));
}
case "time_played:days":
case "days_played": {
return Long.toString(TimeUnit.SECONDS.toDays(secondsPlayed));
return Long.toString(TimeUnit.SECONDS.toDays(StatisticsUtils.getSecondsPlayed(player)));
}
/*
* Time since last death
*/
case "time_since_death": {
return StatisticsUtils.formatTime(Duration.of(secondsSinceLastDeath, ChronoUnit.SECONDS));
return StatisticsUtils.formatTime(StatisticsUtils.getSecondsSinceLastDeath(player));
}
case "seconds_since_death": {
return Integer.toString(secondsSinceLastDeath);
return Integer.toString(StatisticsUtils.getSecondsSinceLastDeath(player));
}
case "minutes_since_death": {
return Long.toString(TimeUnit.SECONDS.toMinutes(secondsSinceLastDeath));
return Long.toString(TimeUnit.SECONDS.toMinutes(StatisticsUtils.getSecondsSinceLastDeath(player)));
}
case "hours_since_death": {
return Long.toString(TimeUnit.SECONDS.toHours(secondsSinceLastDeath));
return Long.toString(TimeUnit.SECONDS.toHours(StatisticsUtils.getSecondsSinceLastDeath(player)));
}
case "days_since_death": {
return Long.toString(TimeUnit.SECONDS.toDays(secondsSinceLastDeath));
return Long.toString(TimeUnit.SECONDS.toDays(StatisticsUtils.getSecondsSinceLastDeath(player)));
}
}
@@ -175,7 +161,7 @@ public class StatisticsExpansion extends PlaceholderExpansion implements Cacheab
final Optional<Statistic> statisticOptional = Enums.getIfPresent(Statistic.class, statisticIdentifier);
if (!statisticOptional.isPresent()) {
return "Unknown statistic '" + statisticIdentifier + "', check https://helpch.at/docs/" + SERVER_VERSION + "/org/bukkit/Statistic.html for more info";
return "Unknown statistic '" + statisticIdentifier + "', check " + StatisticsUtils.JAVADOC_BASE_LINK + "/org/bukkit/Statistic.html for more info";
}
final Statistic statistic = statisticOptional.get();
@@ -192,7 +178,7 @@ public class StatisticsExpansion extends PlaceholderExpansion implements Cacheab
}
try {
return Integer.toString(player.getStatistic(statistic, material.get()));
return Integer.toString(ServerVersion.SUPPORT_OFFLINE_PLAYERS ? player.getStatistic(statistic, material.get()) : player.getPlayer().getStatistic(statistic, material.get()));
} catch (IllegalArgumentException e) {
errorLog("Could not get the statistic '" + statistic.name() + "' for '" + material.get().name() + "'", e);
return "Could not get the statistic '" + statistic.name() + "' for '" + material.get().name() + "'";
@@ -207,7 +193,7 @@ public class StatisticsExpansion extends PlaceholderExpansion implements Cacheab
}
try {
return Integer.toString(player.getStatistic(statistic, entityType.get()));
return Integer.toString(ServerVersion.SUPPORT_OFFLINE_PLAYERS ? player.getStatistic(statistic, entityType.get()) : player.getPlayer().getStatistic(statistic, entityType.get()));
} catch (IllegalArgumentException e) {
errorLog("Could not get the statistic '" + statistic.name() + "' for '" + entityType.get().name() + "'", e);
return "Could not get the statistic '" + statistic.name() + "' for '" + entityType.get().name() + "'";
@@ -234,7 +220,7 @@ public class StatisticsExpansion extends PlaceholderExpansion implements Cacheab
}
try {
total.addAndGet(player.getStatistic(statistic, material.get()));
total.addAndGet(ServerVersion.SUPPORT_OFFLINE_PLAYERS ? player.getStatistic(statistic, material.get()) : player.getPlayer().getStatistic(statistic, material.get()));
} catch (IllegalArgumentException e) {
errorLog("Could not get the statistic '" + statistic.name() + "' for '" + material.get().name() + "'", e);
break;
@@ -253,7 +239,7 @@ public class StatisticsExpansion extends PlaceholderExpansion implements Cacheab
}
try {
total.addAndGet(player.getStatistic(statistic, entityType.get()));
total.addAndGet(ServerVersion.SUPPORT_OFFLINE_PLAYERS ? player.getStatistic(statistic, entityType.get()) : player.getPlayer().getStatistic(statistic, entityType.get()));
} catch (IllegalArgumentException e) {
errorLog("Could not get the statistic '" + statistic.name() + "' for '" + entityType.get().name() + "'", e);
break;
@@ -270,7 +256,7 @@ public class StatisticsExpansion extends PlaceholderExpansion implements Cacheab
return Integer.toString(total.get());
}
private String calculateTotal(final Player player, final Statistic statistic) {
private String calculateTotal(final OfflinePlayer player, final Statistic statistic) {
final AtomicLong total = new AtomicLong();
for (Material material : Material.values()) {
@@ -278,12 +264,16 @@ public class StatisticsExpansion extends PlaceholderExpansion implements Cacheab
continue;
}
if (material.name().startsWith("LEGACY_")) {
continue;
}
if (statistic == Statistic.MINE_BLOCK && (material.name().equals("GRASS") || material.name().equals("SOIL"))) {
continue;
}
try {
total.addAndGet(player.getStatistic(statistic, material));
total.addAndGet(ServerVersion.SUPPORT_OFFLINE_PLAYERS ? player.getStatistic(statistic, material) : player.getPlayer().getStatistic(statistic, material));
} catch (IllegalArgumentException ignored) {
ignoredMaterials.put(statistic, material);
}
@@ -292,9 +282,9 @@ public class StatisticsExpansion extends PlaceholderExpansion implements Cacheab
return Long.toString(total.get());
}
private void errorLog(final String message, final Throwable exception) {
PlaceholderAPIPlugin.getInstance().getLogger().log(Level.SEVERE, "[Statistic Expansion] " + message, exception);
}
private void errorLog(final String message, final Throwable exception) {
PlaceholderAPIPlugin.getInstance().getLogger().log(Level.SEVERE, "[Statistic Expansion] " + message, exception);
}
@Override
public void clear() {
@@ -22,35 +22,47 @@ package com.extendedclip.papi.expansion.mcstatistics;
import com.google.common.base.Enums;
import com.google.common.base.Optional;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.Statistic;
import org.bukkit.entity.Player;
import java.time.Duration;
import java.util.StringJoiner;
public class StatisticsUtils {
public static int getSecondsPlayed(final Player player, final boolean isLegacy) {
return isLegacy ? player.getStatistic(Statistic.valueOf("PLAY_ONE_TICK")) / 20 : player.getStatistic(Statistic.PLAY_ONE_MINUTE) / 20;
private static final Statistic SECONDS_PLAYED_STATISTIC = ServerVersion.IS_LEGACY ? Statistic.valueOf("PLAY_ONE_TICK") : Statistic.PLAY_ONE_MINUTE;
private static final Statistic SECONDS_SINCE_LAST_DEATH_STATISTIC = ServerVersion.IS_LEGACY ? Statistic.valueOf("TIME_SINCE_DEATH") : Statistic.TIME_SINCE_DEATH;
public static final String JAVADOC_BASE_LINK = ServerVersion.IS_LATEST ? "https://hub.spigotmc.org/javadocs/spigot" : "https://docs.docdex.helpch.at/" + ServerVersion.AS_STRING;
public static int getSecondsPlayed(final OfflinePlayer player) {
return (ServerVersion.SUPPORT_OFFLINE_PLAYERS ? player.getStatistic(SECONDS_PLAYED_STATISTIC) : player.getPlayer().getStatistic(SECONDS_PLAYED_STATISTIC)) / 20;
}
public static int getSecondsSinceLastDeath(final Player player, final boolean isLegacy) {
return isLegacy ? player.getStatistic(Statistic.valueOf("TIME_SINCE_DEATH")) / 20 : player.getStatistic(Statistic.TIME_SINCE_DEATH) / 20;
public static int getSecondsSinceLastDeath(final OfflinePlayer player) {
return (ServerVersion.SUPPORT_OFFLINE_PLAYERS ? player.getStatistic(SECONDS_SINCE_LAST_DEATH_STATISTIC) : player.getPlayer().getStatistic(SECONDS_SINCE_LAST_DEATH_STATISTIC)) / 20;
}
@SuppressWarnings("Guava")
public static String getStatistic(final Player player, final String identifier) {
public static String getStatistic(final OfflinePlayer player, final String identifier) {
final Optional<Statistic> optional = Enums.getIfPresent(Statistic.class, identifier.toUpperCase());
if(!ServerVersion.SUPPORT_OFFLINE_PLAYERS && !player.isOnline()) {
return "Cannot get statistic, player is offline";
}
if (!optional.isPresent()) {
return "Unknown statistic '" + identifier + "', check https://helpch.at/docs/" + StatisticsExpansion.SERVER_VERSION + "/org/bukkit/Statistic.html for more info";
return "Unknown statistic '" + identifier + "', check " + JAVADOC_BASE_LINK + "/org/bukkit/Statistic.html for more info";
}
if (optional.get().getType() != Statistic.Type.UNTYPED) {
return "The statistic '" + identifier + "' require an argument, check https://helpch.at/docs/" + StatisticsExpansion.SERVER_VERSION + "/org/bukkit/Statistic.Type.html for more info" ;
final Statistic statistic = optional.get();
if (statistic.getType() != Statistic.Type.UNTYPED) {
return "The statistic '" + identifier + "' require an argument, check " + JAVADOC_BASE_LINK + "/org/bukkit/Statistic.Type.html for more info" ;
}
return Integer.toString(player.getStatistic(optional.get()));
int value = ServerVersion.SUPPORT_OFFLINE_PLAYERS ? player.getStatistic(statistic) : player.getPlayer().getStatistic(statistic);
return Integer.toString(value);
}
public static boolean isItem(final Material material, final boolean isLegacy) {
@@ -120,47 +132,39 @@ public class StatisticsUtils {
/**
* @author Sxtanna
*/
public static String formatTime(final Duration duration) {
final StringBuilder builder = new StringBuilder();
public static String formatTime(final long time) {
if (time < 1) {
return "";
}
long seconds = duration.getSeconds();
if (time < 60) {
return time + "s";
}
long seconds = time;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;
long weeks = days / 7;
seconds %= 60;
minutes %= 60;
hours %= 60;
days %= 24;
hours %= 24;
days %= 7;
if (seconds > 0) {
builder.insert(0, seconds + "s");
}
if (minutes > 0) {
if (builder.length() > 0) {
builder.insert(0, ' ');
}
builder.insert(0, minutes + "m");
}
if (hours > 0) {
if (builder.length() > 0) {
builder.insert(0, ' ');
}
builder.insert(0, hours + "h");
}
if (days > 0) {
if (builder.length() > 0) {
builder.insert(0, ' ');
}
builder.insert(0, days + "d");
}
return builder.toString();
final StringJoiner joiner = new StringJoiner(" ");
appendTime(joiner, weeks, "w");
appendTime(joiner, days, "d");
appendTime(joiner, hours, "h");
appendTime(joiner, minutes, "m");
appendTime(joiner, seconds, "s");
return joiner.toString();
}
private static void appendTime(final StringJoiner joiner, final long value, final String unit) {
if (value > 0) {
joiner.add(value + unit);
}
}
}
Binary file not shown.