From 6bdc91b4bda1497e785af695769acae91e8e7064 Mon Sep 17 00:00:00 2001 From: Linnea Gräf Date: Fri, 6 Dec 2024 19:46:33 +0100 Subject: feat: Add logging toggle to options --- src/main/kotlin/moe/nea/ledger/ConfigCommand.kt | 31 +++ src/main/kotlin/moe/nea/ledger/Ledger.kt | 33 +--- src/main/kotlin/moe/nea/ledger/LedgerLogger.kt | 220 +++++++++------------ src/main/kotlin/moe/nea/ledger/LogChatCommand.kt | 27 +++ .../kotlin/moe/nea/ledger/config/DebugOptions.kt | 13 ++ .../kotlin/moe/nea/ledger/config/LedgerConfig.kt | 6 +- .../moe/nea/ledger/config/Synchronization.kt | 11 -- .../nea/ledger/config/SynchronizationOptions.kt | 11 ++ src/main/kotlin/moe/nea/ledger/utils/DIProvider.kt | 4 +- 9 files changed, 191 insertions(+), 165 deletions(-) create mode 100644 src/main/kotlin/moe/nea/ledger/ConfigCommand.kt create mode 100644 src/main/kotlin/moe/nea/ledger/LogChatCommand.kt create mode 100644 src/main/kotlin/moe/nea/ledger/config/DebugOptions.kt delete mode 100644 src/main/kotlin/moe/nea/ledger/config/Synchronization.kt create mode 100644 src/main/kotlin/moe/nea/ledger/config/SynchronizationOptions.kt (limited to 'src/main/kotlin/moe/nea/ledger') diff --git a/src/main/kotlin/moe/nea/ledger/ConfigCommand.kt b/src/main/kotlin/moe/nea/ledger/ConfigCommand.kt new file mode 100644 index 0000000..5222e3b --- /dev/null +++ b/src/main/kotlin/moe/nea/ledger/ConfigCommand.kt @@ -0,0 +1,31 @@ +package moe.nea.ledger + +import io.github.notenoughupdates.moulconfig.common.IMinecraft +import net.minecraft.command.CommandBase +import net.minecraft.command.ICommandSender + +class ConfigCommand : CommandBase() { + override fun canCommandSenderUseCommand(sender: ICommandSender?): Boolean { + return true + } + + override fun getCommandName(): String { + return "ledger" + } + + override fun getCommandUsage(sender: ICommandSender?): String { + return "" + } + + override fun processCommand(sender: ICommandSender?, args: Array) { + val editor = Ledger.managedConfig.getEditor() + editor.search(args.joinToString(" ")) + Ledger.runLater { + IMinecraft.instance.openWrappedScreen(editor) + } + } + + override fun getCommandAliases(): List { + return listOf("moneyledger") + } +} \ 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 index 521fd9d..54ad6e7 100644 --- a/src/main/kotlin/moe/nea/ledger/Ledger.kt +++ b/src/main/kotlin/moe/nea/ledger/Ledger.kt @@ -1,6 +1,5 @@ package moe.nea.ledger -import io.github.notenoughupdates.moulconfig.common.IMinecraft import io.github.notenoughupdates.moulconfig.managed.ManagedConfig import moe.nea.ledger.config.LedgerConfig import moe.nea.ledger.database.Database @@ -17,8 +16,7 @@ import moe.nea.ledger.modules.MinionDetection import moe.nea.ledger.modules.NpcDetection import moe.nea.ledger.utils.DI import net.minecraft.client.Minecraft -import net.minecraft.command.CommandBase -import net.minecraft.command.ICommandSender +import net.minecraft.command.ICommand import net.minecraftforge.client.ClientCommandHandler import net.minecraftforge.client.event.ClientChatReceivedEvent import net.minecraftforge.common.MinecraftForge @@ -83,31 +81,6 @@ class Ledger { logger.info("Initializing ledger") Database.init() - ClientCommandHandler.instance.registerCommand(object : CommandBase() { - override fun canCommandSenderUseCommand(sender: ICommandSender?): Boolean { - return true - } - - override fun getCommandName(): String { - return "ledger" - } - - override fun getCommandUsage(sender: ICommandSender?): String { - return "" - } - - override fun processCommand(sender: ICommandSender?, args: Array) { - val editor = managedConfig.getEditor() - editor.search(args.joinToString(" ")) - runLater { - IMinecraft.instance.openWrappedScreen(editor) - } - } - - override fun getCommandAliases(): List { - return listOf("moneyledger") - } - }) val di = DI() di.registerSingleton(this) di.registerInjectableClasses( @@ -122,9 +95,13 @@ class Ledger { BitsShopDetection::class.java, MinionDetection::class.java, NpcDetection::class.java, + LogChatCommand::class.java, + ConfigCommand::class.java, ) di.instantiateAll() di.getAllInstances().forEach(MinecraftForge.EVENT_BUS::register) + di.getAllInstances().filterIsInstance() + .forEach { ClientCommandHandler.instance.registerCommand(it) } } var lastJoin = -1L diff --git a/src/main/kotlin/moe/nea/ledger/LedgerLogger.kt b/src/main/kotlin/moe/nea/ledger/LedgerLogger.kt index 691eae7..c35d203 100644 --- a/src/main/kotlin/moe/nea/ledger/LedgerLogger.kt +++ b/src/main/kotlin/moe/nea/ledger/LedgerLogger.kt @@ -5,10 +5,7 @@ import com.google.gson.JsonArray import com.google.gson.JsonObject import moe.nea.ledger.events.ChatReceived import net.minecraft.client.Minecraft -import net.minecraft.command.CommandBase -import net.minecraft.command.ICommandSender import net.minecraft.util.ChatComponentText -import net.minecraftforge.client.ClientCommandHandler import net.minecraftforge.fml.common.eventhandler.SubscribeEvent import net.minecraftforge.fml.common.gameevent.TickEvent.ClientTickEvent import java.io.File @@ -17,49 +14,28 @@ import java.time.Instant import java.util.* class LedgerLogger { - fun printOut(text: String) { - Minecraft.getMinecraft().ingameGUI?.chatGUI?.printChatMessage(ChatComponentText(text)) - } + fun printOut(text: String) { + Minecraft.getMinecraft().ingameGUI?.chatGUI?.printChatMessage(ChatComponentText(text)) + } - val profileIdPattern = - "Profile ID: (?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})".toPattern() + val profileIdPattern = + "Profile ID: (?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})".toPattern() - var currentProfile: String? = null + var currentProfile: String? = null - var shouldLog = false + var shouldLog by Ledger.managedConfig.instance.debug::logEntries - init { - ClientCommandHandler.instance.registerCommand(object : CommandBase() { - override fun getCommandName(): String { - return "ledgerlogchat" - } + @SubscribeEvent + fun onProfileSwitch(event: ChatReceived) { + profileIdPattern.useMatcher(event.message) { + currentProfile = group("profile") + } + } - override fun canCommandSenderUseCommand(sender: ICommandSender?): Boolean { - return true - } - override fun getCommandUsage(sender: ICommandSender?): String { - return "" - } - - override fun processCommand(sender: ICommandSender?, args: Array?) { - shouldLog = !shouldLog - printOut("§eLedger logging toggled " + (if (shouldLog) "§aon" else "§coff") + "§e.") - } - }) - } - - @SubscribeEvent - fun onProfileSwitch(event: ChatReceived) { - profileIdPattern.useMatcher(event.message) { - currentProfile = group("profile") - } - } - - - fun printToChat(entry: LedgerEntry) { - printOut( - """ + fun printToChat(entry: LedgerEntry) { + printOut( + """ §e================= TRANSACTION START §eTYPE: §a${entry.transactionType} §eTIMESTAMP: §a${entry.timestamp} @@ -69,93 +45,93 @@ class LedgerLogger { §ePROFILE: §a${currentProfile} §e================= TRANSACTION END """.trimIndent() - ) - } - - val entries = JsonArray() - var hasRecentlyMerged = false - var lastMergeTime = System.currentTimeMillis() - - fun doMerge() { - val allFiles = folder.listFiles()?.toList() ?: emptyList() - val mergedJson = allFiles - .filter { it.name != "merged.json" && it.extension == "json" } - .sortedDescending() - .map { it.readText().trim().removePrefix("[").removeSuffix("]") } - .joinToString(",", "[", "]") - folder.resolve("merged.json").writeText(mergedJson) - hasRecentlyMerged = true - } - - init { - Runtime.getRuntime().addShutdownHook(Thread { doMerge() }) - } - - @SubscribeEvent - fun onTick(event: ClientTickEvent) { - if (!hasRecentlyMerged && (System.currentTimeMillis() - lastMergeTime) > 60_000L) { - lastMergeTime = System.currentTimeMillis() - doMerge() - } - } - - fun logEntry(entry: LedgerEntry) { - if (shouldLog) - printToChat(entry) - Ledger.logger.info("Logging entry of type ${entry.transactionType}") - entries.add(entry.intoJson(currentProfile)) - commit() - } - - fun commit() { - try { - hasRecentlyMerged = false - file.writeText(gson.toJson(entries)) - } catch (ex: Exception) { - Ledger.logger.error("Could not save file", ex) - } - } - - val gson = Gson() - - val folder = Ledger.dataFolder - val file: File = run { - val date = SimpleDateFormat("yyyy.MM.dd").format(Date()) - - generateSequence(0) { it + 1 } - .map { - if (it == 0) - folder.resolve("$date.json") - else - folder.resolve("$date-$it.json") - } - .filter { !it.exists() } - .first() - } + ) + } + + val entries = JsonArray() + var hasRecentlyMerged = false + var lastMergeTime = System.currentTimeMillis() + + fun doMerge() { + val allFiles = folder.listFiles()?.toList() ?: emptyList() + val mergedJson = allFiles + .filter { it.name != "merged.json" && it.extension == "json" } + .sortedDescending() + .map { it.readText().trim().removePrefix("[").removeSuffix("]") } + .joinToString(",", "[", "]") + folder.resolve("merged.json").writeText(mergedJson) + hasRecentlyMerged = true + } + + init { + Runtime.getRuntime().addShutdownHook(Thread { doMerge() }) + } + + @SubscribeEvent + fun onTick(event: ClientTickEvent) { + if (!hasRecentlyMerged && (System.currentTimeMillis() - lastMergeTime) > 60_000L) { + lastMergeTime = System.currentTimeMillis() + doMerge() + } + } + + fun logEntry(entry: LedgerEntry) { + if (shouldLog) + printToChat(entry) + Ledger.logger.info("Logging entry of type ${entry.transactionType}") + entries.add(entry.intoJson(currentProfile)) + commit() + } + + fun commit() { + try { + hasRecentlyMerged = false + file.writeText(gson.toJson(entries)) + } catch (ex: Exception) { + Ledger.logger.error("Could not save file", ex) + } + } + + val gson = Gson() + + val folder = Ledger.dataFolder + val file: File = run { + val date = SimpleDateFormat("yyyy.MM.dd").format(Date()) + + generateSequence(0) { it + 1 } + .map { + if (it == 0) + folder.resolve("$date.json") + else + folder.resolve("$date-$it.json") + } + .filter { !it.exists() } + .first() + } } data class LedgerEntry( - val transactionType: String, - val timestamp: Instant, - val totalTransactionCoins: Double, - val itemId: String? = null, - val itemAmount: Int? = null, + val transactionType: String, + val timestamp: Instant, + val totalTransactionCoins: Double, + val itemId: String? = null, + val itemAmount: Int? = null, ) { - fun intoJson(profileId: String?): JsonObject { - return JsonObject().apply { - addProperty("transactionType", transactionType) - addProperty("timestamp", timestamp.toEpochMilli().toString()) - addProperty("totalTransactionValue", totalTransactionCoins) - addProperty("itemId", itemId ?: "") - addProperty("itemAmount", itemAmount ?: 0) - addProperty("profileId", profileId) - addProperty( - "playerId", - (Minecraft.getMinecraft().thePlayer?.uniqueID?.toString() ?: lastKnownUUID) - .also { lastKnownUUID = it }) - } - } + fun intoJson(profileId: String?): JsonObject { + return JsonObject().apply { + addProperty("transactionType", transactionType) + addProperty("timestamp", timestamp.toEpochMilli().toString()) + addProperty("totalTransactionValue", totalTransactionCoins) + addProperty("itemId", itemId ?: "") + addProperty("itemAmount", itemAmount ?: 0) + addProperty("profileId", profileId) + addProperty( + "playerId", + (Minecraft.getMinecraft().thePlayer?.uniqueID?.toString() ?: lastKnownUUID) + .also { lastKnownUUID = it }) + } + } } var lastKnownUUID = "null" diff --git a/src/main/kotlin/moe/nea/ledger/LogChatCommand.kt b/src/main/kotlin/moe/nea/ledger/LogChatCommand.kt new file mode 100644 index 0000000..0b49a9a --- /dev/null +++ b/src/main/kotlin/moe/nea/ledger/LogChatCommand.kt @@ -0,0 +1,27 @@ +package moe.nea.ledger + +import moe.nea.ledger.utils.Inject +import net.minecraft.command.CommandBase +import net.minecraft.command.ICommandSender + +class LogChatCommand : CommandBase() { + @Inject + lateinit var logger: LedgerLogger + + override fun getCommandName(): String { + return "ledgerlogchat" + } + + override fun canCommandSenderUseCommand(sender: ICommandSender?): Boolean { + return true + } + + override fun getCommandUsage(sender: ICommandSender?): String { + return "" + } + + override fun processCommand(sender: ICommandSender?, args: Array?) { + logger.shouldLog = !logger.shouldLog + logger.printOut("§eLedger logging toggled " + (if (logger.shouldLog) "§aon" else "§coff") + "§e.") + } +} \ No newline at end of file diff --git a/src/main/kotlin/moe/nea/ledger/config/DebugOptions.kt b/src/main/kotlin/moe/nea/ledger/config/DebugOptions.kt new file mode 100644 index 0000000..fd5ed3d --- /dev/null +++ b/src/main/kotlin/moe/nea/ledger/config/DebugOptions.kt @@ -0,0 +1,13 @@ +package moe.nea.ledger.config + +import io.github.notenoughupdates.moulconfig.annotations.ConfigEditorBoolean +import io.github.notenoughupdates.moulconfig.annotations.ConfigOption + +class DebugOptions { + @ConfigOption(name = "Log entries to chat", + desc = "Appends all logged entries into the chat as they are logged. This option does not persist on restarts.") + @Transient + @ConfigEditorBoolean + @JvmField + var logEntries = false +} diff --git a/src/main/kotlin/moe/nea/ledger/config/LedgerConfig.kt b/src/main/kotlin/moe/nea/ledger/config/LedgerConfig.kt index 7ba5abf..367f1e2 100644 --- a/src/main/kotlin/moe/nea/ledger/config/LedgerConfig.kt +++ b/src/main/kotlin/moe/nea/ledger/config/LedgerConfig.kt @@ -22,6 +22,10 @@ class LedgerConfig : Config() { @Category(name = "Synchronization", desc = "") @JvmField - val synchronization = Synchronization() + val synchronization = SynchronizationOptions() + + @Category(name = "Debug", desc = "") + @JvmField + val debug = DebugOptions() } \ No newline at end of file diff --git a/src/main/kotlin/moe/nea/ledger/config/Synchronization.kt b/src/main/kotlin/moe/nea/ledger/config/Synchronization.kt deleted file mode 100644 index e8d5906..0000000 --- a/src/main/kotlin/moe/nea/ledger/config/Synchronization.kt +++ /dev/null @@ -1,11 +0,0 @@ -package moe.nea.ledger.config - -import io.github.notenoughupdates.moulconfig.annotations.ConfigEditorBoolean -import io.github.notenoughupdates.moulconfig.annotations.ConfigOption - -class Synchronization { - @ConfigOption(name = "Test Option", desc = "Test Description") - @ConfigEditorBoolean - @JvmField - var testOption = false -} \ No newline at end of file diff --git a/src/main/kotlin/moe/nea/ledger/config/SynchronizationOptions.kt b/src/main/kotlin/moe/nea/ledger/config/SynchronizationOptions.kt new file mode 100644 index 0000000..b8c740b --- /dev/null +++ b/src/main/kotlin/moe/nea/ledger/config/SynchronizationOptions.kt @@ -0,0 +1,11 @@ +package moe.nea.ledger.config + +import io.github.notenoughupdates.moulconfig.annotations.ConfigEditorBoolean +import io.github.notenoughupdates.moulconfig.annotations.ConfigOption + +class SynchronizationOptions { + @ConfigOption(name = "Test Option", desc = "Test Description") + @ConfigEditorBoolean + @JvmField + var testOption = false +} \ No newline at end of file diff --git a/src/main/kotlin/moe/nea/ledger/utils/DIProvider.kt b/src/main/kotlin/moe/nea/ledger/utils/DIProvider.kt index 3cedf40..98d1bbc 100644 --- a/src/main/kotlin/moe/nea/ledger/utils/DIProvider.kt +++ b/src/main/kotlin/moe/nea/ledger/utils/DIProvider.kt @@ -30,9 +30,7 @@ fun interface DIProvider : BaseDIProvider { }.toTypedArray() val instance = cons.newInstance(*typArgs) for (it in clazz.fields) { - if (it.getAnnotation(Inject::class.java) != null) { - continue - } + if (it.getAnnotation(Inject::class.java) == null) continue it.set(instance, di.provide(it.type, it)) } instance -- cgit