commit 7c70cf81bbc115c69287476ee2c63502201bc35f Author: TheBrokenRail Date: Tue Jun 23 22:04:22 2020 -0400 Initial Commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..550b373 --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ +# gradle + +.gradle/ +build/ +out/ +classes/ + +# eclipse + +*.launch + +# idea + +.idea/ +*.iml +*.ipr +*.iws + +# vscode + +.settings/ +.vscode/ +bin/ +.classpath +.project + +# fabric + +run/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..40f7511 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,4 @@ +# Changelog + +**1.0.0** +* Initial Release \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..886b254 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 TheBrokenRail + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..70f2d61 --- /dev/null +++ b/README.md @@ -0,0 +1,37 @@ +# ModUpdater +A simple Minecraft mod updater. + +## Mod Users +Go to the Mod Menu and click the configure icon for ModUpdater. + +## Mod Developers +Place this in your ``fabric.mod.json``: + +**Maven** +```json +{ + "custom": { + "modupdater": { + "strategy": "maven", + "repository": "https://maven.fabricmc.net", + "group": "net.fabricmc.fabric-api", + "artifact": "fabric-api" + } + } +} +``` + +**CurseForge** +```json +{ + "custom": { + "modupdater": { + "strategy": "curseforge", + "projectID": 306612 + } + } +} +``` + +## Changelog +[View Changelog](CHANGELOG.md) \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..d203cac --- /dev/null +++ b/build.gradle @@ -0,0 +1,61 @@ +plugins { + id 'fabric-loom' version '0.4-SNAPSHOT' +} + +compileJava { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 +} + +version = "${project.mod_version}+${project.minecraft_version}" +group = project.maven_group as Object + +dependencies { + minecraft "com.mojang:minecraft:${project.minecraft_version}" + mappings "net.fabricmc:yarn:${project.minecraft_version}+build.${project.yarn_build}:v2" + modImplementation "net.fabricmc:fabric-loader:${project.fabric_loader_version}" + + modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_api_version}" + + modImplementation "io.github.prospector:modmenu:${project.modmenu_version}" + + implementation "com.squareup.moshi:moshi:${project.moshi_version}" + include "com.squareup.moshi:moshi:${project.moshi_version}" + + implementation "org.dom4j:dom4j:${project.dom4j_version}" + include "org.dom4j:dom4j:${project.dom4j_version}" + + compileOnly 'com.google.code.findbugs:jsr305:3.0.2' +} + +processResources { + inputs.property "version", project.version + + from(sourceSets.main.resources.srcDirs) { + include "fabric.mod.json" + expand "version": project.version + } + + from(sourceSets.main.resources.srcDirs) { + exclude "fabric.mod.json" + } +} + +// ensure that the encoding is set to UTF-8, no matter what the system default is +// this fixes some edge cases with special characters not displaying correctly +// see http://yodaconditions.net/blog/fix-for-java-file-encoding-problems-with-gradle.html +tasks.withType(JavaCompile) { + options.encoding = "UTF-8" +} + +// Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task +// if it is present. +// If you remove this task, sources will not be generated. +task sourcesJar(type: Jar, dependsOn: classes) { + classifier "sources" + from sourceSets.main.allSource +} + +jar { + from "LICENSE" +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..3fd75b2 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,17 @@ +# Done to increase the memory available to gradle. +org.gradle.jvmargs = -Xmx1G + +# Fabric Properties + minecraft_version = 1.16 + yarn_build = 1 + fabric_loader_version = 0.8.8+build.202 + +# Mod Properties + mod_version = 0.0.1 + maven_group = com.thebrokenrail + +# Dependencies + fabric_api_version = 0.13.1+build.370-1.16 + modmenu_version = 1.12.2+build.16 + moshi_version = 1.9.2 + dom4j_version = 2.1.3 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..490fda8 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..7b08593 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Mon Jun 22 19:07:49 EDT 2020 +distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStorePath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..2fe81a7 --- /dev/null +++ b/gradlew @@ -0,0 +1,183 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or 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 UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# 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"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# 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 + ;; + 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" + which java >/dev/null 2>&1 || 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 + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..62bd9b9 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,103 @@ +@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=. +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%" == "0" goto init + +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 init + +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 + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +: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 %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="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! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..731dfc2 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,12 @@ +pluginManagement { + repositories { + jcenter() + maven { + name = 'Fabric' + url = 'https://maven.fabricmc.net/' + } + gradlePluginPortal() + } +} + +rootProject.name = 'modupdater' diff --git a/src/main/java/com/thebrokenrail/modupdater/ModUpdater.java b/src/main/java/com/thebrokenrail/modupdater/ModUpdater.java new file mode 100644 index 0000000..fda3538 --- /dev/null +++ b/src/main/java/com/thebrokenrail/modupdater/ModUpdater.java @@ -0,0 +1,39 @@ +package com.thebrokenrail.modupdater; + +import com.thebrokenrail.modupdater.strategy.ModUpdateStrategies; +import com.thebrokenrail.modupdater.util.ModUpdate; +import net.fabricmc.api.ModInitializer; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +public class ModUpdater implements ModInitializer { + public static final String NAMESPACE = "modupdater"; + + private static final String LOGGER_NAME = "ModUpdater"; + + private static Logger getLogger() { + return LogManager.getLogger(LOGGER_NAME); + } + + public static void invalidModUpdaterConfig(String modID) { + getLogger().warn("Invalid JSON Configuration: " + modID); + } + + private static ModUpdate[] updates; + + public static ModUpdate[] getUpdates() { + if (updates == null) { + updates = ModUpdateStrategies.findAvailableUpdates(); + } + return updates; + } + + @Override + public void onInitialize() { + getLogger().info("Checking For Mod Updates..."); + for (ModUpdate update : getUpdates()) { + getLogger().info(update.text + " (" + update.downloadURL + ')'); + } + getLogger().info(updates.length + " Mod Update(s) Found"); + } +} diff --git a/src/main/java/com/thebrokenrail/modupdater/client/ModMenu.java b/src/main/java/com/thebrokenrail/modupdater/client/ModMenu.java new file mode 100644 index 0000000..b0ec87b --- /dev/null +++ b/src/main/java/com/thebrokenrail/modupdater/client/ModMenu.java @@ -0,0 +1,15 @@ +package com.thebrokenrail.modupdater.client; + +import com.thebrokenrail.modupdater.client.gui.ModUpdateScreen; +import io.github.prospector.modmenu.api.ConfigScreenFactory; +import io.github.prospector.modmenu.api.ModMenuApi; +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; + +@Environment(EnvType.CLIENT) +public class ModMenu implements ModMenuApi { + @Override + public ConfigScreenFactory getModConfigScreenFactory() { + return ModUpdateScreen::new; + } +} diff --git a/src/main/java/com/thebrokenrail/modupdater/client/gui/ModUpdateScreen.java b/src/main/java/com/thebrokenrail/modupdater/client/gui/ModUpdateScreen.java new file mode 100644 index 0000000..b260e73 --- /dev/null +++ b/src/main/java/com/thebrokenrail/modupdater/client/gui/ModUpdateScreen.java @@ -0,0 +1,136 @@ +package com.thebrokenrail.modupdater.client.gui; + +import com.thebrokenrail.modupdater.ModUpdater; +import com.thebrokenrail.modupdater.util.ModUpdate; +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.gui.screen.Screen; +import net.minecraft.client.gui.screen.ScreenTexts; +import net.minecraft.client.gui.widget.ButtonWidget; +import net.minecraft.client.gui.widget.EntryListWidget; +import net.minecraft.client.util.NarratorManager; +import net.minecraft.client.util.math.MatrixStack; +import net.minecraft.text.TranslatableText; +import net.minecraft.util.Util; + +@Environment(EnvType.CLIENT) +public class ModUpdateScreen extends Screen { + private ModUpdateListWidget list; + private ButtonWidget download; + private final Screen parent; + + public ModUpdateScreen(Screen parent) { + super(new TranslatableText("gui." + ModUpdater.NAMESPACE + ".title")); + this.parent = parent; + } + + @Override + protected void init() { + list = new ModUpdateListWidget(client, this); + children.add(list); + int buttonWidth = 150; + int paddingX = 5; + int doneX = width / 2 - buttonWidth - paddingX; + int downloadX = width / 2 + paddingX; + download = addButton(new ButtonWidget(downloadX, height - 38, buttonWidth, 20, new TranslatableText("gui." + ModUpdater.NAMESPACE + ".download"), buttonWidget -> { + if (list.getSelected() != null) { + Util.getOperatingSystem().open(list.getSelected().update.downloadURL); + } + })); + download.active = false; + addButton(new ButtonWidget(doneX, height - 38, buttonWidth, 20, ScreenTexts.DONE, buttonWidget -> { + assert client != null; + client.openScreen(parent); + })); + super.init(); + } + + @Override + public void render(MatrixStack matrices, int mouseX, int mouseY, float delta) { + list.render(matrices, mouseX, mouseY, delta); + drawCenteredText(matrices, textRenderer, title, width / 2, 16, 16777215); + super.render(matrices, mouseX, mouseY, delta); + } + + @Environment(EnvType.CLIENT) + private static class ModUpdateListWidget extends EntryListWidget { + private final ModUpdateScreen screen; + + private ModUpdateListWidget(MinecraftClient client, ModUpdateScreen screen) { + super(client, screen.width, screen.height, 32, screen.height - 65 + 4, 18); + this.screen = screen; + + for (ModUpdate update : ModUpdater.getUpdates()) { + addEntry(new ModUpdateEntry(update, screen, this)); + } + } + + @Override + public int getRowWidth() { + return width - 20; + } + + @Override + protected int getScrollbarPositionX() { + return super.getScrollbarPositionX() + 30; + } + + private int getWidth() { + return width; + } + + @Override + public void setSelected(ModUpdateEntry entry) { + super.setSelected(entry); + if (entry != null) { + NarratorManager.INSTANCE.narrate(new TranslatableText("narrator.select", entry.update.text).asString()); + screen.download.active = true; + } else { + screen.download.active = false; + } + } + + @Override + protected void renderBackground(MatrixStack matrixStack) { + screen.renderBackground(matrixStack); + } + + @Override + protected boolean isFocused() { + return screen.getFocused() == this; + } + } + + @Environment(EnvType.CLIENT) + private static class ModUpdateEntry extends ModUpdateListWidget.Entry { + private final ModUpdate update; + private final ModUpdateScreen screen; + private final ModUpdateListWidget parent; + + private ModUpdateEntry(ModUpdate update, ModUpdateScreen screen, ModUpdateListWidget parent) { + this.update = update; + this.screen = screen; + this.parent = parent; + } + + @Override + public void render(MatrixStack matrices, int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean hovered, float tickDelta) { + screen.textRenderer.drawWithShadow(matrices, update.text, (float) (parent.getWidth() / 2 - screen.textRenderer.getWidth(update.text) / 2), (float) (y + 1), 16777215, true); + } + + @Override + public boolean mouseClicked(double mouseX, double mouseY, int button) { + if (button == 0) { + onPressed(); + return true; + } else { + return false; + } + } + + private void onPressed() { + parent.setSelected(this); + } + } +} diff --git a/src/main/java/com/thebrokenrail/modupdater/strategy/CurseForgeStrategy.java b/src/main/java/com/thebrokenrail/modupdater/strategy/CurseForgeStrategy.java new file mode 100644 index 0000000..e621a67 --- /dev/null +++ b/src/main/java/com/thebrokenrail/modupdater/strategy/CurseForgeStrategy.java @@ -0,0 +1,93 @@ +package com.thebrokenrail.modupdater.strategy; + +import com.mojang.bridge.game.GameVersion; +import com.squareup.moshi.JsonAdapter; +import com.squareup.moshi.Moshi; +import com.thebrokenrail.modupdater.ModUpdater; +import com.thebrokenrail.modupdater.util.ConfigObject; +import com.thebrokenrail.modupdater.util.ModUpdate; +import com.thebrokenrail.modupdater.util.ModUpdateStrategy; +import com.thebrokenrail.modupdater.util.Util; +import net.fabricmc.loader.api.SemanticVersion; +import net.fabricmc.loader.util.version.VersionParsingException; + +import java.io.IOException; +import java.util.Arrays; + +class CurseForgeStrategy implements ModUpdateStrategy { + @SuppressWarnings({"unused", "MismatchedReadAndWriteOfArray"}) + private static class CurseForgeFile { + private String fileName; + private String downloadUrl; + private String[] gameVersion; + } + + @Override + public ModUpdate checkForUpdate(ConfigObject obj, String oldVersion, String name) { + int projectID; + try { + projectID = obj.getInt("projectID"); + } catch (ConfigObject.MissingValueException e) { + ModUpdater.invalidModUpdaterConfig(name); + return null; + } + + String data = Util.urlToString("https://addons-ecs.forgesvc.net/api/v2/addon/" + projectID + "/files"); + + Moshi moshi = new Moshi.Builder().build(); + JsonAdapter jsonAdapter = moshi.adapter(CurseForgeFile[].class); + + CurseForgeFile[] files; + try { + files = jsonAdapter.fromJson(data); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + + if (files == null) { + return null; + } + + String versionStr; + GameVersion version = Util.getMinecraftVersion(); + if (version.isStable()) { + versionStr = version.getName(); + } else { + versionStr = version.getReleaseTarget() + "-Snapshot"; + } + + CurseForgeFile newestFile = null; + for (CurseForgeFile file : files) { + String fileVersion = Util.getVersionFromFileName(file.fileName); + if (Arrays.asList(file.gameVersion).contains(versionStr) || Util.isVersionCompatible(fileVersion)) { + if (newestFile != null) { + String newestFileVersion = Util.getVersionFromFileName(newestFile.fileName); + try { + if (SemanticVersion.parse(fileVersion).compareTo(SemanticVersion.parse(newestFileVersion)) > 0) { + newestFile = file; + } + } catch (VersionParsingException ignored) { + } + } else { + newestFile = file; + } + } + } + + if (newestFile != null) { + String newestFileVersion = Util.getVersionFromFileName(newestFile.fileName); + try { + if (SemanticVersion.parse(newestFileVersion).compareTo(SemanticVersion.parse(oldVersion)) > 0) { + return new ModUpdate(oldVersion, newestFileVersion, newestFile.downloadUrl, name); + } else { + return null; + } + } catch (VersionParsingException e) { + return null; + } + } else { + return null; + } + } +} diff --git a/src/main/java/com/thebrokenrail/modupdater/strategy/MavenStrategy.java b/src/main/java/com/thebrokenrail/modupdater/strategy/MavenStrategy.java new file mode 100644 index 0000000..26df3bf --- /dev/null +++ b/src/main/java/com/thebrokenrail/modupdater/strategy/MavenStrategy.java @@ -0,0 +1,78 @@ +package com.thebrokenrail.modupdater.strategy; + +import com.thebrokenrail.modupdater.ModUpdater; +import com.thebrokenrail.modupdater.util.ConfigObject; +import com.thebrokenrail.modupdater.util.ModUpdate; +import com.thebrokenrail.modupdater.util.ModUpdateStrategy; +import com.thebrokenrail.modupdater.util.Util; +import net.fabricmc.loader.api.SemanticVersion; +import net.fabricmc.loader.util.version.VersionParsingException; +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.Node; +import org.dom4j.io.SAXReader; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.List; + +public class MavenStrategy implements ModUpdateStrategy { + @Override + public ModUpdate checkForUpdate(ConfigObject obj, String oldVersion, String name) { + String repository; + String group; + String artifact; + try { + repository = obj.getString("repository"); + group = obj.getString("group"); + artifact = obj.getString("artifact"); + } catch (ConfigObject.MissingValueException e) { + ModUpdater.invalidModUpdaterConfig(name); + return null; + } + + String mavenRoot = repository + '/' + group.replaceAll("\\.", "/") + '/' + artifact; + + Document doc; + try { + SAXReader reader = new SAXReader(); + doc = reader.read(new URL(mavenRoot + "/maven-metadata.xml")); + } catch (MalformedURLException | DocumentException e) { + ModUpdater.invalidModUpdaterConfig(name); + return null; + } + + List versions = doc.selectNodes("/metadata/versioning/versions/*"); + + String newestVersion = null; + for (Node node : versions) { + String version = node.getText(); + if (Util.isVersionCompatible(version)) { + if (newestVersion != null) { + try { + if (SemanticVersion.parse(version).compareTo(SemanticVersion.parse(newestVersion)) > 0) { + newestVersion = version; + } + } catch (VersionParsingException ignored) { + } + } else { + newestVersion = version; + } + } + } + + if (newestVersion != null) { + try { + if (SemanticVersion.parse(newestVersion).compareTo(SemanticVersion.parse(oldVersion)) > 0) { + return new ModUpdate(oldVersion, newestVersion, mavenRoot + '/' + newestVersion + '/' + artifact + '-' + newestVersion + Util.JAR_EXTENSION, name); + } else { + return null; + } + } catch (VersionParsingException e) { + return null; + } + } else { + return null; + } + } +} diff --git a/src/main/java/com/thebrokenrail/modupdater/strategy/ModUpdateStrategies.java b/src/main/java/com/thebrokenrail/modupdater/strategy/ModUpdateStrategies.java new file mode 100644 index 0000000..b216b06 --- /dev/null +++ b/src/main/java/com/thebrokenrail/modupdater/strategy/ModUpdateStrategies.java @@ -0,0 +1,73 @@ +package com.thebrokenrail.modupdater.strategy; + +import com.thebrokenrail.modupdater.ModUpdater; +import com.thebrokenrail.modupdater.util.ConfigObject; +import com.thebrokenrail.modupdater.util.HardcodedData; +import com.thebrokenrail.modupdater.util.ModUpdate; +import com.thebrokenrail.modupdater.util.ModUpdateStrategy; +import net.fabricmc.loader.api.FabricLoader; +import net.fabricmc.loader.api.ModContainer; +import net.fabricmc.loader.api.metadata.ModMetadata; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class ModUpdateStrategies { + private static final Map data = new HashMap<>(); + + private static ModUpdate checkForUpdate(ModMetadata metadata, ConfigObject obj, String name) { + String oldVersion = metadata.getVersion().toString(); + + String strategy; + try { + strategy = obj.getString("strategy"); + } catch (ConfigObject.MissingValueException e) { + ModUpdater.invalidModUpdaterConfig(name); + return null; + } + + ModUpdateStrategy strategyObj = data.get(strategy); + if (strategyObj == null) { + ModUpdater.invalidModUpdaterConfig(name); + return null; + } + + return strategyObj.checkForUpdate(obj, oldVersion, name); + } + + public static ModUpdate[] findAvailableUpdates() { + List updates = new ArrayList<>(); + + for (ModContainer mod : FabricLoader.getInstance().getAllMods()) { + ModMetadata metadata = mod.getMetadata(); + String name = metadata.getName() + " (" + metadata.getId() + ')'; + + ModUpdate update = null; + if (metadata.containsCustomValue(ModUpdater.NAMESPACE)) { + try { + update = checkForUpdate(metadata, new ConfigObject.ConfigObjectCustom(metadata.getCustomValue(ModUpdater.NAMESPACE).getAsObject()), name); + } catch (ClassCastException e) { + ModUpdater.invalidModUpdaterConfig(name); + } + } else { + ConfigObject obj = HardcodedData.getData(metadata.getId()); + if (obj != null) { + update = checkForUpdate(metadata, obj, name); + } + } + + if (update != null) { + updates.add(update); + } + } + + return updates.toArray(new ModUpdate[0]); + } + + static { + data.put("curseforge", new CurseForgeStrategy()); + data.put("maven", new MavenStrategy()); + } +} diff --git a/src/main/java/com/thebrokenrail/modupdater/util/ConfigObject.java b/src/main/java/com/thebrokenrail/modupdater/util/ConfigObject.java new file mode 100644 index 0000000..aaf291b --- /dev/null +++ b/src/main/java/com/thebrokenrail/modupdater/util/ConfigObject.java @@ -0,0 +1,81 @@ +package com.thebrokenrail.modupdater.util; + +import net.fabricmc.loader.api.metadata.CustomValue; + +import java.util.Map; + +public interface ConfigObject { + String getString(String str) throws MissingValueException; + int getInt(String str) throws MissingValueException; + + class ConfigObjectCustom implements ConfigObject { + private final CustomValue.CvObject obj; + + public ConfigObjectCustom(CustomValue.CvObject obj) { + this.obj = obj; + } + + @Override + public String getString(String str) throws MissingValueException { + if (obj.containsKey(str)) { + try { + return obj.get(str).getAsString(); + } catch (ClassCastException e) { + throw new MissingValueException(); + } + } else { + throw new MissingValueException(); + } + } + + @Override + public int getInt(String str) throws MissingValueException { + if (obj.containsKey(str)) { + try { + return obj.get(str).getAsNumber().intValue(); + } catch (ClassCastException e) { + throw new MissingValueException(); + } + } else { + throw new MissingValueException(); + } + } + } + + class ConfigObjectHardcoded implements ConfigObject { + private final Map map; + + public ConfigObjectHardcoded(Map map) { + this.map = map; + } + + @Override + public String getString(String str) throws MissingValueException { + if (map.containsKey(str)) { + try { + return (String) map.get(str); + } catch (ClassCastException e) { + throw new MissingValueException(); + } + } else { + throw new MissingValueException(); + } + } + + @Override + public int getInt(String str) throws MissingValueException { + if (map.containsKey(str)) { + try { + return (Integer) map.get(str); + } catch (ClassCastException e) { + throw new MissingValueException(); + } + } else { + throw new MissingValueException(); + } + } + } + + class MissingValueException extends Exception { + } +} diff --git a/src/main/java/com/thebrokenrail/modupdater/util/HardcodedData.java b/src/main/java/com/thebrokenrail/modupdater/util/HardcodedData.java new file mode 100644 index 0000000..455c713 --- /dev/null +++ b/src/main/java/com/thebrokenrail/modupdater/util/HardcodedData.java @@ -0,0 +1,19 @@ +package com.thebrokenrail.modupdater.util; + +import java.util.HashMap; +import java.util.Map; + +public class HardcodedData { + public static ConfigObject getData(String modID) { + if ("fabric".equals(modID)) { + Map map = new HashMap<>(); + map.put("strategy", "maven"); + map.put("repository", "https://maven.fabricmc.net"); + map.put("group", "net.fabricmc.fabric-api"); + map.put("artifact", "fabric-api"); + return new ConfigObject.ConfigObjectHardcoded(map); + } else { + return null; + } + } +} diff --git a/src/main/java/com/thebrokenrail/modupdater/util/ModUpdate.java b/src/main/java/com/thebrokenrail/modupdater/util/ModUpdate.java new file mode 100644 index 0000000..e3bbb90 --- /dev/null +++ b/src/main/java/com/thebrokenrail/modupdater/util/ModUpdate.java @@ -0,0 +1,22 @@ +package com.thebrokenrail.modupdater.util; + +import net.fabricmc.loader.api.Version; +import net.fabricmc.loader.util.version.VersionParsingException; + +public class ModUpdate { + public final String text; + public final String downloadURL; + + private String toFriendlyString(String version) { + try { + return Version.parse(version).getFriendlyString(); + } catch (VersionParsingException e) { + return version; + } + } + + public ModUpdate(String oldVersion, String newVersion, String downloadURL, String name) { + this.text = name + ' ' + toFriendlyString(oldVersion) + " -> " + toFriendlyString(newVersion); + this.downloadURL = downloadURL; + } +} diff --git a/src/main/java/com/thebrokenrail/modupdater/util/ModUpdateStrategy.java b/src/main/java/com/thebrokenrail/modupdater/util/ModUpdateStrategy.java new file mode 100644 index 0000000..4bdac12 --- /dev/null +++ b/src/main/java/com/thebrokenrail/modupdater/util/ModUpdateStrategy.java @@ -0,0 +1,5 @@ +package com.thebrokenrail.modupdater.util; + +public interface ModUpdateStrategy { + ModUpdate checkForUpdate(ConfigObject obj, String oldVersion, String name); +} diff --git a/src/main/java/com/thebrokenrail/modupdater/util/Util.java b/src/main/java/com/thebrokenrail/modupdater/util/Util.java new file mode 100644 index 0000000..733ab04 --- /dev/null +++ b/src/main/java/com/thebrokenrail/modupdater/util/Util.java @@ -0,0 +1,80 @@ +package com.thebrokenrail.modupdater.util; + +import com.mojang.bridge.game.GameVersion; +import net.fabricmc.loader.api.FabricLoader; +import net.fabricmc.loader.api.ModContainer; +import net.minecraft.MinecraftVersion; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.Optional; + +public class Util { + public static String urlToString(String urlStr) { + try { + StringBuilder stringBuilder = new StringBuilder(); + URL url = new URL(urlStr); + + try (BufferedReader in = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream()))) { + String line; + while ((line = in.readLine()) != null) { + stringBuilder.append(line); + stringBuilder.append('\n'); + } + } + + return stringBuilder.toString(); + } catch (IOException e) { + e.printStackTrace(); + return ""; + } + } + + public static final String JAR_EXTENSION = ".jar"; + + public static String getVersionFromFileName(String fileName) { + int index = fileName.indexOf("-"); + fileName = fileName.substring(index != -1 ? index + 1 : 0); + if (fileName.endsWith(JAR_EXTENSION)) { + fileName = fileName.substring(0, fileName.length() - JAR_EXTENSION.length()); + } + return fileName; + } + + private static String getMinecraftSemanticVersion() { + Optional mod = FabricLoader.getInstance().getModContainer("minecraft"); + if (mod.isPresent()) { + return mod.get().getMetadata().getVersion().getFriendlyString(); + } else { + return ""; + } + } + + private static String minecraftVersionSemantic = null; + private static GameVersion minecraftVersion = null; + + private static void updateMinecraftVersion() { + if (minecraftVersionSemantic == null) { + minecraftVersionSemantic = getMinecraftSemanticVersion(); + } + if (minecraftVersion == null) { + minecraftVersion = MinecraftVersion.create(); + } + } + + private static boolean isVersionCompatible(String versionStr, char prefix) { + updateMinecraftVersion(); + return versionStr.endsWith(prefix + minecraftVersionSemantic) || versionStr.endsWith(prefix + minecraftVersion.getReleaseTarget()); + } + + public static boolean isVersionCompatible(String versionStr) { + return isVersionCompatible(versionStr,'+') || isVersionCompatible(versionStr, '-'); + } + + public static GameVersion getMinecraftVersion() { + updateMinecraftVersion(); + return minecraftVersion; + } +} diff --git a/src/main/resources/assets/modupdater/icon.png b/src/main/resources/assets/modupdater/icon.png new file mode 100644 index 0000000..a26285b Binary files /dev/null and b/src/main/resources/assets/modupdater/icon.png differ diff --git a/src/main/resources/assets/modupdater/lang/en_us.json b/src/main/resources/assets/modupdater/lang/en_us.json new file mode 100644 index 0000000..c2f7218 --- /dev/null +++ b/src/main/resources/assets/modupdater/lang/en_us.json @@ -0,0 +1,4 @@ +{ + "gui.modupdater.title": "Available Mod Updates", + "gui.modupdater.download": "Download" +} \ No newline at end of file diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json new file mode 100644 index 0000000..7c08667 --- /dev/null +++ b/src/main/resources/fabric.mod.json @@ -0,0 +1,31 @@ +{ + "schemaVersion": 1, + "id": "modupdater", + "version": "${version}", + "name": "ModUpdater", + "description": "A simple Minecraft mod updater.", + "authors": [ + "TheBrokenRail" + ], + "contact": { + "homepage": "https://thebrokenrail.com/", + "sources": "https://gitea.thebrokenrail.com/TheBrokenRail/ModUpdater.git", + "issues": "https://gitea.thebrokenrail.com/TheBrokenRail/ModUpdater/issues" + }, + "icon": "assets/modupdater/icon.png", + "license": "MIT", + "environment": "*", + "entrypoints": { + "main": [ + "com.thebrokenrail.modupdater.ModUpdater" + ], + "modmenu": [ + "com.thebrokenrail.modupdater.client.ModMenu" + ] + }, + "depends": { + "fabricloader": ">=0.7.4", + "fabric": "*", + "minecraft": "1.16.x" + } +}