aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLinnea Gräf <nea@nea.moe>2024-12-23 02:22:06 +0100
committerLinnea Gräf <nea@nea.moe>2024-12-23 02:22:06 +0100
commitf0285e44ed113bcf2a11b5d6635f6124deb7fc3b (patch)
tree7ebcc5faaf014287f17696c501351447cbe8890d
parent6b7f5b95b0541eb0e76855152e283e5f9cad0c3c (diff)
downloadLocalTransactionLedger-f0285e44ed113bcf2a11b5d6635f6124deb7fc3b.tar.gz
LocalTransactionLedger-f0285e44ed113bcf2a11b5d6635f6124deb7fc3b.tar.bz2
LocalTransactionLedger-f0285e44ed113bcf2a11b5d6635f6124deb7fc3b.zip
feat: Add in game updater
-rw-r--r--.github/workflows/build.yml8
-rw-r--r--build.gradle.kts5
-rw-r--r--src/main/kotlin/moe/nea/ledger/Ledger.kt12
-rw-r--r--src/main/kotlin/moe/nea/ledger/TriggerCommand.kt34
-rw-r--r--src/main/kotlin/moe/nea/ledger/config/LedgerConfig.kt4
-rw-r--r--src/main/kotlin/moe/nea/ledger/config/MainOptions.kt27
-rw-r--r--src/main/kotlin/moe/nea/ledger/config/UpdateUi.kt17
-rw-r--r--src/main/kotlin/moe/nea/ledger/config/UpdateUiMarker.kt6
-rw-r--r--src/main/kotlin/moe/nea/ledger/events/TriggerEvent.kt7
-rw-r--r--src/main/kotlin/moe/nea/ledger/modules/UpdateChecker.kt149
-rw-r--r--src/main/kotlin/moe/nea/ledger/utils/ErrorUtil.kt9
-rw-r--r--src/main/kotlin/moe/nea/ledger/utils/MinecraftExecutor.kt10
-rw-r--r--src/main/kotlin/moe/nea/ledger/utils/di/DI.kt37
13 files changed, 309 insertions, 16 deletions
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 71a5e94..dfc10a0 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -41,6 +41,13 @@ jobs:
name: mod-jar
- name: Update release
run: |
+ echo Generating notes
+ (
+ echo "Automatically generated nightly release. This release is updated on each new commit"
+ echo
+ echo Generated from commit: \`$(git rev-parse HEAD)\`
+ )> release-notes.md
+ cat release-notes.md
echo Deleting all existing nightly assets
gh release view nightly --json assets \
| jq '.assets[]|.name' -r \
@@ -53,5 +60,6 @@ jobs:
git push -f origin nightly
echo Upload release
gh release upload nightly -- "$(echo *.jar)"
+ gh release edit nightly -F release-notes.md
env:
GH_TOKEN: ${{ github.token }} \ No newline at end of file
diff --git a/build.gradle.kts b/build.gradle.kts
index d911121..dad4b3e 100644
--- a/build.gradle.kts
+++ b/build.gradle.kts
@@ -18,7 +18,7 @@ fun cmd(vararg args: String): String {
standardOutput = baos
commandLine(*args)
}
- return baos.toByteArray().decodeToString().trim()
+ return baos.toByteArray().decodeToString().trim()
}
@@ -76,6 +76,7 @@ sourceSets.main {
repositories {
mavenCentral()
+ maven("https://repo.nea.moe/releases/")
maven("https://repo.spongepowered.org/maven/")
maven("https://maven.notenoughupdates.org/releases")
maven("https://pkgs.dev.azure.com/djtheredstoner/DevAuth/_packaging/public/maven/v1")
@@ -100,6 +101,7 @@ dependencies {
shadowImpl("org.xerial:sqlite-jdbc:3.45.3.0")
shadowImpl("org.notenoughupdates.moulconfig:legacy:3.0.0-beta.9")
shadowImpl("io.azam.ulidj:ulidj:1.0.4")
+ shadowImpl("moe.nea:libautoupdate:1.3.1")
runtimeOnly("me.djtheredstoner:DevAuth-forge-legacy:1.1.2")
testImplementation("org.junit.jupiter:junit-jupiter:5.9.2")
}
@@ -155,6 +157,7 @@ tasks.shadowJar {
destinationDirectory.set(layout.buildDirectory.dir("badjars"))
archiveClassifier.set("all-dev")
configurations = listOf(shadowImpl)
+ relocate("moe.nea.libautoupdate", "moe.nea.ledger.deps.libautoupdate")
mergeServiceFiles()
}
diff --git a/src/main/kotlin/moe/nea/ledger/Ledger.kt b/src/main/kotlin/moe/nea/ledger/Ledger.kt
index bb69621..72bd32f 100644
--- a/src/main/kotlin/moe/nea/ledger/Ledger.kt
+++ b/src/main/kotlin/moe/nea/ledger/Ledger.kt
@@ -3,6 +3,8 @@ package moe.nea.ledger
import com.google.gson.Gson
import io.github.notenoughupdates.moulconfig.managed.ManagedConfig
import moe.nea.ledger.config.LedgerConfig
+import moe.nea.ledger.config.UpdateUi
+import moe.nea.ledger.config.UpdateUiMarker
import moe.nea.ledger.database.Database
import moe.nea.ledger.events.ChatReceived
import moe.nea.ledger.events.LateWorldLoadEvent
@@ -23,9 +25,12 @@ import moe.nea.ledger.modules.KuudraChestDetection
import moe.nea.ledger.modules.MineshaftCorpseDetection
import moe.nea.ledger.modules.MinionDetection
import moe.nea.ledger.modules.NpcDetection
+import moe.nea.ledger.modules.UpdateChecker
import moe.nea.ledger.modules.VisitorDetection
import moe.nea.ledger.utils.ErrorUtil
+import moe.nea.ledger.utils.MinecraftExecutor
import moe.nea.ledger.utils.di.DI
+import moe.nea.ledger.utils.di.DIProvider
import moe.nea.ledger.utils.network.RequestUtil
import net.minecraft.client.Minecraft
import net.minecraft.command.ICommand
@@ -82,6 +87,9 @@ class Ledger {
val logger = LogManager.getLogger("MoneyLedger")
val managedConfig = ManagedConfig.create(File("config/money-ledger/config.json"), LedgerConfig::class.java) {
checkExpose = false
+ customProcessor<UpdateUiMarker> { option, ann ->
+ UpdateUi(option)
+ }
}
val gson = Gson()
private val tickQueue = ConcurrentLinkedQueue<Runnable>()
@@ -100,6 +108,7 @@ class Ledger {
di.registerSingleton(this)
di.registerSingleton(Minecraft.getMinecraft())
di.registerSingleton(gson)
+ di.register(LedgerConfig::class.java, DIProvider { managedConfig.instance })
di.registerInjectableClasses(
AuctionHouseDetection::class.java,
BankDetection::class.java,
@@ -123,6 +132,9 @@ class Ledger {
ForgeDetection::class.java,
NpcDetection::class.java,
GambleDetection::class.java,
+ MinecraftExecutor::class.java,
+ UpdateChecker::class.java,
+ TriggerCommand::class.java,
QueryCommand::class.java,
RequestUtil::class.java,
VisitorDetection::class.java,
diff --git a/src/main/kotlin/moe/nea/ledger/TriggerCommand.kt b/src/main/kotlin/moe/nea/ledger/TriggerCommand.kt
new file mode 100644
index 0000000..c97627d
--- /dev/null
+++ b/src/main/kotlin/moe/nea/ledger/TriggerCommand.kt
@@ -0,0 +1,34 @@
+package moe.nea.ledger
+
+import moe.nea.ledger.events.TriggerEvent
+import net.minecraft.command.CommandBase
+import net.minecraft.command.ICommandSender
+import net.minecraft.event.ClickEvent
+import net.minecraft.util.ChatComponentText
+import net.minecraftforge.common.MinecraftForge
+
+class TriggerCommand : CommandBase() {
+ fun getTriggerCommandLine(trigger: String): ClickEvent {
+ return ClickEvent(ClickEvent.Action.RUN_COMMAND, "/${commandName} $trigger")
+ }
+
+ override fun getCommandName(): String {
+ return "__ledgertrigger"
+ }
+
+ override fun getCommandUsage(sender: ICommandSender?): String {
+ return ""
+ }
+
+ override fun processCommand(sender: ICommandSender, args: Array<out String>) {
+ val event = TriggerEvent(args.joinToString(" "))
+ MinecraftForge.EVENT_BUS.post(event)
+ if (!event.isCanceled)
+ sender.addChatMessage(ChatComponentText("§cCould not find the given trigger. This is an internal command for ledger."))
+ }
+
+ override fun canCommandSenderUseCommand(sender: ICommandSender?): Boolean {
+ return true
+ }
+
+} \ No newline at end of file
diff --git a/src/main/kotlin/moe/nea/ledger/config/LedgerConfig.kt b/src/main/kotlin/moe/nea/ledger/config/LedgerConfig.kt
index 367f1e2..91ee5c1 100644
--- a/src/main/kotlin/moe/nea/ledger/config/LedgerConfig.kt
+++ b/src/main/kotlin/moe/nea/ledger/config/LedgerConfig.kt
@@ -20,6 +20,10 @@ class LedgerConfig : Config() {
return DescriptionRendereringBehaviour.EXPAND_PANEL
}
+ @Category(name = "Ledger", desc = "")
+ @JvmField
+ val main = MainOptions()
+
@Category(name = "Synchronization", desc = "")
@JvmField
val synchronization = SynchronizationOptions()
diff --git a/src/main/kotlin/moe/nea/ledger/config/MainOptions.kt b/src/main/kotlin/moe/nea/ledger/config/MainOptions.kt
new file mode 100644
index 0000000..1efa970
--- /dev/null
+++ b/src/main/kotlin/moe/nea/ledger/config/MainOptions.kt
@@ -0,0 +1,27 @@
+package moe.nea.ledger.config
+
+import io.github.notenoughupdates.moulconfig.annotations.ConfigEditorDropdown
+import io.github.notenoughupdates.moulconfig.annotations.ConfigOption
+
+class MainOptions {
+ @ConfigOption(name = "Marker for Update UI", desc = "_")
+ @JvmField
+ @UpdateUiMarker
+ @Transient
+ var testOption = Unit
+
+ @ConfigOption(name = "Check for Updates", desc = "Automatically check for updates on startup")
+ @ConfigEditorDropdown
+ @JvmField
+ var updateCheck = UpdateCheckBehaviour.SEMI
+
+ enum class UpdateCheckBehaviour(val label: String) {
+ SEMI("Semi-Automatic"),
+ FULL("Full-Automatic"),
+ NONE("Don't check");
+
+ override fun toString(): String {
+ return label
+ }
+ }
+}
diff --git a/src/main/kotlin/moe/nea/ledger/config/UpdateUi.kt b/src/main/kotlin/moe/nea/ledger/config/UpdateUi.kt
new file mode 100644
index 0000000..86ccbf7
--- /dev/null
+++ b/src/main/kotlin/moe/nea/ledger/config/UpdateUi.kt
@@ -0,0 +1,17 @@
+package moe.nea.ledger.config
+
+import io.github.notenoughupdates.moulconfig.gui.GuiComponent
+import io.github.notenoughupdates.moulconfig.gui.component.TextComponent
+import io.github.notenoughupdates.moulconfig.gui.editors.ComponentEditor
+import io.github.notenoughupdates.moulconfig.processor.ProcessedOption
+import moe.nea.ledger.Ledger
+
+class UpdateUi(option: ProcessedOption) : ComponentEditor(option) {
+ val delegate by lazy {// TODO
+ TextComponent("Hier könnte ihre werbung stehen")
+ }
+
+ override fun getDelegate(): GuiComponent {
+ return delegate
+ }
+} \ No newline at end of file
diff --git a/src/main/kotlin/moe/nea/ledger/config/UpdateUiMarker.kt b/src/main/kotlin/moe/nea/ledger/config/UpdateUiMarker.kt
new file mode 100644
index 0000000..7a0466a
--- /dev/null
+++ b/src/main/kotlin/moe/nea/ledger/config/UpdateUiMarker.kt
@@ -0,0 +1,6 @@
+package moe.nea.ledger.config
+
+@Retention(AnnotationRetention.RUNTIME)
+@Target(AnnotationTarget.FIELD)
+annotation class UpdateUiMarker {
+} \ No newline at end of file
diff --git a/src/main/kotlin/moe/nea/ledger/events/TriggerEvent.kt b/src/main/kotlin/moe/nea/ledger/events/TriggerEvent.kt
new file mode 100644
index 0000000..3751f43
--- /dev/null
+++ b/src/main/kotlin/moe/nea/ledger/events/TriggerEvent.kt
@@ -0,0 +1,7 @@
+package moe.nea.ledger.events
+
+import net.minecraftforge.fml.common.eventhandler.Cancelable
+import net.minecraftforge.fml.common.eventhandler.Event
+
+@Cancelable
+data class TriggerEvent(val action: String) : Event()
diff --git a/src/main/kotlin/moe/nea/ledger/modules/UpdateChecker.kt b/src/main/kotlin/moe/nea/ledger/modules/UpdateChecker.kt
new file mode 100644
index 0000000..1d6e299
--- /dev/null
+++ b/src/main/kotlin/moe/nea/ledger/modules/UpdateChecker.kt
@@ -0,0 +1,149 @@
+package moe.nea.ledger.modules
+
+import com.google.gson.JsonPrimitive
+import moe.nea.ledger.DevUtil
+import moe.nea.ledger.LedgerLogger
+import moe.nea.ledger.TriggerCommand
+import moe.nea.ledger.config.LedgerConfig
+import moe.nea.ledger.config.MainOptions
+import moe.nea.ledger.events.RegistrationFinishedEvent
+import moe.nea.ledger.events.TriggerEvent
+import moe.nea.ledger.gen.BuildConfig
+import moe.nea.ledger.utils.ErrorUtil
+import moe.nea.ledger.utils.MinecraftExecutor
+import moe.nea.ledger.utils.di.Inject
+import moe.nea.ledger.utils.network.RequestUtil
+import moe.nea.libautoupdate.CurrentVersion
+import moe.nea.libautoupdate.GithubReleaseUpdateData
+import moe.nea.libautoupdate.GithubReleaseUpdateSource
+import moe.nea.libautoupdate.PotentialUpdate
+import moe.nea.libautoupdate.UpdateContext
+import moe.nea.libautoupdate.UpdateData
+import moe.nea.libautoupdate.UpdateTarget
+import moe.nea.libautoupdate.UpdateUtils
+import net.minecraft.util.ChatComponentText
+import net.minecraft.util.ChatStyle
+import net.minecraftforge.fml.common.eventhandler.SubscribeEvent
+import java.util.concurrent.CompletableFuture
+
+class UpdateChecker @Inject constructor(
+ val errorUtil: ErrorUtil,
+ val requestUtil: RequestUtil,
+) {
+
+ @Inject
+ lateinit var minecraftExecutor: MinecraftExecutor
+
+ val updater = UpdateContext(
+ NightlyAwareGithubUpdateSource("nea89o", "LocalTransactionLedger"),
+ if (DevUtil.isDevEnv) UpdateTarget { listOf() }
+ else UpdateTarget.deleteAndSaveInTheSameFolder(UpdateChecker::class.java),
+ CurrentVersion.ofTag(BuildConfig.GIT_COMMIT),
+ "ledger"
+ )
+
+ class NightlyAwareGithubUpdateSource(owner: String, repository: String) :
+ GithubReleaseUpdateSource(owner, repository) {
+ override fun selectUpdate(updateStream: String, releases: List<GithubRelease>): UpdateData? {
+ if (updateStream == "nightly") {
+ return findAsset(releases.find { it.tagName == "nightly" })
+ }
+ return super.selectUpdate(updateStream, releases.filter { it.tagName != "nightly" })
+ }
+
+ val releaseRegex = "commit: `(?<hash>[a-f0-9]+)`".toPattern()
+
+ override fun findAsset(release: GithubRelease?): UpdateData? {
+ val update = super.findAsset(release) as GithubReleaseUpdateData? ?: return null
+ return GithubReleaseUpdateData(
+ update.versionName,
+ releaseRegex.matcher(update.releaseDescription)
+ .takeIf { it.find() }
+ ?.run { group("hash") }
+ ?.let(::JsonPrimitive)
+ ?: update.versionNumber,
+ update.sha256,
+ update.download,
+ update.releaseDescription,
+ update.targetCommittish,
+ update.createdAt,
+ update.publishedAt,
+ update.htmlUrl
+ )
+ }
+ }
+
+ init {
+ UpdateUtils.patchConnection {
+ this.requestUtil.enhanceConnection(it)
+ }
+ }
+
+ var latestUpdate: PotentialUpdate? = null
+ var hasNotified = false
+
+ @SubscribeEvent
+ fun onStartup(event: RegistrationFinishedEvent) {
+ if (config.main.updateCheck == MainOptions.UpdateCheckBehaviour.NONE) return
+ launchUpdateCheck()
+ }
+
+ fun launchUpdateCheck() {
+ errorUtil.listenToFuture(
+ updater.checkUpdate("nightly")
+ .thenAcceptAsync(
+ {
+ latestUpdate = it
+ informAboutUpdates(it)
+ }, minecraftExecutor)
+ )
+ }
+
+ @Inject
+ lateinit var config: LedgerConfig
+
+ @Inject
+ lateinit var triggerCommand: TriggerCommand
+
+ val installTrigger = "execute-download"
+
+ @Inject
+ lateinit var logger: LedgerLogger
+ fun informAboutUpdates(potentialUpdate: PotentialUpdate) {
+ if (hasNotified) return
+ hasNotified = true
+// logger.printOut("Update: ${potentialUpdate}")
+ if (!potentialUpdate.isUpdateAvailable) return
+ logger.printOut(
+ ChatComponentText("§aThere is a new update for LocalTransactionLedger. Click here to automatically download and install it.")
+ .setChatStyle(ChatStyle().setChatClickEvent(triggerCommand.getTriggerCommandLine(installTrigger))))
+ if (config.main.updateCheck == MainOptions.UpdateCheckBehaviour.FULL) {
+ downloadUpdate()
+ }
+ }
+
+ var updateFuture: CompletableFuture<Void>? = null
+
+ fun downloadUpdate() {
+ val l = latestUpdate ?: return
+ if (updateFuture != null) return
+ // TODO: inject into findAsset to overwrite the tag id with the commit id
+ logger.printOut("§aTrying to download ledger update ${l.update.versionName}")
+ updateFuture =
+ latestUpdate?.launchUpdate()
+ ?.thenAcceptAsync(
+ {
+ logger.printOut("§aLedger update downloaded. It will automatically apply after your next restart.")
+ }, minecraftExecutor)
+ ?.let(errorUtil::listenToFuture)
+ }
+
+ @SubscribeEvent
+ fun onTrigger(event: TriggerEvent) {
+ if (event.action == installTrigger) {
+ event.isCanceled = true
+ downloadUpdate()
+ }
+ }
+
+} \ No newline at end of file
diff --git a/src/main/kotlin/moe/nea/ledger/utils/ErrorUtil.kt b/src/main/kotlin/moe/nea/ledger/utils/ErrorUtil.kt
index 344c8bc..e0c83f9 100644
--- a/src/main/kotlin/moe/nea/ledger/utils/ErrorUtil.kt
+++ b/src/main/kotlin/moe/nea/ledger/utils/ErrorUtil.kt
@@ -4,6 +4,7 @@ import moe.nea.ledger.utils.di.Inject
import moe.nea.ledger.utils.telemetry.ContextValue
import moe.nea.ledger.utils.telemetry.EventRecorder
import moe.nea.ledger.utils.telemetry.Span
+import java.util.concurrent.CompletableFuture
class ErrorUtil {
@@ -27,6 +28,14 @@ class ErrorUtil {
return getOrNull()
}
+ fun <T : CompletableFuture<*>> listenToFuture(t: T): T {
+ t.handle { ignored, exception ->
+ if (exception != null)
+ report(exception, "Uncaught exception in completable future")
+ }
+ return t
+ }
+
inline fun <T> catch(
vararg pairs: Pair<String, ContextValue>,
crossinline function: () -> T
diff --git a/src/main/kotlin/moe/nea/ledger/utils/MinecraftExecutor.kt b/src/main/kotlin/moe/nea/ledger/utils/MinecraftExecutor.kt
new file mode 100644
index 0000000..affd86c
--- /dev/null
+++ b/src/main/kotlin/moe/nea/ledger/utils/MinecraftExecutor.kt
@@ -0,0 +1,10 @@
+package moe.nea.ledger.utils
+
+import net.minecraft.client.Minecraft
+import java.util.concurrent.Executor
+
+class MinecraftExecutor : Executor {
+ override fun execute(command: Runnable) {
+ Minecraft.getMinecraft().addScheduledTask(command)
+ }
+} \ No newline at end of file
diff --git a/src/main/kotlin/moe/nea/ledger/utils/di/DI.kt b/src/main/kotlin/moe/nea/ledger/utils/di/DI.kt
index 133637a..a9061d7 100644
--- a/src/main/kotlin/moe/nea/ledger/utils/di/DI.kt
+++ b/src/main/kotlin/moe/nea/ledger/utils/di/DI.kt
@@ -9,25 +9,32 @@ class DI {
private fun formatInjectionStack() =
injectionStack.joinToString(" -> ")
+ fun <T : Any> getProvider(type: Class<T>): BaseDIProvider<T, *> {
+ val provider = providers[type] as BaseDIProvider<T, *>?
+ ?: error("Could not find provider for type $type")
+ return provider
+ }
+
private fun <T : Any, C> internalProvide(type: Class<T>, element: AnnotatedElement? = null): T {
- val provider = providers[type] as BaseDIProvider<T, C>
- val context = if (element == null) provider.createEmptyContext() else provider.createContext(element)
- val key = Pair(type, context)
- val existingValue = values[key]
- if (existingValue != null) return existingValue as T
- if (type in injectionStack) {
- error("Found injection cycle: ${formatInjectionStack()} -> $type")
- }
- injectionStack.push(type)
- val value = try {
- provider.provideWithContext(this, context)
+ try {
+ val provider = getProvider(type) as BaseDIProvider<T, C>
+ val context = if (element == null) provider.createEmptyContext() else provider.createContext(element)
+ val key = Pair(type, context)
+ val existingValue = values[key]
+ if (existingValue != null) return existingValue as T
+ if (type in injectionStack) {
+ error("Found injection cycle: ${formatInjectionStack()} -> $type")
+ }
+ injectionStack.push(type)
+ val value =
+ provider.provideWithContext(this, context)
+ val cycleCheckCookie = injectionStack.pop()
+ require(cycleCheckCookie == type) { "Unbalanced stack cookie: $cycleCheckCookie != $type" }
+ values[key] = value
+ return value
} catch (ex: Exception) {
throw RuntimeException("Could not create instance for type $type (in stack ${formatInjectionStack()})", ex)
}
- val cycleCheckCookie = injectionStack.pop()
- require(cycleCheckCookie == type) { "Unbalanced stack cookie: $cycleCheckCookie != $type" }
- values[key] = value
- return value
}
fun <T : Any> provide(type: Class<T>, element: AnnotatedElement? = null): T {