diff options
author | Linnea Gräf <nea@nea.moe> | 2024-02-15 18:05:28 +0100 |
---|---|---|
committer | Linnea Gräf <nea@nea.moe> | 2024-02-15 18:05:28 +0100 |
commit | ee5d205578117d6fab9b2f89871e5442e480644f (patch) | |
tree | 60753f880972e85e39ed9c1e98bb534253cbd535 | |
download | LocalTransactionLedger-ee5d205578117d6fab9b2f89871e5442e480644f.tar.gz LocalTransactionLedger-ee5d205578117d6fab9b2f89871e5442e480644f.tar.bz2 LocalTransactionLedger-ee5d205578117d6fab9b2f89871e5442e480644f.zip |
Initial commit
-rw-r--r-- | .gitattributes | 3 | ||||
-rw-r--r-- | .github/workflows/build.yml | 29 | ||||
-rw-r--r-- | .github/workflows/gradle-wrapper-validation.yml | 10 | ||||
-rw-r--r-- | .gitignore | 6 | ||||
-rw-r--r-- | build.gradle.kts | 155 | ||||
-rw-r--r-- | gradle.properties | 6 | ||||
-rw-r--r-- | gradle/wrapper/gradle-wrapper.jar | bin | 0 -> 43462 bytes | |||
-rw-r--r-- | gradle/wrapper/gradle-wrapper.properties | 7 | ||||
-rwxr-xr-x | gradlew | 249 | ||||
-rw-r--r-- | gradlew.bat | 92 | ||||
-rw-r--r-- | log4j2.xml | 5 | ||||
-rw-r--r-- | settings.gradle.kts | 26 | ||||
-rw-r--r-- | src/main/java/moe/nea/ledger/init/AutoDiscoveryMixinPlugin.java | 188 | ||||
-rw-r--r-- | src/main/kotlin/moe/nea/ledger/BankDetection.kt | 40 | ||||
-rw-r--r-- | src/main/kotlin/moe/nea/ledger/ChatReceived.kt | 15 | ||||
-rw-r--r-- | src/main/kotlin/moe/nea/ledger/Ledger.kt | 51 | ||||
-rw-r--r-- | src/main/kotlin/moe/nea/ledger/LedgerLogger.kt | 34 | ||||
-rw-r--r-- | src/main/kotlin/moe/nea/ledger/NumberUtil.kt | 32 | ||||
-rw-r--r-- | src/main/resources/mcmod.info | 18 | ||||
-rw-r--r-- | src/main/resources/mixins.ledger.json | 8 |
20 files changed, 974 insertions, 0 deletions
diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..df936ee --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +gradlew* linguist-vendored +gradle/wrapper/* linguist-vendored + diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..e1e773f --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,29 @@ +name: Run Gradle Build +on: + - push + - pull_request + +jobs: + gradle: + runs-on: ubuntu-latest + steps: + - name: Checkout source + uses: actions/checkout@v4.1.1 + + - name: Setup Java + uses: actions/setup-java@v4.0.0 + with: + distribution: temurin + java-version: 17 + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v3 + + - name: Execute Gradle build + run: ./gradlew build + + - name: Upload built mod JAR + uses: actions/upload-artifact@v4.3.0 + with: + name: mod-jar + path: build/libs/*.jar diff --git a/.github/workflows/gradle-wrapper-validation.yml b/.github/workflows/gradle-wrapper-validation.yml new file mode 100644 index 0000000..12213d2 --- /dev/null +++ b/.github/workflows/gradle-wrapper-validation.yml @@ -0,0 +1,10 @@ +name: "Validate Gradle Wrapper" +on: [push, pull_request] + +jobs: + validation: + name: "Validation" + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4.1.1 + - uses: gradle/wrapper-validation-action@v2.0.0
\ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..69fa48a --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.idea/ +.vscode/ +run/ +build/ +.gradle/ + diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..98f7efa --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,155 @@ +import org.apache.commons.lang3.SystemUtils + +plugins { + idea + java + id("gg.essential.loom") version "0.10.0.+" + id("dev.architectury.architectury-pack200") version "0.1.3" + id("com.github.johnrengelman.shadow") version "8.1.1" + kotlin("jvm") version "1.8.21" +} + +//Constants: + +val baseGroup: String by project +val mcVersion: String by project +val version: String by project +val mixinGroup = "$baseGroup.mixin" +val modid: String by project + +// Toolchains: +java { + toolchain.languageVersion.set(JavaLanguageVersion.of(8)) +} + +// Minecraft configuration: +loom { + log4jConfigs.from(file("log4j2.xml")) + launchConfigs { + "client" { + // If you don't want mixins, remove these lines + property("mixin.debug", "true") + property("asmhelper.verbose", "true") + arg("--tweakClass", "org.spongepowered.asm.launch.MixinTweaker") + } + } + runConfigs { + "client" { + if (SystemUtils.IS_OS_MAC_OSX) { + // This argument causes a crash on macOS + vmArgs.remove("-XstartOnFirstThread") + } + } + remove(getByName("server")) + } + forge { + pack200Provider.set(dev.architectury.pack200.java.Pack200Adapter()) + // If you don't want mixins, remove this lines + mixinConfig("mixins.$modid.json") + } + // If you don't want mixins, remove these lines + mixin { + defaultRefmapName.set("mixins.$modid.refmap.json") + } +} + +tasks.compileJava { + dependsOn(tasks.processResources) +} + +sourceSets.main { + output.setResourcesDir(sourceSets.main.flatMap { it.java.classesDirectory }) + java.srcDir(layout.projectDirectory.dir("src/main/kotlin")) + kotlin.destinationDirectory.set(java.destinationDirectory) +} + +// Dependencies: + +repositories { + mavenCentral() + maven("https://repo.spongepowered.org/maven/") + // If you don't want to log in with your real minecraft account, remove this line + maven("https://pkgs.dev.azure.com/djtheredstoner/DevAuth/_packaging/public/maven/v1") +} + +val shadowImpl: Configuration by configurations.creating { + configurations.implementation.get().extendsFrom(this) +} + +dependencies { + minecraft("com.mojang:minecraft:1.8.9") + mappings("de.oceanlabs.mcp:mcp_stable:22-1.8.9") + forge("net.minecraftforge:forge:1.8.9-11.15.1.2318-1.8.9") + + shadowImpl(kotlin("stdlib-jdk8")) + + // If you don't want mixins, remove these lines + shadowImpl("org.spongepowered:mixin:0.7.11-SNAPSHOT") { + isTransitive = false + } + annotationProcessor("org.spongepowered:mixin:0.8.5-SNAPSHOT") + + // If you don't want to log in with your real minecraft account, remove this line + runtimeOnly("me.djtheredstoner:DevAuth-forge-legacy:1.1.2") + +} + +// Tasks: + +tasks.withType(JavaCompile::class) { + options.encoding = "UTF-8" +} + +tasks.withType(Jar::class) { + archiveBaseName.set(modid) + manifest.attributes.run { + this["FMLCorePluginContainsFMLMod"] = "true" + this["ForceLoadAsMod"] = "true" + + // If you don't want mixins, remove these lines + this["TweakClass"] = "org.spongepowered.asm.launch.MixinTweaker" + this["MixinConfigs"] = "mixins.$modid.json" + } +} + +tasks.processResources { + inputs.property("version", project.version) + inputs.property("mcversion", mcVersion) + inputs.property("modid", modid) + inputs.property("basePackage", baseGroup) + + filesMatching(listOf("mcmod.info", "mixins.$modid.json")) { + expand(inputs.properties) + } + + rename("(.+_at.cfg)", "META-INF/$1") +} + + +val remapJar by tasks.named<net.fabricmc.loom.task.RemapJarTask>("remapJar") { + archiveClassifier.set("") + from(tasks.shadowJar) + input.set(tasks.shadowJar.get().archiveFile) +} + +tasks.jar { + archiveClassifier.set("without-deps") + destinationDirectory.set(layout.buildDirectory.dir("badjars")) +} + +tasks.shadowJar { + destinationDirectory.set(layout.buildDirectory.dir("badjars")) + archiveClassifier.set("all-dev") + configurations = listOf(shadowImpl) + doLast { + configurations.forEach { + println("Copying jars into mod: ${it.files}") + } + } + + // If you want to include other dependencies and shadow them, you can relocate them in here + fun relocate(name: String) = relocate(name, "$baseGroup.deps.$name") +} + +tasks.assemble.get().dependsOn(tasks.remapJar) + diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..0cefedf --- /dev/null +++ b/gradle.properties @@ -0,0 +1,6 @@ +loom.platform=forge +org.gradle.jvmargs=-Xmx2g +baseGroup = moe.nea.ledger +mcVersion = 1.8.9 +modid = ledger +version = 1.0.0 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar Binary files differnew file mode 100644 index 0000000..d64cd49 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.jar diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..a80b22c --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists @@ -0,0 +1,249 @@ +#!/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. +# + +############################################################################## +# +# 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/subprojects/plugins/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 "${APP_HOME:-./}" > /dev/null && pwd -P ) || 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=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# 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, 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" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# 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" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@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 + +@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. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +: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 diff --git a/log4j2.xml b/log4j2.xml new file mode 100644 index 0000000..af9b1b7 --- /dev/null +++ b/log4j2.xml @@ -0,0 +1,5 @@ +<?xml version="1.0" encoding="UTF-8"?> +<Configuration status="WARN"> + <!-- Filter out Hypixel scoreboard and sound errors --> + <RegexFilter regex="Error executing task.*|Unable to play unknown soundEvent.*" onMatch="DENY" onMismatch="NEUTRAL"/> +</Configuration>
\ No newline at end of file diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..524d480 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,26 @@ +pluginManagement { + repositories { + mavenCentral() + gradlePluginPortal() + maven("https://oss.sonatype.org/content/repositories/snapshots") + maven("https://maven.architectury.dev/") + maven("https://maven.fabricmc.net") + maven("https://maven.minecraftforge.net/") + maven("https://repo.spongepowered.org/maven/") + maven("https://repo.sk1er.club/repository/maven-releases/") + } + resolutionStrategy { + eachPlugin { + when (requested.id.id) { + "gg.essential.loom" -> useModule("gg.essential:architectury-loom:${requested.version}") + } + } + } +} + +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version("0.6.0") +} + + +rootProject.name = "ledger" diff --git a/src/main/java/moe/nea/ledger/init/AutoDiscoveryMixinPlugin.java b/src/main/java/moe/nea/ledger/init/AutoDiscoveryMixinPlugin.java new file mode 100644 index 0000000..2c3a9c7 --- /dev/null +++ b/src/main/java/moe/nea/ledger/init/AutoDiscoveryMixinPlugin.java @@ -0,0 +1,188 @@ +package moe.nea.ledger.init; + +import org.spongepowered.asm.lib.tree.ClassNode; +import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.stream.Stream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +/** + * A mixin plugin to automatically discover all mixins in the current JAR. + * <p> + * This mixin plugin automatically scans your entire JAR (or class directory, in case of an in-IDE launch) for classes inside of your + * mixin package and registers those. It does this recursively for sub packages of the mixin package as well. This means you will need + * to only have mixin classes inside of your mixin package, which is good style anyway. + * + * @author Linnea Gräf + */ +public class AutoDiscoveryMixinPlugin implements IMixinConfigPlugin { + private static final List<AutoDiscoveryMixinPlugin> mixinPlugins = new ArrayList<>(); + + public static List<AutoDiscoveryMixinPlugin> getMixinPlugins() { + return mixinPlugins; + } + + private String mixinPackage; + + @Override + public void onLoad(String mixinPackage) { + this.mixinPackage = mixinPackage; + mixinPlugins.add(this); + } + + /** + * Resolves the base class root for a given class URL. This resolves either the JAR root, or the class file root. + * In either case the return value of this + the class name will resolve back to the original class url, or to other + * class urls for other classes. + */ + public URL getBaseUrlForClassUrl(URL classUrl) { + String string = classUrl.toString(); + if (classUrl.getProtocol().equals("jar")) { + try { + return new URL(string.substring(4).split("!")[0]); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + } + if (string.endsWith(".class")) { + try { + return new URL(string.replace("\\", "/") + .replace(getClass().getCanonicalName() + .replace(".", "/") + ".class", "")); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + } + return classUrl; + } + + /** + * Get the package that contains all the mixins. This value is set by mixin itself using {@link #onLoad}. + */ + public String getMixinPackage() { + return mixinPackage; + } + + /** + * Get the path inside the class root to the mixin package + */ + public String getMixinBaseDir() { + return mixinPackage.replace(".", "/"); + } + + /** + * A list of all discovered mixins. + */ + private List<String> mixins = null; + + /** + * Try to add mixin class ot the mixins based on the filepath inside of the class root. + * Removes the {@code .class} file suffix, as well as the base mixin package. + * <p><b>This method cannot be called after mixin initialization.</p> + * + * @param className the name or path of a class to be registered as a mixin. + */ + public void tryAddMixinClass(String className) { + String norm = (className.endsWith(".class") ? className.substring(0, className.length() - ".class".length()) : className) + .replace("\\", "/") + .replace("/", "."); + if (norm.startsWith(getMixinPackage() + ".") && !norm.endsWith(".")) { + mixins.add(norm.substring(getMixinPackage().length() + 1)); + } + } + + /** + * Search through the JAR or class directory to find mixins contained in {@link #getMixinPackage()} + */ + @Override + public List<String> getMixins() { + if (mixins != null) return mixins; + System.out.println("Trying to discover mixins"); + mixins = new ArrayList<>(); + URL classUrl = getClass().getProtectionDomain().getCodeSource().getLocation(); + System.out.println("Found classes at " + classUrl); + Path file; + try { + file = Paths.get(getBaseUrlForClassUrl(classUrl).toURI()); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + System.out.println("Base directory found at " + file); + if (Files.isDirectory(file)) { + walkDir(file); + } else { + walkJar(file); + } + System.out.println("Found mixins: " + mixins); + + return mixins; + } + + /** + * Search through directory for mixin classes based on {@link #getMixinBaseDir}. + * + * @param classRoot The root directory in which classes are stored for the default package. + */ + private void walkDir(Path classRoot) { + System.out.println("Trying to find mixins from directory"); + try (Stream<Path> classes = Files.walk(classRoot.resolve(getMixinBaseDir()))) { + classes.map(it -> classRoot.relativize(it).toString()) + .forEach(this::tryAddMixinClass); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + /** + * Read through a JAR file, trying to find all mixins inside. + */ + private void walkJar(Path file) { + System.out.println("Trying to find mixins from jar file"); + try (ZipInputStream zis = new ZipInputStream(Files.newInputStream(file))) { + ZipEntry next; + while ((next = zis.getNextEntry()) != null) { + tryAddMixinClass(next.getName()); + zis.closeEntry(); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { + + } + + @Override + public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { + + } + + @Override + public String getRefMapperConfig() { + return null; + } + + @Override + public boolean shouldApplyMixin(String targetClassName, String mixinClassName) { + return true; + } + + @Override + public void acceptTargets(Set<String> myTargets, Set<String> otherTargets) { + + } +} diff --git a/src/main/kotlin/moe/nea/ledger/BankDetection.kt b/src/main/kotlin/moe/nea/ledger/BankDetection.kt new file mode 100644 index 0000000..6e54539 --- /dev/null +++ b/src/main/kotlin/moe/nea/ledger/BankDetection.kt @@ -0,0 +1,40 @@ +package moe.nea.ledger + +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent +import java.util.regex.Pattern + +class BankDetection(val ledger: LedgerLogger) { + + /* + You have withdrawn 1M coins! You now have 518M coins in your account! + You have deposited 519M coins! You now have 519M coins in your account! + */ + + + val withdrawPattern = + Pattern.compile("^You have withdrawn (?<amount>$SHORT_NUMBER_PATTERN) coins?! You now have (?<newtotal>$SHORT_NUMBER_PATTERN) coins? in your account!$") + val depositPattern = + Pattern.compile("^You have deposited (?<amount>$SHORT_NUMBER_PATTERN) coins?! You now have (?<newtotal>$SHORT_NUMBER_PATTERN) coins? in your account!$") + @SubscribeEvent + fun onChat(event: ChatReceived) { + withdrawPattern.useMatcher(event.message) { + ledger.logEntry( + LedgerEntry( + "BANK_WITHDRAW", + event.timestamp, + parseShortNumber(group("amount")), + ) + ) + } + depositPattern.useMatcher(event.message) { + ledger.logEntry( + LedgerEntry( + "BANK_DEPOSIT", + event.timestamp, + parseShortNumber(group("amount")), + ) + ) + } + } + +} diff --git a/src/main/kotlin/moe/nea/ledger/ChatReceived.kt b/src/main/kotlin/moe/nea/ledger/ChatReceived.kt new file mode 100644 index 0000000..5e19083 --- /dev/null +++ b/src/main/kotlin/moe/nea/ledger/ChatReceived.kt @@ -0,0 +1,15 @@ +package moe.nea.ledger + +import net.minecraftforge.client.event.ClientChatReceivedEvent +import net.minecraftforge.fml.common.eventhandler.Event +import java.time.Instant + +data class ChatReceived( + val message: String, + val timestamp: Instant = Instant.now() +) : Event() { + constructor(event: ClientChatReceivedEvent) : this( + event.message.unformattedText + .replace("§.".toRegex(), "") + ) +}
\ No newline at end of file diff --git a/src/main/kotlin/moe/nea/ledger/Ledger.kt b/src/main/kotlin/moe/nea/ledger/Ledger.kt new file mode 100644 index 0000000..63be626 --- /dev/null +++ b/src/main/kotlin/moe/nea/ledger/Ledger.kt @@ -0,0 +1,51 @@ +package moe.nea.ledger + +import net.minecraftforge.client.event.ClientChatReceivedEvent +import net.minecraftforge.common.MinecraftForge +import net.minecraftforge.fml.common.Mod +import net.minecraftforge.fml.common.event.FMLInitializationEvent +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent + +@Mod(modid = "ledger", useMetadata = true) +class Ledger { + /* + You have withdrawn 1M coins! You now have 518M coins in your account! + You have deposited 519M coins! You now have 519M coins in your account! + + // ORDERS: + + [Bazaar] Buy Order Setup! 160x Wheat for 720.0 coins. + [Bazaar] Claimed 160x Wheat worth 720.0 coins bought for 4.5 each! + + [Bazaar] Sell Offer Setup! 160x Wheat for 933.4 coins. + [Bazaar] Claimed 34,236,799 coins from selling 176x Hyper Catalyst at 196,741 each! + + // INSTABUY: + + [Bazaar] Bought 64x Wheat for 377.6 coins! + [Bazaar] Sold 64x Wheat for 268.8 coins! + + // AUCTION HOUSE: + + You collected 8,712,000 coins from selling Ultimate Carrot Candy Upgrade to [VIP] kodokush in an auction! + You purchased 2x Walnut for 69 coins! + You purchased ◆ Ice Rune I for 4,000 coins! + + TODO: TRADING, FORGE, COOKIE_EATEN, NPC_SELL, NPC_BUY + */ + + @Mod.EventHandler + fun init(event: FMLInitializationEvent) { + val ledger = LedgerLogger() + listOf( + this, + BankDetection(ledger), + ).forEach(MinecraftForge.EVENT_BUS::register) + } + + @SubscribeEvent + fun onChat(event: ClientChatReceivedEvent) { + if (event.type != 2.toByte()) + MinecraftForge.EVENT_BUS.post(ChatReceived(event)) + } +} diff --git a/src/main/kotlin/moe/nea/ledger/LedgerLogger.kt b/src/main/kotlin/moe/nea/ledger/LedgerLogger.kt new file mode 100644 index 0000000..4692a13 --- /dev/null +++ b/src/main/kotlin/moe/nea/ledger/LedgerLogger.kt @@ -0,0 +1,34 @@ +package moe.nea.ledger + +import net.minecraft.client.Minecraft +import net.minecraft.util.ChatComponentText +import java.time.Instant + +class LedgerLogger { + fun printOut(text: String) { + Minecraft.getMinecraft().ingameGUI?.chatGUI?.printChatMessage(ChatComponentText(text)) + } + + fun logEntry(entry: LedgerEntry) { + printOut( + """ + §e================= TRANSACTION START + §eTYPE: §a${entry.transactionType} + §eTIMESTAMP: §a${entry.timestamp} + §eTOTAL VALUE: §a${entry.totalTransactionCoins} + §eITEM ID: §a${entry.itemId} + §eITEM AMOUNT: §a${entry.itemAmount} + §e================= TRANSACTION END + """.trimIndent() + ) + } + +} + +data class LedgerEntry( + val transactionType: String, + val timestamp: Instant, + val totalTransactionCoins: Double, + val itemId: String? = null, + val itemAmount: Int? = null, +) diff --git a/src/main/kotlin/moe/nea/ledger/NumberUtil.kt b/src/main/kotlin/moe/nea/ledger/NumberUtil.kt new file mode 100644 index 0000000..8aa9bb8 --- /dev/null +++ b/src/main/kotlin/moe/nea/ledger/NumberUtil.kt @@ -0,0 +1,32 @@ +package moe.nea.ledger + +import java.util.regex.Matcher +import java.util.regex.Pattern + +// language=regexp +val SHORT_NUMBER_PATTERN = "[0-9]+(?:,[0-9]+)*(?:\\.[0-9]+)?[kKmMbB]?" + +val siScalars = mapOf( + 'k' to 1_000.0, + 'K' to 1_000.0, + 'm' to 1_000_000.0, + 'M' to 1_000_000.0, + 'b' to 1_000_000_000.0, + 'B' to 1_000_000_000.0, +) + +fun parseShortNumber(string: String): Double { + var k = string.replace(",", "") + val scalar = k.last() + var scalarMultiplier = siScalars[scalar] + if (scalarMultiplier == null) { + scalarMultiplier = 1.0 + } else { + k = k.dropLast(1) + } + return k.toDouble() * scalarMultiplier +} + +fun <T> Pattern.useMatcher(string: String, block: Matcher.() -> T): T? = + matcher(string).takeIf { it.matches() }?.let(block) + diff --git a/src/main/resources/mcmod.info b/src/main/resources/mcmod.info new file mode 100644 index 0000000..42456c4 --- /dev/null +++ b/src/main/resources/mcmod.info @@ -0,0 +1,18 @@ +[ + { + "modid": "${modid}", + "name": "Simple Ledger Mod", + "description": "Export all your activities into a file", + "version": "${version}", + "mcversion": "${mcversion}", + "url": "https://github.com/romangraef/Forge1.8.9Template/", + "updateUrl": "", + "authorList": [ + "nea89" + ], + "credits": "", + "logoFile": "", + "screenshots": [], + "dependencies": [] + } +]
\ No newline at end of file diff --git a/src/main/resources/mixins.ledger.json b/src/main/resources/mixins.ledger.json new file mode 100644 index 0000000..5ea0c57 --- /dev/null +++ b/src/main/resources/mixins.ledger.json @@ -0,0 +1,8 @@ +{ + "package": "${basePackage}.mixin", + "plugin": "${basePackage}.init.AutoDiscoveryMixinPlugin", + "refmap": "mixins.${modid}.refmap.json", + "minVersion": "0.7", + "compatibilityLevel": "JAVA_8", + "__comment": "You do not need to manually register mixins in this template. Check the auto discovery mixin plugin for more info." +} |