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
15 changed files with 967 additions and 7 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
+9 -1
View File
@@ -1 +1,9 @@
build/
.settings/
.classpath
.project
/.idea/
*.iml
.floo*
.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
```
-3
View File
@@ -1,3 +0,0 @@
dependencies {
compileOnly project(":api")
}
+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
+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;
}
}
@@ -0,0 +1,293 @@
/*
*
* Statistics-Expansion
* Copyright (C) 2020 Ryan McCarthy
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
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.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 == null ? "2.0.2" : version;
}
@SuppressWarnings({"DuplicatedCode", "Guava"})
@Override
public String onRequest(OfflinePlayer player, String identifier) {
if (player == null) {
return "";
}
if (!ServerVersion.SUPPORT_OFFLINE_PLAYERS && !player.isOnline()) {
return "";
}
switch (identifier.toLowerCase()) {
case "mine_block": {
return calculateTotal(player, Statistic.MINE_BLOCK);
}
case "use_item": {
return calculateTotal(player, Statistic.USE_ITEM);
}
case "break_item": {
return calculateTotal(player, Statistic.BREAK_ITEM);
}
case "craft_item": {
return calculateTotal(player, Statistic.CRAFT_ITEM);
}
/*
* Time played
*/
case "time_played": {
return StatisticsUtils.formatTime(StatisticsUtils.getSecondsPlayed(player));
}
case "time_played:seconds": {
return Integer.toString(StatisticsUtils.getSecondsPlayed(player) % 60);
}
case "time_played:minutes": {
return Long.toString(TimeUnit.SECONDS.toMinutes(StatisticsUtils.getSecondsPlayed(player)) % 60);
}
case "time_played:hours": {
return Long.toString(TimeUnit.SECONDS.toHours(StatisticsUtils.getSecondsPlayed(player)) % 24);
}
case "seconds_played": {
return Integer.toString(StatisticsUtils.getSecondsPlayed(player));
}
case "minutes_played": {
return Long.toString(TimeUnit.SECONDS.toMinutes(StatisticsUtils.getSecondsPlayed(player)));
}
case "hours_played": {
return Long.toString(TimeUnit.SECONDS.toHours(StatisticsUtils.getSecondsPlayed(player)));
}
case "time_played:days":
case "days_played": {
return Long.toString(TimeUnit.SECONDS.toDays(StatisticsUtils.getSecondsPlayed(player)));
}
/*
* Time since last death
*/
case "time_since_death": {
return StatisticsUtils.formatTime(StatisticsUtils.getSecondsSinceLastDeath(player));
}
case "seconds_since_death": {
return Integer.toString(StatisticsUtils.getSecondsSinceLastDeath(player));
}
case "minutes_since_death": {
return Long.toString(TimeUnit.SECONDS.toMinutes(StatisticsUtils.getSecondsSinceLastDeath(player)));
}
case "hours_since_death": {
return Long.toString(TimeUnit.SECONDS.toHours(StatisticsUtils.getSecondsSinceLastDeath(player)));
}
case "days_since_death": {
return Long.toString(TimeUnit.SECONDS.toDays(StatisticsUtils.getSecondsSinceLastDeath(player)));
}
}
final int splitterIndex = identifier.indexOf(':');
// %statistic_<Statistic>%
if (splitterIndex == -1) {
return StatisticsUtils.getStatistic(player, identifier);
}
final String statisticIdentifier = identifier.substring(0, splitterIndex).toUpperCase();
final String types = identifier.substring(splitterIndex + 1).toUpperCase();
if (types.trim().isEmpty()) {
return StatisticsUtils.getStatistic(player, statisticIdentifier);
}
final Optional<Statistic> statisticOptional = Enums.getIfPresent(Statistic.class, statisticIdentifier);
if (!statisticOptional.isPresent()) {
return "Unknown statistic '" + statisticIdentifier + "', check " + StatisticsUtils.JAVADOC_BASE_LINK + "/org/bukkit/Statistic.html for more info";
}
final Statistic statistic = statisticOptional.get();
// %statistic_<Statistic>:<Material/Entity>%
if (!types.contains(",")) {
switch (statistic.getType()) {
case BLOCK:
case ITEM: {
final Optional<Material> material = Enums.getIfPresent(Material.class, types);
if (!material.isPresent()) {
return "Invalid material " + types;
}
try {
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() + "'";
}
}
case ENTITY: {
final Optional<EntityType> entityType = Enums.getIfPresent(EntityType.class, types);
if (!entityType.isPresent()) {
return "Invalid entity " + types;
}
try {
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() + "'";
}
}
default:
break;
}
}
// %statistic_<Statistic>:<Material/Entity>,<Material/Entity>,<Material/Entity>%
final String[] args = types.split(",");
final AtomicInteger total = new AtomicInteger();
switch (statistic.getType()) {
case BLOCK:
case ITEM: {
for (String arg : args) {
final Optional<Material> material = Enums.getIfPresent(Material.class, arg);
if (!material.isPresent()) {
continue;
}
try {
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;
}
}
break;
}
case ENTITY: {
for (String arg : args) {
final Optional<EntityType> entityType = Enums.getIfPresent(EntityType.class, arg);
if (!entityType.isPresent()) {
continue;
}
try {
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;
}
}
break;
}
default:
break;
}
return Integer.toString(total.get());
}
private String calculateTotal(final OfflinePlayer player, final Statistic statistic) {
final AtomicLong total = new AtomicLong();
for (Material material : Material.values()) {
if (ignoredMaterials.get(statistic).contains(material)) {
continue;
}
if (material.name().startsWith("LEGACY_")) {
continue;
}
if (statistic == Statistic.MINE_BLOCK && (material.name().equals("GRASS") || material.name().equals("SOIL"))) {
continue;
}
try {
total.addAndGet(ServerVersion.SUPPORT_OFFLINE_PLAYERS ? player.getStatistic(statistic, material) : player.getPlayer().getStatistic(statistic, material));
} catch (IllegalArgumentException ignored) {
ignoredMaterials.put(statistic, material);
}
}
return Long.toString(total.get());
}
private void errorLog(final String message, final Throwable exception) {
PlaceholderAPIPlugin.getInstance().getLogger().log(Level.SEVERE, "[Statistic Expansion] " + message, exception);
}
@Override
public void clear() {
ignoredMaterials.clear();
}
}
@@ -0,0 +1,170 @@
/*
*
* Statistics-Expansion
* Copyright (C) 2020 Ryan McCarthy
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
package com.extendedclip.papi.expansion.mcstatistics;
import com.google.common.base.Enums;
import com.google.common.base.Optional;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.Statistic;
import java.util.StringJoiner;
public class StatisticsUtils {
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 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 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 " + JAVADOC_BASE_LINK + "/org/bukkit/Statistic.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" ;
}
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) {
if (isLegacy) {
switch (material.name()) {
case "ACACIA_DOOR":
case "BED_BLOCK":
case "BEETROOT_BLOCK":
case "BIRCH_DOOR":
case "BREWING_STAND":
case "BURNING_FURNACE":
case "CAKE_BLOCK":
case "CARROT":
case "CAULDRON":
case "COCOA":
case "CROPS":
case "DARK_OAK_DOOR":
case "DAYLIGHT_DETECTOR_INVERTED":
case "DIODE_BLOCK_OFF":
case "DIODE_BLOCK_ON":
case "DOUBLE_STEP":
case "DOUBLE_STONE_SLAB2":
case "ENDER_PORTAL":
case "END_GATEWAY":
case "FIRE":
case "FLOWER_POT":
case "FROSTED_ICE":
case "GLOWING_REDSTONE_ORE":
case "IRON_DOOR_BLOCK":
case "JUNGLE_DOOR":
case "LAVA":
case "MELON_STEM":
case "NETHER_WARTS":
case "PISTON_EXTENSION":
case "PISTON_MOVING_PIECE":
case "PORTAL":
case "POTATO":
case "PUMPKIN_STEM":
case "PURPUR_DOUBLE_SLAB":
case "REDSTONE_COMPARATOR_OFF":
case "REDSTONE_COMPARATOR_ON":
case "REDSTONE_LAMP_ON":
case "REDSTONE_TORCH_OFF":
case "REDSTONE_WIRE":
case "SIGN_POST":
case "SKULL":
case "SPRUCE_DOOR":
case "STANDING_BANNER":
case "STATIONARY_LAVA":
case "STATIONARY_WATER":
case "SUGAR_CANE_BLOCK":
case "TRIPWIRE":
case "WALL_BANNER":
case "WALL_SIGN":
case "WATER":
case "WOODEN_DOOR":
case "WOOD_DOUBLE_STEP":
return false;
default:
return true;
}
} else {
return material.isItem();
}
}
/**
* @author Sxtanna
*/
public static String formatTime(final long time) {
if (time < 1) {
return "";
}
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 %= 24;
days %= 7;
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);
}
}
}