diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index 6edd627..0000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,47 +0,0 @@ -name: Release -on: - push: - tags: - - "v*" -jobs: - test: - runs-on: ubuntu-latest - steps: - - name: checkout repository - uses: actions/checkout@v2 - - name: validate gradle wrapper - uses: gradle/wrapper-validation-action@v1 - - name: setup jdk 17 - uses: actions/setup-java@v1 - with: - java-version: 17 - - name: make gradle wrapper executable - run: chmod +x ./gradlew - - name: create run directory - run: mkdir run - - name: test - run: ./gradlew test - - name: Publish Unit Test Results - uses: EnricoMi/publish-unit-test-result-action@v1 - if: always() - with: - files: build/test-results/**/*.xml - publish: - runs-on: ubuntu-latest - steps: - - name: checkout repository - uses: actions/checkout@v2 - - name: validate gradle wrapper - uses: gradle/wrapper-validation-action@v1 - - name: setup jdk 17 - uses: actions/setup-java@v1 - with: - java-version: 17 - - name: make gradle wrapper executable - run: chmod +x ./gradlew - - name: create run directory - run: mkdir run - - name: test - run: ./gradlew publish - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/snapshot.yml b/.github/workflows/snapshot.yml deleted file mode 100644 index 994796d..0000000 --- a/.github/workflows/snapshot.yml +++ /dev/null @@ -1,47 +0,0 @@ -name: Publish Snapshot -on: - push: - branches: - - main -jobs: - test: - runs-on: ubuntu-latest - steps: - - name: checkout repository - uses: actions/checkout@v2 - - name: validate gradle wrapper - uses: gradle/wrapper-validation-action@v1 - - name: setup jdk 17 - uses: actions/setup-java@v1 - with: - java-version: 17 - - name: make gradle wrapper executable - run: chmod +x ./gradlew - - name: create run directory - run: mkdir run - - name: test - run: ./gradlew test - - name: Publish Unit Test Results - uses: EnricoMi/publish-unit-test-result-action@v1 - if: always() - with: - files: build/test-results/**/*.xml - publish: - runs-on: ubuntu-latest - steps: - - name: checkout repository - uses: actions/checkout@v2 - - name: validate gradle wrapper - uses: gradle/wrapper-validation-action@v1 - - name: setup jdk 17 - uses: actions/setup-java@v1 - with: - java-version: 17 - - name: make gradle wrapper executable - run: chmod +x ./gradlew - - name: create run directory - run: mkdir run - - name: test - run: ./gradlew -Psnapshot publish - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..38ba51d --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,26 @@ +name: Test commit +on: [ push ] + +jobs: + test: + runs-on: ubuntu-latest + steps: + - name: checkout repository + uses: actions/checkout@v2 + - name: validate gradle wrapper + uses: gradle/wrapper-validation-action@v1 + - name: setup jdk 8 + uses: actions/setup-java@v1 + with: + java-version: 1.8 + - name: make gradle wrapper executable + run: chmod +x ./gradlew + - name: create run directory + run: mkdir run + - name: test + run: ./gradlew test + - name: Publish Unit Test Results + uses: EnricoMi/publish-unit-test-result-action@v1 + if: always() + with: + files: build/test-results/**/*.xml \ No newline at end of file diff --git a/.gitignore b/.gitignore index f6a3ab6..3dd3227 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,116 @@ -.idea +# User-specific stuff +.idea/ *.iml *.ipr *.iws -build/ -.gradle +# IntelliJ +out/ +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Compiled class file +*.class +# Log file +*.log + +# BlueJ files +*.ctxt + +# Package Files # *.jar -!gradle/wrapper/gradle-wrapper.jar \ No newline at end of file +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +# General +.DS_Store +.AppleDouble +.LSOverride + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +.gradle +build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Cache of project +.gradletasknamecache + +**/build/ + +# Common working directory +run/ +logs/ + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar diff --git a/.gitmodules b/.gitmodules index c436886..6c76836 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,3 @@ -[submodule "src/main/resources/assets/modmanager/lang"] +[submodule "translations"] path = src/main/resources/assets/modmanager/lang - url = https://github.com/ModManagerMC/translations + url = https://github.com/ModManagerMC/translations.git diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f49a4e1 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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 + + http://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. \ No newline at end of file diff --git a/Readme.md b/Readme.md new file mode 100644 index 0000000..99444fb --- /dev/null +++ b/Readme.md @@ -0,0 +1,18 @@ +# ModManager's core + +This ModManager's version independent part of code. It handles everything that's not specific to a minecraft version. + +## Development + +Clone this repo and then execute the following command to also +download the translations + +```shell +git submodule update --init --recursive +``` + +Now you can open this project in [IntelliJ IDEA](https://www.jetbrains.com/idea/) + +## License + +This mod is available under the Apache 2.0 license which you can read [here](LICENSE). \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts index 22e3ecd..2ba2ce6 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,84 +1,65 @@ -@file:Suppress("GradlePackageVersionRange") - plugins { kotlin("jvm") kotlin("plugin.serialization") - id("maven-publish") + id("fabric-loom") } -val libVersion: String by project +group = "xyz.deathsgun.modmanager" +version = "1.0-SNAPSHOT" -group = "net.modmanagermc" -version = if(project.hasProperty("snapshot")) "$libVersion-SNAPSHOT" else libVersion +java.sourceCompatibility = JavaVersion.VERSION_1_8 +java.targetCompatibility = JavaVersion.VERSION_1_8 repositories { - maven("https://maven.fabricmc.net") { - name = "Fabric" - } mavenCentral() } +val minecraftVersion: String by project +val yarnMappings: String by project val loaderVersion: String by project -val fabricKotlinVersion: String by project -val kotlinVersion: String by project + dependencies { - local("net.fabricmc:fabric-language-kotlin:${fabricKotlinVersion}") - local("net.fabricmc:fabric-loader:$loaderVersion") - local("org.apache.httpcomponents:httpclient:4.5.13") - local("org.apache.logging.log4j:log4j-api:2.17.1") - implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.4.0") + // Only for some specific code like identifiers + minecraft("com.mojang:minecraft:$minecraftVersion") + mappings("net.fabricmc:yarn:$yarnMappings:v2") + modImplementation("net.fabricmc:fabric-loader:${loaderVersion}") - testImplementation("org.apache.logging.log4j:log4j-core:2.17.1") - testImplementation("org.jetbrains.kotlin:kotlin-test:$kotlinVersion") -} + implementation(kotlin("stdlib")) + implementation(kotlin("stdlib-jdk8")) + implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.2") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.0") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.6.0") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:1.6.0") -fun DependencyHandler.local(dependencyNotation: Any) { - compileOnly(dependencyNotation) - testImplementation(dependencyNotation) + testImplementation("org.jetbrains.kotlin:kotlin-test:1.6.0") } -tasks.withType { - kotlinOptions.freeCompilerArgs += "-Xopt-in=kotlin.RequiresOptIn" +tasks.getByName("processResources") { + filesMatching("core-build.info") { + expand( + mutableMapOf( + "version" to version + ) + ) + } } -val sourcesJar by tasks.registering(Jar::class) { - archiveClassifier.set("sources") - from(sourceSets.main.get().allSource) + +//region Set target to Java 1.8 +tasks.compileKotlin { + kotlinOptions.jvmTarget = "1.8" + kotlinOptions.freeCompilerArgs += "-Xopt-in=kotlin.RequiresOptIn" } -tasks { - test { - File("run").mkdirs() - workingDir("run") - } - processResources { - filesMatching("fabric.mod.json") { - expand( - mutableMapOf( - "version" to version, - "fabricKotlinVersion" to fabricKotlinVersion, - ) - ) - } - } +tasks.compileTestKotlin { + kotlinOptions.jvmTarget = "1.8" + kotlinOptions.freeCompilerArgs += "-Xopt-in=kotlin.RequiresOptIn" } +//endregion -publishing { - repositories { - maven { - name = "GitHubPackages" - url = uri("https://maven.pkg.github.com/ModManagerMC/core") - credentials { - username = project.findProperty("gpr.user") as String? ?: System.getenv("GITHUB_ACTOR") - password = project.findProperty("gpr.key") as String? ?: System.getenv("GITHUB_TOKEN") - } - } - } - publications { - register("gpr") { - from(components["java"]) - artifact(sourcesJar.get()) - } - } +tasks.test { + useJUnitPlatform() + workingDir = File("run") + workingDir.mkdirs() } \ No newline at end of file diff --git a/gradle.properties b/gradle.properties index 22856b8..db2fa90 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,8 +1,7 @@ kotlin.code.style=official -org.gradle.jvmargs=-Xmx2G +kotlinVersion=1.6.10 -libVersion=1.0.0 - -loaderVersion=0.14.9 -fabricKotlinVersion=1.8.2+kotlin.1.7.10 -kotlinVersion=1.7.10 \ No newline at end of file +#Values from https://fabricmc.net/versions.html +minecraftVersion=1.16.5 +yarnMappings=1.16.5+build.10 +loaderVersion=0.12.12 \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 41d9927..7454180 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 41dfb87..ffed3a2 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 1b6c787..744e882 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ -#!/bin/sh +#!/usr/bin/env sh # -# Copyright © 2015-2021 the original authors. +# 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. @@ -17,101 +17,67 @@ # ############################################################################## -# -# 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/master/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/. -# +## +## Gradle start up script for UN*X +## ############################################################################## # 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 +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 - -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null APP_NAME="Gradle" -APP_BASE_NAME=${0##*/} +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 +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 ;; +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 @@ -121,9 +87,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 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 + JAVACMD="$JAVA_HOME/jre/sh/java" else - JAVACMD=$JAVA_HOME/bin/java + JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -132,7 +98,7 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD=java + 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 @@ -140,95 +106,80 @@ location of your Java installation." fi # Increase the maximum file descriptors if we can. -if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then - case $MAX_FD in #( - max*) - MAX_FD=$( ulimit -H -n ) || - warn "Could not query maximum file descriptor limit" - esac - case $MAX_FD in #( - '' | soft) :;; #( - *) - ulimit -n "$MAX_FD" || - warn "Could not set maximum file descriptor limit to $MAX_FD" - esac +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 -# 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 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" || "$msys" ; then - APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) - CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) - - JAVACMD=$( cygpath --unix "$JAVACMD" ) - +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 - 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" ) + 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 - # 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 + 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 -# Collect all arguments for the java command; -# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of -# shell script including quotes and variable substitutions, so put them in -# double quotes to make sure that they get re-expanded; and -# * put everything else in single quotes, so that it's not re-expanded. - -set -- \ - "-Dorg.gradle.appname=$APP_BASE_NAME" \ - -classpath "$CLASSPATH" \ - org.gradle.wrapper.GradleWrapperMain \ - "$@" - -# 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. -# +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` -eval "set -- $( - printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | - xargs -n1 | - sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | - tr '\n' ' ' - )" '"$@"' +# 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/settings.gradle.kts b/settings.gradle.kts index 8fd3e80..b3d0c58 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,10 +1,17 @@ pluginManagement { repositories { + maven { + name = "Fabric" + url = java.net.URI.create("https://maven.fabricmc.net/") + } gradlePluginPortal() } - val kotlinVersion: String by settings plugins { + val kotlinVersion: String by settings kotlin("jvm") version kotlinVersion kotlin("plugin.serialization") version kotlinVersion + id("fabric-loom") version "0.7-SNAPSHOT" } } +rootProject.name = "core" + diff --git a/src/main/kotlin/net/modmanagermc/core/Core.kt b/src/main/kotlin/net/modmanagermc/core/Core.kt deleted file mode 100644 index 8f04dfb..0000000 --- a/src/main/kotlin/net/modmanagermc/core/Core.kt +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2022 DeathsGun - * - * 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 - * - * http://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. - */ - -package net.modmanagermc.core - -import net.fabricmc.loader.api.FabricLoader -import net.modmanagermc.core.config.Config -import net.modmanagermc.core.di.DI -import net.modmanagermc.core.discover.IModDiscoveryService -import net.modmanagermc.core.discover.ModDiscoveryService -import net.modmanagermc.core.mod.IModService -import net.modmanagermc.core.mod.ModService -import net.modmanagermc.core.store.IStoreService -import net.modmanagermc.core.store.StoreService -import net.modmanagermc.core.update.IUpdateService -import net.modmanagermc.core.update.UpdateService - -/** - * Initializer for ModManager Core - * - * @since 1.0.0 - * @author DeathsGun - */ -object Core { - - private var initialized = false - - private lateinit var dependencyInjection: DI - - @JvmStatic - val di: DI get() = dependencyInjection - - fun init() { - if (initialized) { - throw RuntimeException("ModManager core is already initialized!") - } - dependencyInjection = DI { - bind { Config.loadConfig() } - bind { ModDiscoveryService(this) } - bind { ModService(this) } - bind { UpdateService(this) } - bind { FabricLoader.getInstance() } - bind { StoreService(this) } - } - initialized = true - } - - fun getMinecraftVersion(di: DI): String { - val loader: FabricLoader by di - return loader.getModContainer("minecraft").get().metadata.version.friendlyString - } - - fun getCoreVersion(di: DI): String { - val loader: FabricLoader by di - return loader.getModContainer("modmanager-core").get().metadata.version.friendlyString - } -} diff --git a/src/main/kotlin/net/modmanagermc/core/controller/ModInfoController.kt b/src/main/kotlin/net/modmanagermc/core/controller/ModInfoController.kt deleted file mode 100644 index 653e661..0000000 --- a/src/main/kotlin/net/modmanagermc/core/controller/ModInfoController.kt +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2022 DeathsGun - * - * 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 - * - * http://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. - */ - -package net.modmanagermc.core.controller - -import kotlinx.coroutines.* -import net.modmanagermc.core.Core -import net.modmanagermc.core.mod.IModService -import net.modmanagermc.core.mod.State -import net.modmanagermc.core.model.Mod -import net.modmanagermc.core.store.IStoreService - -class ModInfoController(var mod: Mod, private val view: View) { - - private val state: State get() = modService.getModState(mod.id) - private val modService: IModService by Core.di - private val storeService: IStoreService by Core.di - private var loading = false - - @OptIn(DelicateCoroutinesApi::class) - fun init() { - loading = true - GlobalScope.launch(Dispatchers.IO) { - delay(1500L) - if (loading) { - view.setLoading(true) - } - } - val actionText = when (state) { - State.INSTALLED, State.OUTDATED -> "modmanager.button.remove" - State.DOWNLOADABLE -> "modmanager.button.install" - } - view.updateActionText(actionText) - GlobalScope.launch(Dispatchers.IO) { - try { - mod = storeService.getMod(mod) ?: throw Exception("Unknown error") - } catch (e: Exception) { - view.error(e) - } - loading = false - view.setLoading(false) - } - } - - fun tick() { - } - - fun doAction() { - if (state == State.DOWNLOADABLE) { - modService.install(mod) - return - } - } - - interface View { - fun updateActionText(translationId: String) - fun error(e: Exception) - fun setLoading(loading: Boolean) - } - -} \ No newline at end of file diff --git a/src/main/kotlin/net/modmanagermc/core/controller/ModListController.kt b/src/main/kotlin/net/modmanagermc/core/controller/ModListController.kt deleted file mode 100644 index ec5dc28..0000000 --- a/src/main/kotlin/net/modmanagermc/core/controller/ModListController.kt +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (c) 2022 DeathsGun - * - * 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 - * - * http://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. - */ - -package net.modmanagermc.core.controller - -import kotlinx.coroutines.* -import net.modmanagermc.core.Core -import net.modmanagermc.core.model.Category -import net.modmanagermc.core.model.Mod -import net.modmanagermc.core.store.IStoreService -import net.modmanagermc.core.store.Sort - -@OptIn(DelicateCoroutinesApi::class) -class ModListController(private val view: View) { - - var scrollAmount: Double = 0.0 - private val limit = 20 - private val storeService: IStoreService by Core.di - private var page = 0 - var query: String = "" - var sorting: Sort = Sort.DOWNLOADS - var nextPageAvailable = true - var previousPageAvailable = false - var selectedCategories: List = emptyList() - var mods: List = emptyList() - var categories: MutableList = mutableListOf(Category("updatable", "modmanager.category.updatable")) - var selectedMod: Mod? = null - var loading: Boolean = false - - fun init() = GlobalScope.launch(Dispatchers.IO) { - loading = true - GlobalScope.launch(Dispatchers.Default) { - delay(1500L) - if (loading) { - view.setLoading(true) - } - } - categories.addAll(storeService.categories) - view.setCategories(categories) - search() - loading = false - view.setLoading(false) - } - - fun search() = GlobalScope.launch(Dispatchers.IO) { - loading = true - GlobalScope.launch(Dispatchers.Default) { - delay(2000L) - if (loading) { - view.setLoading(true) - } - } - try { - mods = storeService.search(query, selectedCategories, sorting, page, limit) - } catch (e: Exception) { - view.error(e) - return@launch - } - nextPageAvailable = mods.size >= limit - previousPageAvailable = page != 0 - view.setMods(mods) - view.setScrollAmount(scrollAmount) - loading = false - view.setLoading(false) - } - - fun tick() { - } - - fun close() { - } - - fun previousPage() { - page-- - if (page < 0) { - page = 0 - } - search() - } - - fun nextPage() { - page++ - search() - } - - fun reset() { - query = "" - page = 0 - sorting = Sort.RELEVANCE - nextPageAvailable = true - previousPageAvailable = false - } - - fun keyPressed(keyCode: Int, scanCode: Int, modifiers: Int): Boolean { - if (view.searchFieldFocused && keyCode == 257) { - page = 0 - view.setScrollAmount(0.0) - search() - return true - } - return false - } - - interface View { - - val searchFieldFocused: Boolean - - fun setMods(mods: List) - fun error(e: Exception) - fun setCategories(categories: List) - fun setScrollAmount(scrollAmount: Double) - fun setLoading(loading: Boolean) - - } - -} \ No newline at end of file diff --git a/src/main/kotlin/net/modmanagermc/core/controller/UpdateScreenController.kt b/src/main/kotlin/net/modmanagermc/core/controller/UpdateScreenController.kt deleted file mode 100644 index 153d6f7..0000000 --- a/src/main/kotlin/net/modmanagermc/core/controller/UpdateScreenController.kt +++ /dev/null @@ -1,47 +0,0 @@ -package net.modmanagermc.core.controller - -import kotlinx.coroutines.* -import net.fabricmc.loader.api.FabricLoader -import net.fabricmc.loader.api.metadata.ModMetadata -import net.modmanagermc.core.Core -import net.modmanagermc.core.model.Mod -import net.modmanagermc.core.update.IUpdateService -import net.modmanagermc.core.update.Update - -class UpdateScreenController(val mod: Mod, private val view: View) { - - lateinit var metadata: ModMetadata - lateinit var update: Update - private val updateService: IUpdateService by Core.di - private val fabricLoader: FabricLoader by Core.di - private var loading = false - - @OptIn(DelicateCoroutinesApi::class) - fun init() { - loading = true - GlobalScope.launch(Dispatchers.IO) { - delay(1500L) - if (loading) { - view.setLoading(true) - } - } - GlobalScope.launch(Dispatchers.IO) { - try { - update = updateService.getUpdate(mod) ?: throw Exception("Unknown error") - view.setDescription(update.version.changelog) - } catch (e: Exception) { - view.error(e) - } - metadata = fabricLoader.getModContainer(update.modId).get().metadata - loading = false - view.setLoading(false) - } - } - - interface View { - fun error(e: Exception) - fun setLoading(loading: Boolean) - fun setDescription(text: String) - } - -} diff --git a/src/main/kotlin/net/modmanagermc/core/di/DI.kt b/src/main/kotlin/net/modmanagermc/core/di/DI.kt deleted file mode 100644 index 67f94ca..0000000 --- a/src/main/kotlin/net/modmanagermc/core/di/DI.kt +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2022 DeathsGun - * - * 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 - * - * http://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. - */ - -package net.modmanagermc.core.di - -import kotlin.reflect.KProperty - -/** - * Custom DependencyInjection implementation for minecraft. - * Because we can't use things like Kodein-DI. - * - * @author DeathsGun - * @since 1.0.0 - */ -//TODO: Move to own repo -class DI(init: DI.(DI) -> Unit) { - - val instances = mutableMapOf() - - init { - init(this) - } - - inline fun bind(init: DI.(DI) -> Any) { - instances[T::class.qualifiedName!!] = init(this) - } - - inline operator fun getValue(updateService: C?, property: KProperty<*>): T { - return instances[T::class.qualifiedName] as T - } - -} \ No newline at end of file diff --git a/src/main/kotlin/net/modmanagermc/core/discover/IModDiscoveryService.kt b/src/main/kotlin/net/modmanagermc/core/discover/IModDiscoveryService.kt deleted file mode 100644 index 4997a42..0000000 --- a/src/main/kotlin/net/modmanagermc/core/discover/IModDiscoveryService.kt +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2022 DeathsGun - * - * 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 - * - * http://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. - */ - -package net.modmanagermc.core.discover - -import net.fabricmc.loader.api.FabricLoader -import net.fabricmc.loader.api.metadata.ModMetadata -import java.nio.file.Path -import java.util.StringJoiner - -/** - * This service helps to interact with - * the mod's directory. - * - * @author DeathsGun - * @see ModDiscoveryService - * @since 1.0.0 - */ -interface IModDiscoveryService { - - /** - * Returns a list of all mods which should be checked - * for updates. - * Mods which have update checking disabled are excluded. - * Additional to the java and minecraft dummy mod. - * @return a list of [ModMetadata] - */ - fun getMods(): List - - /** - * Returns the JAR of the given mod id. - * - * @return the [Path] of the JAR or null if not found - */ - fun getJar(fabricLoader: FabricLoader, modId: String): Path? - - /** - * Finds mod by the given hashes - */ - fun findJarByHashes(fabricLoader: FabricLoader, hashes: Map): Path? - fun getModMetadata(fabricLoader: FabricLoader, projectId: String): ModMetadata? - - fun setProjectIdForModId(projectId: String, modId: String) - -} \ No newline at end of file diff --git a/src/main/kotlin/net/modmanagermc/core/discover/ModDiscoveryService.kt b/src/main/kotlin/net/modmanagermc/core/discover/ModDiscoveryService.kt deleted file mode 100644 index 75d7bbd..0000000 --- a/src/main/kotlin/net/modmanagermc/core/discover/ModDiscoveryService.kt +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2022 DeathsGun - * - * 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 - * - * http://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. - */ - -package net.modmanagermc.core.discover - -import net.fabricmc.loader.api.FabricLoader -import net.fabricmc.loader.api.metadata.ModMetadata -import net.modmanagermc.core.di.DI -import net.modmanagermc.core.extensions.generateHashes -import net.modmanagermc.core.extensions.readMetadata -import net.modmanagermc.core.extensions.updatesDisabled -import java.nio.file.Files -import java.nio.file.Path -import java.util.StringJoiner -import kotlin.io.path.absolutePathString -import kotlin.io.path.extension -import kotlin.jvm.optionals.getOrDefault -import kotlin.jvm.optionals.getOrNull - -/** - * Implementation of [IModDiscoveryService] - * - * @author DeathsGun - * @since 1.0.0 - */ -internal class ModDiscoveryService(di: DI) : IModDiscoveryService { - - private val fabricLoader: FabricLoader by di - private val blocked = listOf("minecraft", "java") - private val projectIdModIs = mutableMapOf() - private val modIdJars = mutableMapOf() - private val hashJars = mutableMapOf() - - override fun getMods(): List { - return fabricLoader.allMods.map { it.metadata } - .filter { - !it.updatesDisabled() && !blocked.contains(it.id) && - !it.containsCustomValue("fabric-api:module-lifecycle") && - !it.containsCustomValue("fabric-loom:generated") - } - } - - override fun getJar(fabricLoader: FabricLoader, modId: String): Path? { - if (modIdJars.containsKey(modId)) { - return Path.of(modIdJars[modId]!!) - } - val files = - Files.walk(fabricLoader.gameDir.resolve("mods")).filter { "jar".equals(it.extension, true) } - files.forEach { - val metadata = it.readMetadata(fabricLoader) ?: return@forEach - modIdJars[metadata.id] = it.absolutePathString() - } - val path = modIdJars[modId] ?: return null - return Path.of(path) - } - - override fun findJarByHashes(fabricLoader: FabricLoader, hashes: Map): Path? { - for ((key, value) in hashJars) { - if (hashes.containsValue(key)) { - return Path.of(value) - } - } - val files = Files.walk(fabricLoader.gameDir.resolve("mods")).filter { "jar".equals(it.extension, true) } - files.forEach { path -> - path.generateHashes().forEach { - hashJars[it.value] = path.absolutePathString() - } - } - for ((key, value) in hashJars) { - if (hashes.containsValue(key)) { - return Path.of(value) - } - } - return null - } - - @OptIn(ExperimentalStdlibApi::class) - override fun getModMetadata(fabricLoader: FabricLoader, projectId: String): ModMetadata? { - val modId = projectIdModIs[projectId] ?: return null - return fabricLoader.getModContainer(modId).getOrNull()?.metadata - } - - override fun setProjectIdForModId(projectId: String, modId: String) { - projectIdModIs[projectId] = modId - } - -} \ No newline at end of file diff --git a/src/main/kotlin/net/modmanagermc/core/exceptions/ModManagerException.kt b/src/main/kotlin/net/modmanagermc/core/exceptions/ModManagerException.kt deleted file mode 100644 index 93b808f..0000000 --- a/src/main/kotlin/net/modmanagermc/core/exceptions/ModManagerException.kt +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (c) 2022 DeathsGun - * - * 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 - * - * http://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. - */ - -package net.modmanagermc.core.exceptions - -open class ModManagerException(val translationId: String, vararg val args: Any) : Exception() \ No newline at end of file diff --git a/src/main/kotlin/net/modmanagermc/core/extensions/ModMetadataExtensions.kt b/src/main/kotlin/net/modmanagermc/core/extensions/ModMetadataExtensions.kt deleted file mode 100644 index 7a9c178..0000000 --- a/src/main/kotlin/net/modmanagermc/core/extensions/ModMetadataExtensions.kt +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2022 DeathsGun - * - * 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 - * - * http://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. - */ - -package net.modmanagermc.core.extensions - -import net.fabricmc.loader.api.metadata.ModMetadata - -/** - * Extracts the update provider from `modmanager` custom space in `fabric.mod.json` - * - * @author DeathsGun - * @since 1.0.0 - */ -fun ModMetadata.getUpdateProvider(): Map { - val providers = mutableMapOf() - if (!containsCustomValue("modmanager")) { - providers["modrinth"] = "" - return providers - } - getCustomValue("modmanager").asObject.forEach { - if (it.key != "disable-checking") { - return@forEach - } - providers[it.key] = it.value.asString - } - if (providers.isEmpty()) { - providers["modrinth"] = "" - } - return providers -} - -/** - * Checks for the disable-checking in `modmanager` custom space in `fabric.mod.json` - * - * @author DeathsGun - * @since 1.0.0 - */ -fun ModMetadata.updatesDisabled(): Boolean { - if (!this.containsCustomValue("modmanager")) { - return false - } - val modmanager = this.getCustomValue("modmanager").asObject - return modmanager.containsKey("disable-checking") && modmanager.get("disable-checking").asBoolean -} diff --git a/src/main/kotlin/net/modmanagermc/core/extensions/PathExtensions.kt b/src/main/kotlin/net/modmanagermc/core/extensions/PathExtensions.kt deleted file mode 100644 index c23cad1..0000000 --- a/src/main/kotlin/net/modmanagermc/core/extensions/PathExtensions.kt +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2022 DeathsGun - * - * 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 - * - * http://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. - */ - -package net.modmanagermc.core.extensions - -import net.fabricmc.loader.api.FabricLoader -import net.fabricmc.loader.api.metadata.ModMetadata -import net.fabricmc.loader.impl.metadata.DependencyOverrides -import net.fabricmc.loader.impl.metadata.ModMetadataParser -import net.fabricmc.loader.impl.metadata.VersionOverrides -import java.nio.file.Path -import java.security.MessageDigest -import java.util.jar.JarFile -import kotlin.io.path.absolutePathString -import kotlin.io.path.isDirectory -import kotlin.io.path.readBytes - -val hashes = listOf("SHA-1", "SHA-512", "MD5") - -/** - * Opens the file as a JAR and reads the fabric.mod.json from it - * @return [ModMetadata] if not found or else null - * - * @author DeathsGun - * @since 1.0.0 - */ -fun Path.readMetadata(fabricLoader: FabricLoader): ModMetadata? { - try { - val jar = JarFile(this.toFile()) - val entry = jar.getJarEntry("fabric.mod.json") ?: return null - jar.getInputStream(entry).use { - return ModMetadataParser.parseMetadata( - it, - this.absolutePathString(), - emptyList(), - VersionOverrides(), - DependencyOverrides(fabricLoader.configDir) - ) - } - } catch (_: Exception) { - } - return null -} - -/** - * Hashes the file using the algorithms declared in [hashes]. - * - * @author DeathsGun - * @since 1.0.0 - * @return A map of the hashes or if the path is a directory an empty map - */ -fun Path.generateHashes(): Map { - if (this.isDirectory()) { - return emptyMap() - } - val map = mutableMapOf() - for (hash in hashes) { - map[hash] = hash(hash) - } - return map -} - -/** - * Hashes the path using the provided algorithm - * - * @param algorithm the hashing algorithm - */ -fun Path.hash(algorithm: String): String { - return MessageDigest.getInstance(algorithm).digest(readBytes()) - .joinToString("") { - "%02x".format(it) - } -} diff --git a/src/main/kotlin/net/modmanagermc/core/mod/IModService.kt b/src/main/kotlin/net/modmanagermc/core/mod/IModService.kt deleted file mode 100644 index 09c6184..0000000 --- a/src/main/kotlin/net/modmanagermc/core/mod/IModService.kt +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2022 DeathsGun - * - * 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 - * - * http://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. - */ - -package net.modmanagermc.core.mod - -import net.modmanagermc.core.model.JarFileInfo -import net.modmanagermc.core.model.Mod -import net.modmanagermc.core.model.Version -import net.modmanagermc.core.update.IUpdateProvider -import net.modmanagermc.core.update.Update - -/** - * @author DeathsGun - * @since 1.0.0 - */ -interface IModService { - - val providers: List - - suspend fun createJarFileInfo(): List - - fun getNewerVersions(fileInfo: JarFileInfo): List - - fun registerProvider(provider: IUpdateProvider) - - fun getModState(modId: String): State - - fun install(mod: Mod) - - fun installVersion(version: Version) - - fun removeMod(modId: String) - fun update(update: Update) -} \ No newline at end of file diff --git a/src/main/kotlin/net/modmanagermc/core/mod/ModService.kt b/src/main/kotlin/net/modmanagermc/core/mod/ModService.kt deleted file mode 100644 index 122dba2..0000000 --- a/src/main/kotlin/net/modmanagermc/core/mod/ModService.kt +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Copyright (c) 2022 DeathsGun - * - * 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 - * - * http://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. - */ - -package net.modmanagermc.core.mod - -import kotlinx.serialization.ExperimentalSerializationApi -import kotlinx.serialization.json.Json -import kotlinx.serialization.json.decodeFromStream -import net.fabricmc.loader.api.FabricLoader -import net.fabricmc.loader.api.SemanticVersion -import net.modmanagermc.core.Core -import net.modmanagermc.core.config.Config -import net.modmanagermc.core.di.DI -import net.modmanagermc.core.discover.IModDiscoveryService -import net.modmanagermc.core.exceptions.ModManagerException -import net.modmanagermc.core.extensions.generateHashes -import net.modmanagermc.core.extensions.getUpdateProvider -import net.modmanagermc.core.model.Dependency -import net.modmanagermc.core.model.JarFileInfo -import net.modmanagermc.core.model.Mod -import net.modmanagermc.core.model.Version -import net.modmanagermc.core.update.IUpdateProvider -import net.modmanagermc.core.update.Update -import net.modmanagermc.core.update.provider.modrinth.Modrinth -import net.modmanagermc.core.update.provider.modrinth.model.ErrorResponse -import org.apache.http.client.methods.HttpGet -import org.apache.http.impl.client.HttpClients -import org.apache.http.util.EntityUtils -import org.apache.logging.log4j.LogManager -import java.nio.file.Files -import java.nio.file.Path -import java.util.* -import kotlin.io.path.absolutePathString -import kotlin.io.path.deleteIfExists -import kotlin.io.path.exists - -@OptIn(ExperimentalSerializationApi::class) -internal class ModService(val di: DI) : IModService { - - private val config: Config by di - private val fabricLoader: FabricLoader by di - private val logger = LogManager.getLogger(ModService::class.java) - private val providerList: MutableList = mutableListOf(Modrinth(di)) - override val providers: List get() = providerList - private val discoveryService: IModDiscoveryService by di - private val modStates = mutableMapOf() - private val client = HttpClients.createDefault() - private val json = Json { - ignoreUnknownKeys = true - } - - override suspend fun createJarFileInfo(): List { - val mods = discoveryService.getMods() - logger.info("Processing {} mods", mods.size) - val modInfos = ArrayList() - for (mod in mods) { - val path = discoveryService.getJar(fabricLoader, mod.id) - if (path == null) { - logger.debug( - "Skipping update check for {} because it has no jar in {}", - mod.id, - fabricLoader.gameDir.resolve("mods") - ) - continue - } - logger.debug("Adding {} to update check", mod.id) - modInfos.add( - JarFileInfo( - mod.id, - mod.version.friendlyString, - mod.getUpdateProvider(), - path.generateHashes() - ) - ) - } - logger.info("Processed {} mods {} can be used", mods.size, modInfos.size) - return modInfos - } - - override fun getNewerVersions(fileInfo: JarFileInfo): List { - val versions = mutableListOf() - for (providerName in fileInfo.provider.keys) { - val provider = providers.find { it.name == providerName } - if (provider == null) { - logger.warn("Mod ${fileInfo.modId} requested provider $providerName but it's not available") - continue - } - val version = provider.getVersion(fileInfo) ?: continue - discoveryService.setProjectIdForModId(version.providerModId, fileInfo.modId) - if (Objects.equals(version.hashes["sha512"], fileInfo.hashes["SHA-512"])) { - modStates[version.providerModId] = State.INSTALLED - modStates[fileInfo.modId] = State.INSTALLED - continue - } - modStates[version.providerModId] = State.OUTDATED - modStates[fileInfo.modId] = State.OUTDATED - versions.add(version); - } - return versions - } - - override fun registerProvider(provider: IUpdateProvider) { - logger.debug("Registering provider ${provider.name}") - this.providerList.add(provider) - } - - override fun getModState(modId: String): State { - return modStates.getOrDefault(modId, State.DOWNLOADABLE) - } - - override fun install(mod: Mod) { - val provider = providerList.find { it.name == mod.provider } ?: return - val version = provider.getLatestVersion(mod.id) ?: return - installVersion(version) - } - - override fun installVersion(version: Version) { - val path = fabricLoader.gameDir.resolve("mods").resolve(version.id) // Store all relevant files in one dir - try { - Files.createDirectories(path) - } catch (e: Exception) { - throw ModManagerException("modmanager.error.install.directory", e.message!!) - } - val files = resolve(version.dependencies) - files[version.filename] = version.downloadUrl - for ((key, value) in files) { - download(value, path.resolve(key)) - } - } - - private fun resolve(dependencies: List): MutableMap { - val files = mutableMapOf() - for (dependency in dependencies) { - if (!dependency.required) { - continue // Ignore optional dependencies - } - val jar = discoveryService.findJarByHashes(fabricLoader, dependency.hashes) - if (jar != null) { - continue // Already installed - } - val metadata = discoveryService.getModMetadata(fabricLoader, dependency.projectId) - if (metadata != null) { // Maybe there is a newer version installed - val ver = net.fabricmc.loader.api.Version.parse(dependency.version) - if (ver is SemanticVersion) { - if (metadata.version > ver) { - continue // Dependency is newer - } - } - } - files[dependency.filename] = dependency.downloadUrl - if (files.isEmpty()) { - continue - } - files.putAll(resolve(dependency.dependencies)) - } - return files - } - - private fun download(url: String, path: Path) { - val request = HttpGet(url) - request.setHeader("User-Agent", "ModManager-Core ${Core.getCoreVersion(di)}") - - val resp = client.execute(request) - if (resp.statusLine.statusCode != 200) { - val error = json.decodeFromStream(resp.entity.content) - EntityUtils.consume(resp.entity) - throw error.toException("Received invalid status code ${resp.statusLine.statusCode}.") - } - val output = Files.newOutputStream(path) - resp.entity.writeTo(output) - } - - override fun update(update: Update) { - installVersion(update.version) - removeMod(update.modId) - } - - override fun removeMod(modId: String) { - val jar = - discoveryService.getJar(fabricLoader, modId) ?: throw ModManagerException("modmanager.error.jar.notFound") - jar.deleteIfExists() - if (jar.exists()) { - config.remove.add(jar.absolutePathString()) - config.save() - } - } - -} \ No newline at end of file diff --git a/src/main/kotlin/net/modmanagermc/core/mod/State.kt b/src/main/kotlin/net/modmanagermc/core/mod/State.kt deleted file mode 100644 index 3b33439..0000000 --- a/src/main/kotlin/net/modmanagermc/core/mod/State.kt +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2022 DeathsGun - * - * 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 - * - * http://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. - */ - -package net.modmanagermc.core.mod - -enum class State { - INSTALLED, OUTDATED, DOWNLOADABLE; -} \ No newline at end of file diff --git a/src/main/kotlin/net/modmanagermc/core/model/Dependency.kt b/src/main/kotlin/net/modmanagermc/core/model/Dependency.kt deleted file mode 100644 index 787df98..0000000 --- a/src/main/kotlin/net/modmanagermc/core/model/Dependency.kt +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2022 DeathsGun - * - * 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 - * - * http://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. - */ - -package net.modmanagermc.core.model - -/** - * A dependency for a mod which can also have dependencies - * - * @author DeathsGun - * @since 1.0.0 - */ -data class Dependency( - val projectId: String, - val version: String, - val downloadUrl: String, - val filename: String, - val required: Boolean, - val hashes: Map, - val dependencies: List -) diff --git a/src/main/kotlin/net/modmanagermc/core/model/JarFileInfo.kt b/src/main/kotlin/net/modmanagermc/core/model/JarFileInfo.kt deleted file mode 100644 index 2fc59de..0000000 --- a/src/main/kotlin/net/modmanagermc/core/model/JarFileInfo.kt +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2022 DeathsGun - * - * 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 - * - * http://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. - */ - -package net.modmanagermc.core.model - -/** - * Extracted info about a mod - * - * @author DeathsGun - * @since 1.0.0 - */ -data class JarFileInfo( - val modId: String, - val version: String, - val provider: Map, - val hashes: Map -) diff --git a/src/main/kotlin/net/modmanagermc/core/model/ProcessingStatus.kt b/src/main/kotlin/net/modmanagermc/core/model/ProcessingStatus.kt deleted file mode 100644 index 586ba26..0000000 --- a/src/main/kotlin/net/modmanagermc/core/model/ProcessingStatus.kt +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2022 DeathsGun - * - * 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 - * - * http://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. - */ - -package net.modmanagermc.core.model - -enum class ProcessingStatus { - PENDING, DONE, -} \ No newline at end of file diff --git a/src/main/kotlin/net/modmanagermc/core/model/Version.kt b/src/main/kotlin/net/modmanagermc/core/model/Version.kt deleted file mode 100644 index 80480d7..0000000 --- a/src/main/kotlin/net/modmanagermc/core/model/Version.kt +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2022 DeathsGun - * - * 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 - * - * http://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. - */ - -package net.modmanagermc.core.model - -/** - * A representation of a basic version - * - * @author DeathsGun - * @since 1.0.0 - */ -data class Version( - /** - * The id of the version **not** the mod id - */ - val id: String, - /** - * Provider specific id for the mod - */ - val providerModId: String, - val provider: String, - val version: String, - val changelog: String, - /** - * A list of dependencies for the mod - */ - val dependencies: List, - val filename: String, - val downloadUrl: String, - val hashes: Map, -) diff --git a/src/main/kotlin/net/modmanagermc/core/store/IStore.kt b/src/main/kotlin/net/modmanagermc/core/store/IStore.kt deleted file mode 100644 index 89b663b..0000000 --- a/src/main/kotlin/net/modmanagermc/core/store/IStore.kt +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2022 DeathsGun - * - * 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 - * - * http://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. - */ - -package net.modmanagermc.core.store - -import net.modmanagermc.core.model.Category -import net.modmanagermc.core.model.Mod - -/** - * Provides info about categories and mods - * - * @since 1.0.0 - * @author DeathsGun - */ -interface IStore { - - val name: String - - fun search( - query: String, - categories: List, - sort: Sort, - page: Int, - limit: Int - ): List - - fun getCategories(): List - fun getMod(mod: Mod): Mod? - - fun getMod(mod: String): Mod? - - fun getLicences(): Map - -} \ No newline at end of file diff --git a/src/main/kotlin/net/modmanagermc/core/store/IStoreService.kt b/src/main/kotlin/net/modmanagermc/core/store/IStoreService.kt deleted file mode 100644 index 998f8af..0000000 --- a/src/main/kotlin/net/modmanagermc/core/store/IStoreService.kt +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2022 DeathsGun - * - * 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 - * - * http://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. - */ - -package net.modmanagermc.core.store - -import net.modmanagermc.core.model.Category -import net.modmanagermc.core.model.Mod -import java.util.StringJoiner - -interface IStoreService { - - var store: String - val categories: List - val licenses: Map - - fun search( - query: String, - categories: List = emptyList(), - sort: Sort, - page: Int, - limit: Int - ): List - - fun getMod(mod: Mod): Mod? - -} diff --git a/src/main/kotlin/net/modmanagermc/core/store/StoreService.kt b/src/main/kotlin/net/modmanagermc/core/store/StoreService.kt deleted file mode 100644 index 8d307df..0000000 --- a/src/main/kotlin/net/modmanagermc/core/store/StoreService.kt +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2022 DeathsGun - * - * 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 - * - * http://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. - */ - -package net.modmanagermc.core.store - -import net.modmanagermc.core.di.DI -import net.modmanagermc.core.model.Category -import net.modmanagermc.core.model.Mod -import net.modmanagermc.core.store.provider.modrinth.Modrinth -import net.modmanagermc.core.update.IUpdateService -import net.modmanagermc.core.update.Update -import org.apache.logging.log4j.LogManager - -internal class StoreService(di: DI) : IStoreService { - - // Store to use - override var store: String = "modrinth" - - // Cache stores - private val logger = LogManager.getLogger("ModManager|StoreService") - private val _categories: MutableMap> = mutableMapOf() - private val stores: MutableList = mutableListOf(Modrinth(di)) - private val modCache: MutableMap> = mutableMapOf() - override val licenses: Map - private val updateService: IUpdateService by di - - init { - licenses = getStore()?.getLicences() ?: emptyMap() - } - - override val categories: List - get() { - var cate = _categories.getOrDefault(store, emptyList()) - if (cate.isNotEmpty()) { - return cate - } - val store = getStore() ?: return emptyList() - cate = store.getCategories() - _categories[store.name] = cate - return cate - } - - override fun search(query: String, categories: List, sort: Sort, page: Int, limit: Int): List { - if (categories.any { it.id == "updatable" }) { - return searchUpdates(query, categories, sort, page, limit) - } - val store = getStore() ?: return emptyList() - val id = searchId(query, categories, sort, page, limit) - var mods = modCache.getOrDefault(id, emptyList()) - if (mods.isEmpty()) { - mods = store.search(query, categories, sort, page, limit) - modCache[id] = mods - } - return mods - } - - private fun searchUpdates(query: String, categories: List, sort: Sort, page: Int, limit: Int): List { - val searchId = searchId(query, categories, sort, page, limit) - var mods = modCache.getOrDefault(searchId, emptyList()) - - if (mods.isEmpty()) { - mods = updateService.updates.mapNotNull { getInfo(it) } - modCache[searchId] = mods - } - return mods - } - - private fun getInfo(update: Update): Mod? { - val store = stores.find { update.storeIds.containsKey(it.name) } - if (store == null) { - logger.warn("Couldn't find any store for \"{}\"", update.modId) - return null - } - return store.getMod(update.storeIds[store.name]!!) - } - - override fun getMod(mod: Mod): Mod? { - return getStore()?.getMod(mod) - } - - private fun getStore(): IStore? { - return stores.find { it.name == store } - } - - private fun searchId(query: String, categories: List, sort: Sort, page: Int, limit: Int): String { - return "${query}|${categories.joinToString(".")}|${sort}|${page}|${limit}" - } - -} \ No newline at end of file diff --git a/src/main/kotlin/net/modmanagermc/core/store/provider/modrinth/Modrinth.kt b/src/main/kotlin/net/modmanagermc/core/store/provider/modrinth/Modrinth.kt deleted file mode 100644 index 26c3961..0000000 --- a/src/main/kotlin/net/modmanagermc/core/store/provider/modrinth/Modrinth.kt +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (c) 2022 DeathsGun - * - * 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 - * - * http://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. - */ - -package net.modmanagermc.core.store.provider.modrinth - -import kotlinx.serialization.ExperimentalSerializationApi -import kotlinx.serialization.decodeFromString -import kotlinx.serialization.json.Json -import kotlinx.serialization.json.decodeFromStream -import net.modmanagermc.core.Core -import net.modmanagermc.core.di.DI -import net.modmanagermc.core.exceptions.ModManagerException -import net.modmanagermc.core.model.Category -import net.modmanagermc.core.model.Mod -import net.modmanagermc.core.store.IStore -import net.modmanagermc.core.store.IStoreService -import net.modmanagermc.core.store.Sort -import net.modmanagermc.core.store.provider.modrinth.models.LicenseModel -import net.modmanagermc.core.store.provider.modrinth.models.SearchResponse -import org.apache.http.client.methods.HttpGet -import org.apache.http.client.utils.URIBuilder -import org.apache.http.impl.client.HttpClients -import org.apache.http.util.EntityUtils - -@OptIn(ExperimentalSerializationApi::class) -class Modrinth(val di: DI) : IStore { - - private val storeService: IStoreService by di - private val uri = "https://api.modrinth.com/v2" - private val client = HttpClients.createDefault() - private val json = Json { - ignoreUnknownKeys = true - } - - override val name: String = "modrinth" - - override fun search(query: String, categories: List, sort: Sort, page: Int, limit: Int): List { - val uri = URIBuilder("${uri}/search").apply { - addParameter("query", query) - addParameter("offset", "${page * limit}") - addParameter("limit", "$limit") - addParameter("index", sort.toModrinth()) - addParameter("facets", buildFacets(categories)) - } - val request = HttpGet(uri.build()) - request.setHeader("Accept", "application/json") - request.setHeader("User-Agent", "ModManager-Core ${Core.getCoreVersion(di)}") - val response = client.execute(request) - - if (response.statusLine.statusCode != 200) { - EntityUtils.consume(response.entity) - throw ModManagerException("modmanager.error.status", response.statusLine.statusCode) - } - - val searchResponse = json.decodeFromStream(response.entity.content) - EntityUtils.consume(response.entity) - return searchResponse.hits.map { it.toMod(storeService.licenses) } - } - - private fun buildFacets(categories: List): String { - var result = - "[[\"categories:fabric\"],[\"versions:${Core.getMinecraftVersion(Core.di)}\"],[\"project_type:mod\"]" - for (category in categories) { - result += ",[\"categories:${category.id}\"]" - } - return "$result]" - } - - override fun getLicences(): Map { - val request = HttpGet("${uri}/tag/license") - request.setHeader("Accept", "application/json") - request.setHeader("User-Agent", "ModManager-Core ${Core.getCoreVersion(di)}") - - val response = client.execute(request) - - if (response.statusLine.statusCode != 200) { - EntityUtils.consume(response.entity) - throw ModManagerException("modmanager.error.status", response.statusLine.statusCode) - } - val licenses = json.decodeFromStream>(response.entity.content) - return licenses.associate { it.short!! to it.name } - } - - override fun getCategories(): List { - val request = HttpGet("${uri}/tag/category") - request.addHeader("Accept", "application/json") - request.setHeader("User-Agent", "ModManager-Core ${Core.getCoreVersion(di)}") - val response = client.execute(request) - if (response.statusLine.statusCode != 200) { - EntityUtils.consume(response.entity) - throw ModManagerException("modmanager.error.status", response.statusLine.statusCode) - } - val categories = - json.decodeFromStream>(response.entity.content) - EntityUtils.consume(response.entity) - return categories.filter { it.projectType == "mod" }.map { it.toCategory() } - } - - override fun getMod(mod: Mod): Mod { - return getMod(mod.id) - } - - override fun getMod(mod: String): Mod { - val request = HttpGet("${uri}/project/${mod}") - request.setHeader("Accept", "application/json") - request.setHeader("User-Agent", "ModManager-Core ${Core.getCoreVersion(di)}") - val response = client.execute(request) - if (response.statusLine.statusCode != 200) { - EntityUtils.consume(response.entity) - throw ModManagerException("modmanager.error.status", response.statusLine.statusCode) - } - val m = json.decodeFromStream(response.entity.content) - EntityUtils.consume(response.entity) - return m.toMod() - } - - private fun Sort.toModrinth(): String { - return name.lowercase() - } - -} \ No newline at end of file diff --git a/src/main/kotlin/net/modmanagermc/core/store/provider/modrinth/models/Mod.kt b/src/main/kotlin/net/modmanagermc/core/store/provider/modrinth/models/Mod.kt deleted file mode 100644 index 62bfeb3..0000000 --- a/src/main/kotlin/net/modmanagermc/core/store/provider/modrinth/models/Mod.kt +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2022 DeathsGun - * - * 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 - * - * http://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. - */ - -package net.modmanagermc.core.store.provider.modrinth.models - -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable -import net.modmanagermc.core.model.Category - -@Serializable -data class Mod( - val title: String, - val description: String, - val downloads: Int, - @SerialName("icon_url") - val iconUrl: String, - @SerialName("id") - val projectId: String, - val license: LicenseModel, - val categories: List, - val body: String? = null -) { - - private val blacklisted = listOf("fabric", "quilt", "forge") - - fun toMod(): net.modmanagermc.core.model.Mod { - return net.modmanagermc.core.model.Mod( - projectId, - "modrinth", - title, - iconUrl, - description, - license.name, - categories.filter { !blacklisted.contains(it) }.map { Category(it, "modmanager.category.$it") }, - body - ) - } -} \ No newline at end of file diff --git a/src/main/kotlin/net/modmanagermc/core/store/provider/modrinth/models/SearchMod.kt b/src/main/kotlin/net/modmanagermc/core/store/provider/modrinth/models/SearchMod.kt deleted file mode 100644 index 107c63b..0000000 --- a/src/main/kotlin/net/modmanagermc/core/store/provider/modrinth/models/SearchMod.kt +++ /dev/null @@ -1,35 +0,0 @@ -package net.modmanagermc.core.store.provider.modrinth.models - -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable -import net.modmanagermc.core.model.Category - -@Serializable -data class SearchMod( - val title: String, - val description: String, - val downloads: Int, - @SerialName("icon_url") - val iconUrl: String, - @SerialName("project_id") - val projectId: String, - val license: String, - val categories: List, - val body: String? = null -) { - - private val blacklisted = listOf("fabric", "quilt", "forge") - - fun toMod(licenses: Map): net.modmanagermc.core.model.Mod { - return net.modmanagermc.core.model.Mod( - projectId, - "modrinth", - title, - iconUrl, - description, - licenses.getOrDefault(license, license.uppercase()), - categories.filter { !blacklisted.contains(it) }.map { Category(it, "modmanager.category.$it") }, - body - ) - } -} \ No newline at end of file diff --git a/src/main/kotlin/net/modmanagermc/core/update/IUpdateProvider.kt b/src/main/kotlin/net/modmanagermc/core/update/IUpdateProvider.kt deleted file mode 100644 index 4cc6a83..0000000 --- a/src/main/kotlin/net/modmanagermc/core/update/IUpdateProvider.kt +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2022 DeathsGun - * - * 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 - * - * http://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. - */ - -package net.modmanagermc.core.update - -import net.modmanagermc.core.model.JarFileInfo -import net.modmanagermc.core.model.Version - -/** - * Provides versions for a mod by using [JarFileInfo] - * - * @since 1.0.0 - * @author DeathsGun - */ -interface IUpdateProvider { - - val name: String - - fun getVersion(fileInfo: JarFileInfo): Version? - - fun getLatestVersion(projectId: String): Version? - -} \ No newline at end of file diff --git a/src/main/kotlin/net/modmanagermc/core/update/IUpdateService.kt b/src/main/kotlin/net/modmanagermc/core/update/IUpdateService.kt deleted file mode 100644 index 0843dcb..0000000 --- a/src/main/kotlin/net/modmanagermc/core/update/IUpdateService.kt +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2022 DeathsGun - * - * 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 - * - * http://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. - */ - -package net.modmanagermc.core.update - -import net.modmanagermc.core.model.Mod -import net.modmanagermc.core.model.ProcessingStatus -import net.modmanagermc.core.model.Version - -/** - * Processes the installed mods and sends them to - * the ModManager backend. - * - * @since 1.0.0 - * @author DeathsGun - */ -interface IUpdateService { - - val processingStatus: ProcessingStatus - val updates: List - - fun checkUpdate() - fun getUpdate(mod: Mod): Update? - -} \ No newline at end of file diff --git a/src/main/kotlin/net/modmanagermc/core/update/Update.kt b/src/main/kotlin/net/modmanagermc/core/update/Update.kt deleted file mode 100644 index c0350ff..0000000 --- a/src/main/kotlin/net/modmanagermc/core/update/Update.kt +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2022 DeathsGun - * - * 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 - * - * http://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. - */ - -package net.modmanagermc.core.update - -import net.modmanagermc.core.model.Version - -data class Update( - val modId: String, - val storeIds: Map, - val version: Version -) diff --git a/src/main/kotlin/net/modmanagermc/core/update/UpdateService.kt b/src/main/kotlin/net/modmanagermc/core/update/UpdateService.kt deleted file mode 100644 index ab3fd86..0000000 --- a/src/main/kotlin/net/modmanagermc/core/update/UpdateService.kt +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2022 DeathsGun - * - * 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 - * - * http://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. - */ - -package net.modmanagermc.core.update - -import kotlinx.coroutines.DelicateCoroutinesApi -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import net.modmanagermc.core.di.DI -import net.modmanagermc.core.mod.IModService -import net.modmanagermc.core.model.JarFileInfo -import net.modmanagermc.core.model.Mod -import net.modmanagermc.core.model.ProcessingStatus -import net.modmanagermc.core.model.Version -import org.apache.logging.log4j.LogManager - -@OptIn(DelicateCoroutinesApi::class) -internal class UpdateService(di: DI) : IUpdateService { - - private val modService: IModService by di - private val logger = LogManager.getLogger("ModManager|UpdateService") - private var status: ProcessingStatus = ProcessingStatus.PENDING - private val _updates: MutableList = mutableListOf() - - override val processingStatus: ProcessingStatus - get() { - return status - } - override val updates: List - get() = _updates - - override fun checkUpdate() { - logger.info("Checking for updates...") - GlobalScope.launch(Dispatchers.IO) { - val modInfos = modService.createJarFileInfo() - if (modInfos.isEmpty()) { - logger.info("Skipping update check because 0 mods could be checked!") - return@launch - } - for (fileInfo in modInfos) { - try { - checkUpdate(fileInfo) - } catch (e: Exception) { - logger.error("Failed to check for updates for mod '{}': {}", fileInfo.modId, e) - } - } - status = ProcessingStatus.DONE - } - } - - override fun getUpdate(mod: Mod): Update? { - return updates.find { it.storeIds.containsValue(mod.id) } - } - - private fun checkUpdate(fileInfo: JarFileInfo) { - val versions = modService.getNewerVersions(fileInfo) - if (versions.isEmpty()) { - logger.info("No updates for {} found", fileInfo.modId) - return - } - val storeIds = mutableMapOf(versions[0].provider to versions[0].providerModId) - val update = Update(fileInfo.modId, storeIds, versions[0]) - logger.info("Update for {} ({} -> {}) found", fileInfo.modId, fileInfo.version, update.version.version) - _updates.add(update) - } - -} - diff --git a/src/main/kotlin/net/modmanagermc/core/update/provider/modrinth/Modrinth.kt b/src/main/kotlin/net/modmanagermc/core/update/provider/modrinth/Modrinth.kt deleted file mode 100644 index 320ff26..0000000 --- a/src/main/kotlin/net/modmanagermc/core/update/provider/modrinth/Modrinth.kt +++ /dev/null @@ -1,199 +0,0 @@ -/* - * Copyright (c) 2022 DeathsGun - * - * 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 - * - * http://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. - */ - -package net.modmanagermc.core.update.provider.modrinth - -import kotlinx.serialization.ExperimentalSerializationApi -import kotlinx.serialization.encodeToString -import kotlinx.serialization.json.Json -import kotlinx.serialization.json.decodeFromStream -import net.modmanagermc.core.Core -import net.modmanagermc.core.di.DI -import net.modmanagermc.core.exceptions.ModManagerException -import net.modmanagermc.core.model.Dependency -import net.modmanagermc.core.model.JarFileInfo -import net.modmanagermc.core.model.Version -import net.modmanagermc.core.update.IUpdateProvider -import net.modmanagermc.core.update.provider.modrinth.model.ErrorResponse -import net.modmanagermc.core.update.provider.modrinth.model.ModrinthVersion -import net.modmanagermc.core.update.provider.modrinth.model.UpdateRequest -import org.apache.http.client.methods.HttpGet -import org.apache.http.client.methods.HttpPost -import org.apache.http.client.utils.URIBuilder -import org.apache.http.entity.StringEntity -import org.apache.http.impl.client.HttpClients -import org.apache.http.util.EntityUtils - -/** - * Modrinth Provider - */ -class Modrinth(private val di: DI) : IUpdateProvider { - - override val name: String = "modrinth" - private val client = HttpClients.createMinimal() - private val json = Json { - ignoreUnknownKeys = true - } - - /** - * Uses the following url: https://api.modrinth.com/v2/version_file/{hash}/update?algorithm={algorithm} - * - * @throws ModManagerException if no SHA-512 or SHA-1 is provided - */ - @OptIn(ExperimentalSerializationApi::class) - @Throws(ModManagerException::class) - override fun getVersion(fileInfo: JarFileInfo): Version? { - val hash = fileInfo.hashes["SHA-512"] ?: fileInfo.hashes["SHA-1"] - ?: throw ModManagerException("modmanager.error.hash", fileInfo.modId) - - val algorithm = if (fileInfo.hashes.containsKey("SHA-512")) "sha512" else "sha1" - - val request = HttpPost("https://api.modrinth.com/v2/version_file/$hash/update?algorithm=$algorithm") - request.setHeader("Accept", "application/json") - request.setHeader("User-Agent", "ModManager-Core ${Core.getCoreVersion(di)}") - request.setHeader("Content-Type", "application/json") - request.entity = StringEntity( - Json.encodeToString( - UpdateRequest( - listOf("fabric"), - listOf(Core.getMinecraftVersion(di)) - ) - ) - ) - - val response = client.execute(request) - if (response.statusLine.statusCode != 200) { - val error = json.decodeFromStream(response.entity.content) - EntityUtils.consume(response.entity) - throw error.toException("Received invalid status code ${response.statusLine.statusCode}. Message: %s") - } - val updateResponse = try { - json.decodeFromStream(response.entity.content) - } catch (e: Exception) { - EntityUtils.consume(response.entity) - e.printStackTrace() - return null - } - EntityUtils.consume(response.entity) - - val asset = updateResponse.files.firstOrNull() ?: return null - return Version( - updateResponse.id, - updateResponse.projectId, - "modrinth", - updateResponse.version, - updateResponse.changelog, - updateResponse.dependencies.mapNotNull { toDependency(it) }, - asset.filename, - asset.url, - asset.hashes, - ) - } - - override fun getLatestVersion(projectId: String): Version? { - var versions = getVersions(projectId) - if (versions.isEmpty()) { - return null - } - versions = versions.sortedBy { it.datePublished } - val version = versions[0] - val asset = version.files.firstOrNull() ?: return null - return Version( - version.id, - version.projectId, - "modrinth", - version.version, - version.changelog, - version.dependencies.mapNotNull { toDependency(it) }, - asset.filename, - asset.url, - asset.hashes, - ) - } - - @OptIn(ExperimentalSerializationApi::class) - private fun getVersions(projectId: String): List { - val uri = URIBuilder("https://api.modrinth.com/v2/project/${projectId}/version") - .addParameter("loaders", "[\"fabric\"]") - .addParameter("game_versions", "[\"${Core.getMinecraftVersion(di)}\"]") - .build() - val request = HttpGet(uri) - - request.setHeader("Accept", "application/json") - request.setHeader("User-Agent", "ModManager-Core ${Core.getCoreVersion(di)}") - val response = client.execute(request) - if (response.statusLine.statusCode != 200) { - val error = json.decodeFromStream(response.entity.content) - throw error.toException("Received invalid status code ${response.statusLine.statusCode}. Message: %s") - } - return try { - json.decodeFromStream(response.entity.content) - } catch (e: Exception) { - e.printStackTrace() - emptyList() - } - } - - @OptIn(ExperimentalSerializationApi::class) - private fun getVersion(id: String): ModrinthVersion? { - val request = HttpGet("https://api.modrinth.com/v2/version/${id}") - request.addHeader("Accept", "application/json") - request.setHeader("User-Agent", "ModManager-Core ${Core.getCoreVersion(di)}") - - val response = client.execute(request) - if (response.statusLine.statusCode != 200) { - val error = json.decodeFromStream(response.entity.content) - throw error.toException("Received invalid status code ${response.statusLine.statusCode}. Message: %s") - } - return try { - json.decodeFromStream(response.entity.content) - } catch (e: Exception) { - e.printStackTrace() - null - } - } - - // Creates a dependency tree - private fun toDependency(dep: ModrinthVersion.Dependency): Dependency? { - if (dep.versionId == null) { - return null // Currently, only direct versions supported - } - try { - var version = getVersion(dep.versionId) ?: return null - if (!version.gameVersions.contains(Core.getMinecraftVersion(di))) { - val versions = getVersions(version.projectId) - if (versions.isEmpty()) { - return null // Can't be installed due to having no compatible version - } - version = versions.firstOrNull() ?: return null - } - val asset = version.files.firstOrNull() ?: return null - return Dependency( - version.projectId, - version.version, - asset.url, - asset.filename, - dep.dependencyType == "required", - asset.hashes, - version.dependencies.mapNotNull { toDependency(it) } - ) - } catch (e: Exception) { - e.printStackTrace() - } - return null - } - -} \ No newline at end of file diff --git a/src/main/kotlin/net/modmanagermc/core/update/provider/modrinth/model/ErrorResponse.kt b/src/main/kotlin/net/modmanagermc/core/update/provider/modrinth/model/ErrorResponse.kt deleted file mode 100644 index c24c959..0000000 --- a/src/main/kotlin/net/modmanagermc/core/update/provider/modrinth/model/ErrorResponse.kt +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2022 DeathsGun - * - * 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 - * - * http://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. - */ - -package net.modmanagermc.core.update.provider.modrinth.model - -import kotlinx.serialization.Serializable -import net.modmanagermc.core.exceptions.ModManagerException - -@Serializable -data class ErrorResponse( - val description: String?, - val error: String? -) { - - fun toException(message: String): ModManagerException { - return when (error) { - "not_found" -> ModManagerException(String.format(message, description)) - else -> ModManagerException(String.format(message, description ?: "no detailed error message provided")) - } - } -} diff --git a/src/main/kotlin/net/modmanagermc/core/update/provider/modrinth/model/ModrinthVersion.kt b/src/main/kotlin/net/modmanagermc/core/update/provider/modrinth/model/ModrinthVersion.kt deleted file mode 100644 index 3471822..0000000 --- a/src/main/kotlin/net/modmanagermc/core/update/provider/modrinth/model/ModrinthVersion.kt +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) 2022 DeathsGun - * - * 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 - * - * http://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. - */ - -package net.modmanagermc.core.update.provider.modrinth.model - -import kotlinx.datetime.Instant -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable -import java.util.StringJoiner - -/* -{ - "name": "Version 1.0.0", - "version_number": "1.0.0", - "changelog": "List of changes in this version: ...", - "changelog_url": null, - "dependencies": [ - { - "version_id": "IIJJKKLL", - "project_id": "QQRRSSTT", - "dependency_type": "required" - } - ], - "game_versions": [ - "1.16.5", - "1.17.1" - ], - "version_type": "release", - "loaders": [ - "fabric", - "forge" - ], - "featured": true, - "id": "IIJJKKLL", - "project_id": "AABBCCDD", - "author_id": "EEFFGGHH", - "date_published": "2019-08-24T14:15:22Z", - "downloads": 0, - "files": [ - { - "hashes": { - "sha512": "93ecf5fe02914fb53d94aa3d28c1fb562e23985f8e4d48b9038422798618761fe208a31ca9b723667a4e05de0d91a3f86bcd8d018f6a686c39550e21b198d96f", - "sha1": "c84dd4b3580c02b79958a0590afd5783d80ef504" - }, - "url": "https://cdn.modrinth.com/data/AABBCCDD/versions/1.0.0/my_file.jar", - "filename": "my_file.jar", - "primary": false - } - ] -} - */ -@Serializable -data class ModrinthVersion( - val id: String, - val name: String, - @SerialName("version_number") - val version: String, - val changelog: String, - val dependencies: List, - @SerialName("game_versions") - val gameVersions: List, - @SerialName("version_type") - val versionType: String, - @SerialName("project_id") - val projectId: String, - @SerialName("date_published") - val datePublished: Instant, - val loaders: List, - val files: List -) { - - @Serializable - data class Dependency( - @SerialName("version_id") - val versionId: String?, - @SerialName("project_id") - val projectId: String?, - @SerialName("dependency_type") - val dependencyType: String - ) - - @Serializable - data class Asset( - val url: String, - val filename: String, - val hashes: Map - ) -} diff --git a/src/main/kotlin/xyz/deathsgun/modmanager/core/ModManager.kt b/src/main/kotlin/xyz/deathsgun/modmanager/core/ModManager.kt new file mode 100644 index 0000000..a32170b --- /dev/null +++ b/src/main/kotlin/xyz/deathsgun/modmanager/core/ModManager.kt @@ -0,0 +1,51 @@ +/* + * Copyright 2022 ModManagerMC + * + * 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 + * + * http://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. + */ + +package xyz.deathsgun.modmanager.core + +import net.fabricmc.loader.api.FabricLoader +import xyz.deathsgun.modmanager.core.api.provider.IModProvider +import xyz.deathsgun.modmanager.core.config.Config +import java.util.* + +object ModManager { + + private lateinit var modManagerBuildInfo: Properties + private val buildInfo = Properties() + var config = Config.loadConfig() + val provider: List + get() = FabricLoader.getInstance().getEntrypoints("modmanager", IModProvider::class.java) + + init { + buildInfo.load(ModManager::class.java.getResourceAsStream("/core-build.info")) + } + + @JvmStatic + fun init(properties: Properties) { + this.modManagerBuildInfo = properties + } + + @JvmStatic + fun getProvider(name: String): IModProvider? { + return provider.find { it.getName().equals(name, true) } + } + + fun getCoreVersion(): String = buildInfo["version.core"] as String + + fun getMinecraftReleaseTarget(): String = modManagerBuildInfo["version.target"] as String + fun getMinecraftVersion(): String = modManagerBuildInfo["version.minecraft"] as String + +} \ No newline at end of file diff --git a/src/main/kotlin/net/modmanagermc/core/model/Category.kt b/src/main/kotlin/xyz/deathsgun/modmanager/core/api/Category.kt similarity index 79% rename from src/main/kotlin/net/modmanagermc/core/model/Category.kt rename to src/main/kotlin/xyz/deathsgun/modmanager/core/api/Category.kt index 0290fb3..b821e51 100644 --- a/src/main/kotlin/net/modmanagermc/core/model/Category.kt +++ b/src/main/kotlin/xyz/deathsgun/modmanager/core/api/Category.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 DeathsGun + * Copyright 2021-2022 ModManagerMC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,9 +14,12 @@ * limitations under the License. */ -package net.modmanagermc.core.model +package xyz.deathsgun.modmanager.core.api + +import net.minecraft.text.TranslatableText data class Category( val id: String, - val translationId: String + val text: TranslatableText ) + diff --git a/src/main/kotlin/net/modmanagermc/core/task/TaskManager.kt b/src/main/kotlin/xyz/deathsgun/modmanager/core/api/http/CategoriesResult.kt similarity index 59% rename from src/main/kotlin/net/modmanagermc/core/task/TaskManager.kt rename to src/main/kotlin/xyz/deathsgun/modmanager/core/api/http/CategoriesResult.kt index 6514e85..cc6b90a 100644 --- a/src/main/kotlin/net/modmanagermc/core/task/TaskManager.kt +++ b/src/main/kotlin/xyz/deathsgun/modmanager/core/api/http/CategoriesResult.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 DeathsGun + * Copyright 2021-2022 ModManagerMC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,22 +14,15 @@ * limitations under the License. */ -package net.modmanagermc.core.task +package xyz.deathsgun.modmanager.core.api.http -object TaskManager { +import net.minecraft.text.TranslatableText +import xyz.deathsgun.modmanager.core.api.Category - private val tasks: MutableList = mutableListOf() +sealed class CategoriesResult { - fun add(task: Runnable) { - tasks.add(task) - } + data class Success(val categories: List) : CategoriesResult() - fun executeTasks() { - val tasks = ArrayList(this.tasks) - for (task in tasks) { - task.run() - this.tasks.remove(task) - } - } + data class Error(val text: TranslatableText, val cause: Exception? = null) : CategoriesResult() -} \ No newline at end of file +} diff --git a/src/main/kotlin/xyz/deathsgun/modmanager/core/api/http/HttpClient.kt b/src/main/kotlin/xyz/deathsgun/modmanager/core/api/http/HttpClient.kt new file mode 100644 index 0000000..0d9c28f --- /dev/null +++ b/src/main/kotlin/xyz/deathsgun/modmanager/core/api/http/HttpClient.kt @@ -0,0 +1,103 @@ +/* + * Copyright 2022 ModManagerMC + * + * 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 + * + * http://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. + */ + +package xyz.deathsgun.modmanager.core.api.http + +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.decodeFromStream +import xyz.deathsgun.modmanager.core.ModManager +import java.io.ByteArrayInputStream +import java.io.InputStream +import java.net.HttpURLConnection +import java.net.URI +import java.net.URL +import java.nio.file.Files +import java.nio.file.Path +import kotlin.math.min + +object HttpClient { + + val json = Json { + ignoreUnknownKeys = true + } + + fun get(url: String): ByteArray { + return get(URI.create(url)) + } + + fun get(uri: URI): ByteArray { + val connection = uri.toURL().openConnection() as HttpURLConnection + connection.readTimeout = 10000 + connection.requestMethod = "GET" + connection.setRequestProperty("User-Agent", "ModManager Core ${ModManager.getCoreVersion()}") + connection.connect() + if (connection.responseCode != 200) { + connection.disconnect() + throw InvalidStatusCodeException(connection.responseCode) + } + val content = connection.inputStream.readBytes() + connection.disconnect() + return content + } + + fun getInputStream(url: String): InputStream { + return getInputStream(URI.create(url)) + } + + fun getInputStream(uri: URI): InputStream { + return ByteArrayInputStream(get(uri)) + } + + fun download(url: String, path: Path, listener: ((Double) -> Unit)? = null) { + val output = Files.newOutputStream(path) + val connection = URL(url).openConnection() as HttpURLConnection + connection.readTimeout = 10000 + connection.requestMethod = "GET" + connection.connect() + if (connection.responseCode != 200) { + connection.disconnect() + throw InvalidStatusCodeException(connection.responseCode) + } + val size = connection.contentLength + var downloaded = 0 + while (true) { + val buffer = ByteArray(min(1024, size - downloaded)) + val read = connection.inputStream.read(buffer) + if (read == -1) { + break + } + output.write(buffer, 0, read) + downloaded += read + listener?.invoke((downloaded / size).toDouble()) + } + connection.disconnect() + output.flush() + output.close() + } + + @OptIn(ExperimentalSerializationApi::class) + inline fun getJson(url: String): T { + return json.decodeFromStream(getInputStream(url)) + } + + @OptIn(ExperimentalSerializationApi::class) + inline fun getJson(url: URI): T { + return json.decodeFromStream(getInputStream(url)) + } + + class InvalidStatusCodeException(val statusCode: Int) : Exception("Received invalid status code: $statusCode") +} diff --git a/src/main/kotlin/net/modmanagermc/core/screen/IListScreen.kt b/src/main/kotlin/xyz/deathsgun/modmanager/core/api/http/ModResult.kt similarity index 62% rename from src/main/kotlin/net/modmanagermc/core/screen/IListScreen.kt rename to src/main/kotlin/xyz/deathsgun/modmanager/core/api/http/ModResult.kt index 494f675..ce0d521 100644 --- a/src/main/kotlin/net/modmanagermc/core/screen/IListScreen.kt +++ b/src/main/kotlin/xyz/deathsgun/modmanager/core/api/http/ModResult.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 DeathsGun + * Copyright 2021-2022 ModManagerMC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,14 +14,12 @@ * limitations under the License. */ -package net.modmanagermc.core.screen +package xyz.deathsgun.modmanager.core.api.http -interface IListScreen { +import net.minecraft.text.TranslatableText +import xyz.deathsgun.modmanager.core.api.mod.Mod - fun getFocused(): Any? - - fun updateSelectedEntry(widget: Any, entry: E?) - - fun updateMultipleEntries(widget: Any, entries: ArrayList) - -} \ No newline at end of file +sealed class ModResult { + data class Success(val mod: Mod) : ModResult() + data class Error(val text: TranslatableText, val cause: Exception? = null) : ModResult() +} diff --git a/src/main/kotlin/net/modmanagermc/core/store/provider/modrinth/models/LicenseModel.kt b/src/main/kotlin/xyz/deathsgun/modmanager/core/api/http/ModsResult.kt similarity index 61% rename from src/main/kotlin/net/modmanagermc/core/store/provider/modrinth/models/LicenseModel.kt rename to src/main/kotlin/xyz/deathsgun/modmanager/core/api/http/ModsResult.kt index 1a123d1..4384790 100644 --- a/src/main/kotlin/net/modmanagermc/core/store/provider/modrinth/models/LicenseModel.kt +++ b/src/main/kotlin/xyz/deathsgun/modmanager/core/api/http/ModsResult.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 DeathsGun + * Copyright 2021-2022 ModManagerMC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,9 +14,12 @@ * limitations under the License. */ -package net.modmanagermc.core.store.provider.modrinth.models +package xyz.deathsgun.modmanager.core.api.http -import kotlinx.serialization.Serializable +import net.minecraft.text.TranslatableText +import xyz.deathsgun.modmanager.core.api.mod.Mod -@Serializable -data class LicenseModel(val short: String? = null, val id: String? = null, val name: String) +sealed class ModsResult { + data class Success(val mods: List) : ModsResult() + data class Error(val text: TranslatableText, val cause: Exception? = null) : ModsResult() +} diff --git a/src/main/kotlin/net/modmanagermc/core/model/Mod.kt b/src/main/kotlin/xyz/deathsgun/modmanager/core/api/mod/Mod.kt similarity index 74% rename from src/main/kotlin/net/modmanagermc/core/model/Mod.kt rename to src/main/kotlin/xyz/deathsgun/modmanager/core/api/mod/Mod.kt index 5da4d8c..01638e5 100644 --- a/src/main/kotlin/net/modmanagermc/core/model/Mod.kt +++ b/src/main/kotlin/xyz/deathsgun/modmanager/core/api/mod/Mod.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 DeathsGun + * Copyright 2021-2022 ModManagerMC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,15 +14,18 @@ * limitations under the License. */ -package net.modmanagermc.core.model +package xyz.deathsgun.modmanager.core.api.mod + +import xyz.deathsgun.modmanager.core.api.Category data class Mod( val id: String, - val provider: String, + val slug: String, + var author: String?, val name: String, + var shortDescription: String, val iconUrl: String?, - val description: String, + var description: String?, val license: String?, val categories: List, - val fullDescription: String?, ) diff --git a/src/main/kotlin/xyz/deathsgun/modmanager/core/api/provider/IModProvider.kt b/src/main/kotlin/xyz/deathsgun/modmanager/core/api/provider/IModProvider.kt new file mode 100644 index 0000000..2e47f70 --- /dev/null +++ b/src/main/kotlin/xyz/deathsgun/modmanager/core/api/provider/IModProvider.kt @@ -0,0 +1,85 @@ +/* + * Copyright 2021-2022 ModManagerMC + * + * 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 + * + * http://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. + */ + +package xyz.deathsgun.modmanager.core.api.provider + +import xyz.deathsgun.modmanager.core.api.Category +import xyz.deathsgun.modmanager.core.api.http.CategoriesResult +import xyz.deathsgun.modmanager.core.api.http.ModResult +import xyz.deathsgun.modmanager.core.api.http.ModsResult + +/** + * Main entrypoint for developers who want to extend + * the list of mods which ModManager shows. + */ +interface IModProvider { + + /** + * Name of the provider. This will be shown + * in the GUI + * + * @return a user-friendly name of the mod provider implementation + */ + fun getName(): String + + /** + * Returns a list of all possible mod categories also with containing a translatable text + * + * @return a list of all mod categories + */ + fun getCategories(): CategoriesResult + + /** + * Returns a limited number of [xyz.deathsgun.modmanager.core.api.mod.Mod]'s sorted + * in a given way. + * + * @param sorting the requested sorting of the mods + * @param page the requested from the UI starting at 1 + * @param limit to not overfill the ui and for shorter loading times the amount of returned mods needs to limited + * @return a list of sorted mods + */ + fun getMods(sorting: Sorting, page: Int, limit: Int): ModsResult + + /** + * Returns a limited number of [xyz.deathsgun.modmanager.core.api.mod.Mod]'s from the specified category + * + * @param categories the categories of the mods + * @param sorting the sorting order + * @param page the requested from the UI starting at 1 + * @param limit to not overfill the ui and for shorter loading times the amount of returned mods needs to limited + * @return a list of sorted mods + */ + fun getMods(categories: List, sorting: Sorting, page: Int, limit: Int): ModsResult + + /** + * Returns a limited number of [xyz.deathsgun.modmanager.core.api.mod.Mod]'s from a given search. + * + * @param query the search string + * @param categories the categories in which should be searched + * @param page the current requested page starts at 0 + * @param limit the amount of mods to return + * @return a list of mods matching the search term + */ + fun search(query: String, categories: List, sorting: Sorting, page: Int, limit: Int): ModsResult + + /** + * Returns a more detailed representation of the mod + * + * @param id the [xyz.deathsgun.modmanager.core.api.mod.Mod] id which is used to receive + * @return a more detailed representation of [xyz.deathsgun.modmanager.core.api.mod.Mod] + */ + fun getMod(id: String): ModResult +} \ No newline at end of file diff --git a/src/main/kotlin/net/modmanagermc/core/store/Sort.kt b/src/main/kotlin/xyz/deathsgun/modmanager/core/api/provider/Sorting.kt similarity index 62% rename from src/main/kotlin/net/modmanagermc/core/store/Sort.kt rename to src/main/kotlin/xyz/deathsgun/modmanager/core/api/provider/Sorting.kt index fb66383..563880d 100644 --- a/src/main/kotlin/net/modmanagermc/core/store/Sort.kt +++ b/src/main/kotlin/xyz/deathsgun/modmanager/core/api/provider/Sorting.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 DeathsGun + * Copyright 2021-2022 ModManagerMC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,14 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +package xyz.deathsgun.modmanager.core.api.provider -package net.modmanagermc.core.store +import net.minecraft.text.Text +import net.minecraft.text.TranslatableText -enum class Sort { - RELEVANCE, DOWNLOADS, FOLLOWS, NEWEST, UPDATED; +enum class Sorting { + RELEVANCE, DOWNLOADS, UPDATED, NEWEST; - fun translation(): String { - return "modmanager.sorting.%s".format(name.lowercase()) + fun translation(): Text { + return TranslatableText(String.format("modmanager.sorting.%s", name.lowercase())) } } \ No newline at end of file diff --git a/src/main/kotlin/net/modmanagermc/core/config/Config.kt b/src/main/kotlin/xyz/deathsgun/modmanager/core/config/Config.kt similarity index 55% rename from src/main/kotlin/net/modmanagermc/core/config/Config.kt rename to src/main/kotlin/xyz/deathsgun/modmanager/core/config/Config.kt index 6f943af..957506d 100644 --- a/src/main/kotlin/net/modmanagermc/core/config/Config.kt +++ b/src/main/kotlin/xyz/deathsgun/modmanager/core/config/Config.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 DeathsGun + * Copyright 2021-2022 ModManagerMC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,35 +14,25 @@ * limitations under the License. */ -package net.modmanagermc.core.config +package xyz.deathsgun.modmanager.core.config +import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.Serializable import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json -import net.modmanagermc.core.config.Config.UpdateChannel -import net.modmanagermc.core.config.Config.UpdateChannel.* +import net.minecraft.text.Text +import net.minecraft.text.TranslatableText import java.io.FileNotFoundException import java.nio.file.Files import java.nio.file.NoSuchFileException import java.nio.file.Paths -import java.util.Arrays -import java.util.StringJoiner -/** - * ModManager's config representation - * - * Currently, only holds information about the [UpdateChannel] - * and the mods to hide from the update page. - * - * @author DeathsGun - * @since ModManager 1.0.0 - */ @Serializable data class Config( - var updateChannel: UpdateChannel = ALL, - var hidden: ArrayList = ArrayList(), - var remove: ArrayList = ArrayList() + var defaultProvider: String = "modrinth", + var updateChannel: UpdateChannel = UpdateChannel.ALL, + var hidden: ArrayList = ArrayList() ) { companion object { @@ -52,6 +42,7 @@ data class Config( encodeDefaults = true } + @OptIn(ExperimentalSerializationApi::class) fun loadConfig(): Config { return try { val file = Paths.get("config", "modmanager", "modmanager.json") @@ -62,35 +53,29 @@ data class Config( if (e !is FileNotFoundException && e !is NoSuchFileException) { e.printStackTrace() } - Config().save() + saveConfig(Config()) } } - } - fun save(): Config { - try { - val dir = Paths.get("config", "modmanager") - dir.toFile().mkdirs() - val file = dir.resolve("modmanager.json") - val data = json.encodeToString(this) - Files.write(file, data.encodeToByteArray()) - } catch (ignored: Exception) { + @OptIn(ExperimentalSerializationApi::class) + fun saveConfig(config: Config): Config { + try { + val dir = Paths.get("config", "modmanager") + dir.toFile().mkdirs() + val file = dir.resolve("modmanager.json") + val data = json.encodeToString(config) + Files.write(file, data.encodeToByteArray()) + } catch (ignored: Exception) { + } + return config } - return this } - /** - * The [UpdateChannel] allows the user to control which type - * of update he receives. - * [ALL] -> Release, Alpha and Beta - * [STABLE] -> Only Release - * [UNSTABLE] -> Only Alpha and Beta's - */ enum class UpdateChannel { ALL, STABLE, UNSTABLE; - fun translationKey(): String { - return String.format("modmanager.channel.%s", name.lowercase()) + fun translation(): Text { + return TranslatableText(String.format("modmanager.channel.%s", name.lowercase())) } } diff --git a/src/main/kotlin/xyz/deathsgun/modmanager/core/gui/ErrorScreen.kt b/src/main/kotlin/xyz/deathsgun/modmanager/core/gui/ErrorScreen.kt new file mode 100644 index 0000000..c2a7bfd --- /dev/null +++ b/src/main/kotlin/xyz/deathsgun/modmanager/core/gui/ErrorScreen.kt @@ -0,0 +1,63 @@ +/* + * Copyright 2021 DeathsGun + * + * 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 + * + * http://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. + */ + +package xyz.deathsgun.modmanager.core.gui + +import net.minecraft.client.font.MultilineText +import net.minecraft.client.gui.DrawableHelper +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.util.math.MatrixStack +import net.minecraft.text.TranslatableText +import net.minecraft.util.math.MathHelper + +class ErrorScreen( + private val previousScreen: Screen, + private val actionScreen: Screen, + private val error: TranslatableText +) : Screen(TranslatableText("modmanager.error.title")) { + + private lateinit var text: MultilineText + + override fun init() { + this.text = MultilineText.create(this.textRenderer, this.error, this.width - 50) + val linesHeight = this.text.count() * 9 + val bottom = MathHelper.clamp(90 + linesHeight + 12, this.height / 6 + 69, this.height - 24) + addButton(ButtonWidget( + this.width / 2 - 155, bottom, 150, 20, ScreenTexts.BACK + ) { + client!!.openScreen(previousScreen) + }) + addButton(ButtonWidget( + this.width / 2 + 5, bottom, 150, 20, TranslatableText("modmanager.button.tryAgain") + ) { + client!!.openScreen(actionScreen) + }) + } + + override fun render(matrices: MatrixStack?, mouseX: Int, mouseY: Int, delta: Float) { + super.renderBackground(matrices) + DrawableHelper.drawCenteredText(matrices, this.textRenderer, this.title, this.width / 2, 70, 16777215) + this.text.drawCenterWithShadow(matrices, this.width / 2, 90) + super.render(matrices, mouseX, mouseY, delta) + } + + override fun shouldCloseOnEsc(): Boolean { + return false + } + +} \ No newline at end of file diff --git a/src/main/kotlin/xyz/deathsgun/modmanager/core/gui/View.kt b/src/main/kotlin/xyz/deathsgun/modmanager/core/gui/View.kt new file mode 100644 index 0000000..cf1283c --- /dev/null +++ b/src/main/kotlin/xyz/deathsgun/modmanager/core/gui/View.kt @@ -0,0 +1,7 @@ +package xyz.deathsgun.modmanager.core.gui + +interface View { + + fun update() + +} \ No newline at end of file diff --git a/src/main/kotlin/xyz/deathsgun/modmanager/core/gui/controller/ConfigController.kt b/src/main/kotlin/xyz/deathsgun/modmanager/core/gui/controller/ConfigController.kt new file mode 100644 index 0000000..8f1f9a1 --- /dev/null +++ b/src/main/kotlin/xyz/deathsgun/modmanager/core/gui/controller/ConfigController.kt @@ -0,0 +1,48 @@ +/* + * Copyright 2022 ModManagerMC + * + * 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 + * + * http://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. + */ + +package xyz.deathsgun.modmanager.core.gui.controller + +import xyz.deathsgun.modmanager.core.ModManager +import xyz.deathsgun.modmanager.core.config.Config + +class ConfigController { + + var provider: String = ModManager.config.defaultProvider + "" + var updateChannel: Config.UpdateChannel = Config.UpdateChannel.values()[ModManager.config.updateChannel.ordinal] + var hidden: ArrayList = ArrayList(ModManager.config.hidden) + + fun nextChannel() { + var pos = Config.UpdateChannel.values().indexOf(updateChannel).inc() + if (pos >= Config.UpdateChannel.values().size) { + pos = 0 + } + updateChannel = Config.UpdateChannel.values()[pos] + } + + fun nextProvider() { + var pos = ModManager.provider.indexOfFirst { it.getName().equals(provider, true) }.inc() + if (pos >= ModManager.provider.size) { + pos = 0 + } + provider = ModManager.provider[pos].getName().lowercase() + } + + fun saveConfig() { + ModManager.config = Config.saveConfig(Config(provider, updateChannel, hidden)) + } + +} \ No newline at end of file diff --git a/src/main/kotlin/xyz/deathsgun/modmanager/core/gui/controller/OverviewController.kt b/src/main/kotlin/xyz/deathsgun/modmanager/core/gui/controller/OverviewController.kt new file mode 100644 index 0000000..8a3e539 --- /dev/null +++ b/src/main/kotlin/xyz/deathsgun/modmanager/core/gui/controller/OverviewController.kt @@ -0,0 +1,49 @@ +package xyz.deathsgun.modmanager.core.gui.controller + +import net.minecraft.text.TranslatableText +import xyz.deathsgun.modmanager.core.api.Category +import xyz.deathsgun.modmanager.core.api.mod.Mod +import xyz.deathsgun.modmanager.core.api.provider.Sorting +import xyz.deathsgun.modmanager.core.gui.View +import xyz.deathsgun.modmanager.core.icon.IconCache + +class OverviewController(private val view: View) { + + var query = "" + var mod: Mod? = null + var categories = ArrayList() + var page = 0 + var limit = 30 + var sorting: Sorting = Sorting.DOWNLOADS + var scrollPercentage = 0.0 + var error: TranslatableText? = null + + fun shouldShowUpdateAll(): Boolean { + return categories.any { it.id == "updatable" } + } + + fun hasNextPage(): Boolean { + return false + } + + fun nextPage() { + page++ + } + + fun hasPreviousPage(): Boolean { + return 0 < page + } + + fun previousPage() { + page-- + if (page < 0) { + page = 0 + } + } + + fun close() { + IconCache.destroyAll() + } + + +} \ No newline at end of file diff --git a/src/main/kotlin/xyz/deathsgun/modmanager/core/icon/IconCache.kt b/src/main/kotlin/xyz/deathsgun/modmanager/core/icon/IconCache.kt new file mode 100644 index 0000000..611e680 --- /dev/null +++ b/src/main/kotlin/xyz/deathsgun/modmanager/core/icon/IconCache.kt @@ -0,0 +1,171 @@ +/* + * Copyright 2021-2022 ModManagerMC + * + * 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 + * + * http://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. + */ + +package xyz.deathsgun.modmanager.core.icon + +import kotlinx.coroutines.DelicateCoroutinesApi +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.launch +import net.minecraft.client.MinecraftClient +import net.minecraft.util.Identifier +import org.apache.logging.log4j.LogManager +import xyz.deathsgun.modmanager.core.api.http.HttpClient +import xyz.deathsgun.modmanager.core.api.mod.Mod +import java.io.InputStream +import java.nio.file.Files +import java.nio.file.Path +import java.util.concurrent.ConcurrentHashMap +import java.util.stream.Collectors + +/** + * Global cache for ModManager's icons + */ +object IconCache { + + private val logger = LogManager.getLogger("IconCache") + private val unknownIcon = Identifier("textures/misc/unknown_pack.png") + private val loadingIcon = Identifier("modmanager", "textures/gui/loading.png") + private val state: ConcurrentHashMap = ConcurrentHashMap() + + // FabricLoader.getInstance().configDir.resolve("modmanager").resolve("icons") + private lateinit var iconsDir: Path + + // MinecraftClient.getInstance().textureManager.registerTexture(icon, NativeImageBackedTexture(image)) + private lateinit var loader: (image: InputStream) -> Unit + + /** + * Initializes the cache with a directory and a texture loader method + */ + @JvmStatic + fun init(dir: Path, textureLoader: (image: InputStream) -> Unit) { + iconsDir = Files.createDirectories(dir) + loader = textureLoader + } + + /** + * This method gets called by the rendering method which binds + * the icon. It will start downloading the icon in the background + * and will show a loading icon. + * In case of an error it will return a default error icon. + * @return in the best case the icon of the mod. In the worst an error icon + * @throws IllegalStateException when [IconCache.init] hasn't been called before + */ + @JvmStatic + @OptIn(DelicateCoroutinesApi::class) + @Throws(IllegalStateException::class) + fun get(mod: Mod): Identifier { + if (!this::iconsDir.isInitialized) { + throw IllegalStateException() + } + return when (this.state[mod.id] ?: IconState.NOT_FOUND) { + IconState.NOT_FOUND -> { + GlobalScope.launch { + downloadIcon(mod) + } + loadingIcon + } + IconState.DOWNLOADED -> { + readIcon(mod) + } + IconState.LOADED -> { + Identifier("modmanager", "mod_icons/${mod.id.lowercase()}") + } + IconState.DOWNLOADING -> loadingIcon + IconState.ERRORED -> unknownIcon + } + } + + private fun readIcon(mod: Mod): Identifier { + return try { + loader(Files.newInputStream(iconsDir.resolve(mod.id))) + this.state[mod.id] = IconState.LOADED + Identifier("modmanager", "mod_icons/${mod.id.lowercase()}") + } catch (e: Exception) { + this.state[mod.id] = IconState.ERRORED + logger.error("Error while loading icon for {}: {}", mod.slug, e.message) + unknownIcon + } + } + + private fun downloadIcon(mod: Mod) { + if (Files.exists(iconsDir.resolve(mod.id))) { + state[mod.id] = IconState.DOWNLOADED + return + } + if (mod.iconUrl == null) { + state[mod.id] = IconState.ERRORED + return + } + val iconState = state[mod.id] ?: IconState.NOT_FOUND + if (iconState != IconState.NOT_FOUND) { + return + } + state[mod.id] = IconState.DOWNLOADING + try { + HttpClient.download(mod.iconUrl, iconsDir.resolve(mod.id)) + state[mod.id] = IconState.DOWNLOADED + } catch (e: Exception) { + state[mod.id] = IconState.ERRORED + logger.error("Error while downloading icon for {}: {}", mod.slug, e.message) + } + } + + /** + * Unloads all icons with the state [IconState.LOADED] + * and resets them to [IconState.DOWNLOADED] + */ + @JvmStatic + fun destroyAll() { + val loadedMods = state.filter { it.value == IconState.LOADED }.keys + for (mod in loadedMods) { + val icon = Identifier("modmanager", "mod_icons/${mod.lowercase()}") + MinecraftClient.getInstance().textureManager.destroyTexture(icon) + this.state[mod] = IconState.DOWNLOADED + } + } + + /** + * Removes files from the icon cache until the maximum of + * 10MB has been reached. + */ + @JvmStatic + fun clean() { + logger.info("Cleaning icon cache...") + val files = Files.list(iconsDir) + .sorted { o1, o2 -> + o1.toFile().lastModified().compareTo(o2.toFile().lastModified()) + }.collect(Collectors.toList()) + if (files.isEmpty()) { + logger.info("No cleanup required") + return + } + var i = 0 + while (Files.list(iconsDir).mapToLong { it.toFile().length() }.sum() >= 10000000) { + if (files.size <= i) { + return + } + logger.debug("Deleting {}", files[i].fileName) + Files.delete(files[i]) + i++ + } + logger.info("Cache cleanup done!") + } + + private enum class IconState { + NOT_FOUND, DOWNLOADING, DOWNLOADED, LOADED, ERRORED + } + +} \ No newline at end of file diff --git a/src/main/kotlin/xyz/deathsgun/modmanager/core/modrinth/Modrinth.kt b/src/main/kotlin/xyz/deathsgun/modmanager/core/modrinth/Modrinth.kt new file mode 100644 index 0000000..c57f12f --- /dev/null +++ b/src/main/kotlin/xyz/deathsgun/modmanager/core/modrinth/Modrinth.kt @@ -0,0 +1,188 @@ +/* + * Copyright 2021-2022 ModManagerMC + * + * 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 + * + * http://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. + */ + +package xyz.deathsgun.modmanager.core.modrinth + +import kotlinx.serialization.SerializationException +import net.minecraft.text.TranslatableText +import org.apache.http.client.utils.URIBuilder +import org.apache.logging.log4j.LogManager +import xyz.deathsgun.modmanager.core.ModManager +import xyz.deathsgun.modmanager.core.api.Category +import xyz.deathsgun.modmanager.core.api.http.CategoriesResult +import xyz.deathsgun.modmanager.core.api.http.HttpClient +import xyz.deathsgun.modmanager.core.api.http.ModResult +import xyz.deathsgun.modmanager.core.api.http.ModsResult +import xyz.deathsgun.modmanager.core.api.mod.Mod +import xyz.deathsgun.modmanager.core.api.provider.IModProvider +import xyz.deathsgun.modmanager.core.api.provider.Sorting +import xyz.deathsgun.modmanager.core.modrinth.models.DetailedMod +import xyz.deathsgun.modmanager.core.modrinth.models.SearchResult +import java.io.IOException +import java.net.SocketTimeoutException + +class Modrinth : IModProvider { + + private val baseUri: String = "https://api.modrinth.com" + private val logger = LogManager.getLogger("Modrinth") + private val categories = ArrayList() + + override fun getName() = "Modrinth" + + override fun getCategories(): CategoriesResult { + logger.debug("Getting categories...") + if (categories.isNotEmpty()) { + logger.debug("Using cached categories({})", categories.size) + return CategoriesResult.Success(categories) + } + logger.debug("Categories not cached retrieving...") + return try { + val categories = HttpClient.getJson>("${baseUri}/api/v1/tag/category") + for (category in categories) { + if (category == "fabric" || category == "forge") { // Fabric and Forge are not really a categories + continue + } + this.categories.add( + Category( + category, + TranslatableText(String.format("modmanager.category.%s", category)) + ) + ) + } + logger.debug("Retrieved {} categories!", this.categories.size) + CategoriesResult.Success(this.categories) + } catch (e: Exception) { + logger.error("Error while getting categories: {}", e.message) + CategoriesResult.Error(e.toTranslatable(), e) + } + } + + override fun getMods(sorting: Sorting, page: Int, limit: Int): ModsResult { + val builder = URIBuilder(baseUri).apply { + path = "/api/v1/mod" + addParameter("filters", "categories=\"fabric\" AND NOT client_side=\"unsupported\"") + } + return getMods(builder, sorting, page, limit) + } + + override fun getMods(categories: List, sorting: Sorting, page: Int, limit: Int): ModsResult { + val builder = URIBuilder(baseUri).apply { + path = "/api/v1/mod" + addParameter( + "filters", + "categories=\"fabric\" AND NOT client_side=\"unsupported\"${filterFromCategories(categories)}" + ) + } + return getMods(builder, sorting, page, limit) + } + + override fun search( + query: String, + categories: List, + sorting: Sorting, + page: Int, + limit: Int + ): ModsResult { + val builder = URIBuilder(baseUri).apply { + path = "/api/v1/mod" + addParameter("query", query) + addParameter( + "filters", + "categories=\"fabric\" AND NOT client_side=\"unsupported\"${filterFromCategories(categories)}" + ) + } + return getMods(builder, sorting, page, limit) + } + + override fun getMod(id: String): ModResult { + val modId = if (id.contains("-")) id.split("-")[1] else id + return try { + val result = HttpClient.getJson("${baseUri}/api/v1/mod/$modId") + val categoriesList = ArrayList() + result.categories.forEach { categoryId -> + categoriesList.add( + Category( + categoryId, + TranslatableText("modmanager.category.${categoryId}") + ) + ) + } + ModResult.Success( + Mod( + id = if (result.id.contains("-")) result.id.split("-")[1] else id, + slug = result.slug, + author = null, + name = result.title, + shortDescription = result.description, + iconUrl = result.iconUrl, + description = result.body, + license = result.license.name, + categories = categoriesList + ) + ) + } catch (e: Exception) { + ModResult.Error(e.toTranslatable(), e) + } + } + + private fun filterFromCategories(categories: List): String { + var categoriesFilter = "" + for (category in categories) { + categoriesFilter += "AND categories=\"${category.id}\"" + } + categoriesFilter = categoriesFilter.replaceFirst("AND ", " AND (") + if (categories.isNotEmpty()) { + categoriesFilter += ")" + } + return categoriesFilter + } + + private fun getMods(builder: URIBuilder, sorting: Sorting, page: Int, limit: Int): ModsResult { + builder.apply { + addParameter( + "version", + String.format( + "versions=\"%s\" OR versions=\"%s\"", + ModManager.getMinecraftReleaseTarget(), + ModManager.getMinecraftVersion() + ) + ) + addParameter("index", sorting.name.lowercase()) + addParameter("offset", (page * limit).toString()) + addParameter("limit", limit.toString()) + } + return try { + ModsResult.Success(HttpClient.getJson(builder.build()).toList()) + } catch (e: Exception) { + logger.error("Error while requesting mods {}", e) + ModsResult.Error(e.toTranslatable(), e) + } + } + + private fun Exception.toTranslatable(): TranslatableText { + return when (this) { + is HttpClient.InvalidStatusCodeException -> TranslatableText( + "modmanager.error.invalidStatus", + statusCode + ) + is SerializationException -> TranslatableText("modmanager.error.failedToParse", message) + is SocketTimeoutException -> TranslatableText("modmanager.error.network", message) + is IOException -> TranslatableText("modmanager.error.network", message) + else -> TranslatableText("modmanager.error.unknown", message) + } + } + +} \ No newline at end of file diff --git a/src/main/kotlin/net/modmanagermc/core/store/provider/modrinth/models/Category.kt b/src/main/kotlin/xyz/deathsgun/modmanager/core/modrinth/models/DetailedMod.kt similarity index 62% rename from src/main/kotlin/net/modmanagermc/core/store/provider/modrinth/models/Category.kt rename to src/main/kotlin/xyz/deathsgun/modmanager/core/modrinth/models/DetailedMod.kt index fb0219b..2c6da88 100644 --- a/src/main/kotlin/net/modmanagermc/core/store/provider/modrinth/models/Category.kt +++ b/src/main/kotlin/xyz/deathsgun/modmanager/core/modrinth/models/DetailedMod.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 DeathsGun + * Copyright 2021-2022 ModManagerMC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,19 +14,23 @@ * limitations under the License. */ -package net.modmanagermc.core.store.provider.modrinth.models +package xyz.deathsgun.modmanager.core.modrinth.models import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable -import net.modmanagermc.core.model.Category @Serializable -data class Category( - val name: String, - @SerialName("project_type") - val projectType: String +data class DetailedMod( + val id: String, + val slug: String, + val title: String, + val description: String, + val body: String, + val license: License, + val categories: List, + @SerialName("icon_url") + val iconUrl: String? ) { - fun toCategory(): Category { - return Category(name, "modmanager.category.${name.lowercase()}") - } + @Serializable + data class License(val name: String) } diff --git a/src/main/kotlin/net/modmanagermc/core/update/provider/modrinth/model/UpdateRequest.kt b/src/main/kotlin/xyz/deathsgun/modmanager/core/modrinth/models/ModResult.kt similarity index 65% rename from src/main/kotlin/net/modmanagermc/core/update/provider/modrinth/model/UpdateRequest.kt rename to src/main/kotlin/xyz/deathsgun/modmanager/core/modrinth/models/ModResult.kt index 3d27b03..2b6203a 100644 --- a/src/main/kotlin/net/modmanagermc/core/update/provider/modrinth/model/UpdateRequest.kt +++ b/src/main/kotlin/xyz/deathsgun/modmanager/core/modrinth/models/ModResult.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 DeathsGun + * Copyright 2021-2022 ModManagerMC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,14 +14,20 @@ * limitations under the License. */ -package net.modmanagermc.core.update.provider.modrinth.model +package xyz.deathsgun.modmanager.core.modrinth.models import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable -data class UpdateRequest( - val loaders: List, - @SerialName("game_versions") - val gameVersions: List +data class ModResult( + @SerialName("mod_id") + val id: String, + val slug: String, + val author: String, + val title: String, + val description: String, + @SerialName("icon_url") + val iconUrl: String?, + val categories: ArrayList ) diff --git a/src/main/kotlin/xyz/deathsgun/modmanager/core/modrinth/models/SearchResult.kt b/src/main/kotlin/xyz/deathsgun/modmanager/core/modrinth/models/SearchResult.kt new file mode 100644 index 0000000..075e9cf --- /dev/null +++ b/src/main/kotlin/xyz/deathsgun/modmanager/core/modrinth/models/SearchResult.kt @@ -0,0 +1,56 @@ +/* + * Copyright 2021-2022 ModManagerMC + * + * 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 + * + * http://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. + */ + +package xyz.deathsgun.modmanager.core.modrinth.models + +import kotlinx.serialization.Serializable +import net.minecraft.text.TranslatableText +import xyz.deathsgun.modmanager.core.api.Category +import xyz.deathsgun.modmanager.core.api.mod.Mod + +@Serializable +data class SearchResult( + val hits: List +) { + fun toList(): List { + val mods = ArrayList() + for (mod in hits) { + val categoriesList = ArrayList() + mod.categories.forEach { categoryId -> + categoriesList.add( + Category( + categoryId, + TranslatableText("modmanager.category.${categoryId}") + ) + ) + } + mods.add( + Mod( + mod.id.split("-")[1], + mod.slug, + mod.author, + mod.title, + mod.description, + mod.iconUrl, + null, + null, + categoriesList, + ) + ) + } + return mods + } +} diff --git a/src/main/resources/assets/modmanager/textures/gui/hide_button.png b/src/main/resources/assets/modmanager/gui/hide_button.png similarity index 100% rename from src/main/resources/assets/modmanager/textures/gui/hide_button.png rename to src/main/resources/assets/modmanager/gui/hide_button.png diff --git a/src/main/resources/assets/modmanager/textures/gui/install_button.png b/src/main/resources/assets/modmanager/gui/install_button.png similarity index 100% rename from src/main/resources/assets/modmanager/textures/gui/install_button.png rename to src/main/resources/assets/modmanager/gui/install_button.png diff --git a/src/main/resources/assets/modmanager/textures/gui/loading.png b/src/main/resources/assets/modmanager/gui/loading.png similarity index 100% rename from src/main/resources/assets/modmanager/textures/gui/loading.png rename to src/main/resources/assets/modmanager/gui/loading.png diff --git a/src/main/resources/assets/modmanager/textures/gui/show_button.png b/src/main/resources/assets/modmanager/gui/show_button.png similarity index 100% rename from src/main/resources/assets/modmanager/textures/gui/show_button.png rename to src/main/resources/assets/modmanager/gui/show_button.png diff --git a/src/main/resources/assets/modmanager/lang b/src/main/resources/assets/modmanager/lang index be475ae..f50ef2f 160000 --- a/src/main/resources/assets/modmanager/lang +++ b/src/main/resources/assets/modmanager/lang @@ -1 +1 @@ -Subproject commit be475ae3982aaa71e80b37eade538da3eca1340b +Subproject commit f50ef2f4db1aca631069857d90c961c53b468db5 diff --git a/src/main/resources/core-build.info b/src/main/resources/core-build.info new file mode 100644 index 0000000..020663b --- /dev/null +++ b/src/main/resources/core-build.info @@ -0,0 +1,17 @@ +# +# Copyright 2022 ModManagerMC +# +# 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 +# +# http://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. +# + +version.core=${version} \ No newline at end of file diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json deleted file mode 100644 index 88f0760..0000000 --- a/src/main/resources/fabric.mod.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "schemaVersion": 1, - "name": "ModManager Core", - "id": "modmanager-core", - "version": "${version}", - "authors": [ - "DeathsGun" - ], - "icon": "assets/modmanager/icon.png", - "description": "Version independent core of ModManager", - "contact": { - "sources": "https://github.com/ModManagerMC/core", - "issues": "https://github.com/ModManagerMC/core/issues" - }, - "environment": "client", - "custom": { - "modmenu": { - "badges": [ - "library" - ], - "parent": "modmanager" - } - } -} \ No newline at end of file diff --git a/src/test/java/net/modmanagermc/core/mod/ModServiceTest.kt b/src/test/java/net/modmanagermc/core/mod/ModServiceTest.kt deleted file mode 100644 index 085308f..0000000 --- a/src/test/java/net/modmanagermc/core/mod/ModServiceTest.kt +++ /dev/null @@ -1,70 +0,0 @@ -package net.modmanagermc.core.mod - -import net.fabricmc.loader.api.FabricLoader -import net.modmanagermc.core.di.DI -import net.modmanagermc.core.discover.IModDiscoveryService -import net.modmanagermc.core.discover.ModDiscoveryService -import net.modmanagermc.core.model.JarFileInfo -import net.modmanagermc.core.test.DummyFabricLoader -import net.modmanagermc.core.test.DummyContainer -import org.junit.Test -import kotlin.test.assertEquals - -internal class ModServiceTest { - - private val di = DI { - bind { - DummyFabricLoader( - mutableListOf( - DummyContainer("minecraft", "1.18.2"), - DummyContainer("modmanager", "2.0.0"), - DummyContainer("modmanager-core", "2.0.0") - ) - ) - } - bind { ModService(this) } - bind { ModDiscoveryService(this) } - } - private val modService: IModService by di - - @Test - fun getVersions() { - val info = JarFileInfo( - "fabric", - "0.47.10+1.18.2", - mapOf("modrinth" to ""), - mapOf( - "SHA-1" to "ff78c08167a3e4ea68c63dd17a2236662f98aefd", - "SHA-256" to "30b506ebb379f8b30c1a78f21417278cca89b89e194f965ca63cbec97434d132", - "MD5" to "0444045edc8b7f9a3472a54b6fea2744" - ) - ) - val versions = modService.getNewerVersions(info) - assert(versions.isNotEmpty()) - } - - @Test - fun dependencyTest() { - val info = JarFileInfo( - "modmanager", - "1.2.2+1.18", - mapOf("modrinth" to "6kq7BzRK"), - mapOf( - "SHA-1" to "ecf4da053cc570500eaf17e478e331277397f7d0", - "SHA-512" to "c5b1d99cc39c9fb7f2f51c4f9544a2e1e7c6b8be671d7d63e2b06bef0c53587289bad8e2c11b2f865c960ddf3929bdad4c682d808455ce38e33b26ccf05e696a" - ) - ) - val versions = modService.getNewerVersions(info) - assert(versions.isNotEmpty()) - for (version in versions) { - assertEquals("6kq7BzRK", version.providerModId) - } - val latest = versions[0] - assert(latest.dependencies.isNotEmpty()) - assert(latest.dependencies.size == 2) - for (dep in latest.dependencies) { - assert(dep.required) - assert(dep.filename.contains("modmenu") || dep.filename.contains("fabric")) - } - } -} \ No newline at end of file diff --git a/src/test/java/net/modmanagermc/core/test/DummyContainer.kt b/src/test/java/net/modmanagermc/core/test/DummyContainer.kt deleted file mode 100644 index 7c78dfd..0000000 --- a/src/test/java/net/modmanagermc/core/test/DummyContainer.kt +++ /dev/null @@ -1,38 +0,0 @@ -package net.modmanagermc.core.test - -import net.fabricmc.loader.api.ModContainer -import net.fabricmc.loader.api.metadata.ModMetadata -import net.fabricmc.loader.api.metadata.ModOrigin -import net.fabricmc.loader.impl.metadata.ModOriginImpl -import java.nio.file.Path -import java.util.* - -class DummyContainer(private val modId: String, private val version: String) : ModContainer { - override fun getMetadata(): ModMetadata { - return DummyMetadata(modId, version) - } - - override fun getRootPaths(): MutableList { - return mutableListOf() - } - - override fun getOrigin(): ModOrigin { - return ModOriginImpl(mutableListOf()) - } - - override fun getContainingMod(): Optional { - return Optional.empty() - } - - override fun getContainedMods(): MutableCollection { - return mutableListOf() - } - - override fun getRootPath(): Path? { - return null - } - - override fun getPath(file: String?): Path? { - return null - } -} \ No newline at end of file diff --git a/src/test/java/net/modmanagermc/core/test/DummyFabricLoader.kt b/src/test/java/net/modmanagermc/core/test/DummyFabricLoader.kt deleted file mode 100644 index f3065bc..0000000 --- a/src/test/java/net/modmanagermc/core/test/DummyFabricLoader.kt +++ /dev/null @@ -1,78 +0,0 @@ -package net.modmanagermc.core.test - -import net.fabricmc.api.EnvType -import net.fabricmc.loader.api.FabricLoader -import net.fabricmc.loader.api.MappingResolver -import net.fabricmc.loader.api.ModContainer -import net.fabricmc.loader.api.ObjectShare -import net.fabricmc.loader.api.entrypoint.EntrypointContainer -import java.io.File -import java.nio.file.Path -import java.util.* - -class DummyFabricLoader(private val mods: MutableList) : FabricLoader { - - override fun getEntrypoints(key: String?, type: Class?): MutableList { - return mutableListOf() - } - - override fun getEntrypointContainers( - key: String?, - type: Class? - ): MutableList> { - return mutableListOf() - } - - override fun getObjectShare(): ObjectShare? { - return null - } - - override fun getMappingResolver(): MappingResolver? { - return null - } - - override fun getModContainer(id: String): Optional { - return mods.stream().filter { it.metadata.id == id }.findFirst() - } - - override fun getAllMods(): MutableCollection { - return mods - } - - override fun isModLoaded(id: String?): Boolean { - return false - } - - override fun isDevelopmentEnvironment(): Boolean { - return true - } - - override fun getEnvironmentType(): EnvType { - return EnvType.CLIENT - } - - override fun getGameInstance(): Any? { - return null - } - - override fun getGameDir(): Path { - TODO("Not yet implemented") - } - - override fun getGameDirectory(): File { - TODO("Not yet implemented") - } - - override fun getConfigDir(): Path { - TODO("Not yet implemented") - } - - override fun getConfigDirectory(): File { - TODO("Not yet implemented") - } - - override fun getLaunchArguments(sanitize: Boolean): Array { - return arrayOf() - } - -} diff --git a/src/test/java/net/modmanagermc/core/test/DummyMetadata.kt b/src/test/java/net/modmanagermc/core/test/DummyMetadata.kt deleted file mode 100644 index cea51e0..0000000 --- a/src/test/java/net/modmanagermc/core/test/DummyMetadata.kt +++ /dev/null @@ -1,77 +0,0 @@ -package net.modmanagermc.core.test - -import net.fabricmc.loader.api.Version -import net.fabricmc.loader.api.metadata.* -import java.util.* - -class DummyMetadata(private val modId: String, private val versionStr: String) : ModMetadata { - override fun getType(): String { - return "builtin" - } - - override fun getId(): String { - return modId - } - - override fun getProvides(): MutableCollection { - return mutableListOf() - } - - override fun getVersion(): Version { - return Version.parse(versionStr) - } - - override fun getEnvironment(): ModEnvironment { - return ModEnvironment.CLIENT - } - - override fun getDependencies(): MutableCollection { - return mutableListOf() - } - - override fun getName(): String { - return modId - } - - override fun getDescription(): String { - return "" - } - - override fun getAuthors(): MutableCollection { - return mutableListOf() - } - - override fun getContributors(): MutableCollection { - return mutableListOf() - } - - override fun getContact(): ContactInformation? { - return null - } - - override fun getLicense(): MutableCollection { - return mutableListOf() - } - - override fun getIconPath(size: Int): Optional { - return Optional.empty() - } - - override fun containsCustomValue(key: String?): Boolean { - return false - } - - override fun getCustomValue(key: String?): CustomValue? { - return null - } - - override fun getCustomValues(): MutableMap { - return mutableMapOf() - } - - @Deprecated("Deprecated in Java", ReplaceWith("")) - override fun containsCustomElement(key: String?): Boolean { - return false - } - -} diff --git a/src/main/kotlin/net/modmanagermc/core/store/provider/modrinth/models/SearchResponse.kt b/src/test/kotlin/xyz/deathsgun/modmanager/core/dummy/DummyMod.kt similarity index 56% rename from src/main/kotlin/net/modmanagermc/core/store/provider/modrinth/models/SearchResponse.kt rename to src/test/kotlin/xyz/deathsgun/modmanager/core/dummy/DummyMod.kt index 838594a..ae2b6a9 100644 --- a/src/main/kotlin/net/modmanagermc/core/store/provider/modrinth/models/SearchResponse.kt +++ b/src/test/kotlin/xyz/deathsgun/modmanager/core/dummy/DummyMod.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 DeathsGun + * Copyright 2022 ModManagerMC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,11 +14,23 @@ * limitations under the License. */ -package net.modmanagermc.core.store.provider.modrinth.models +package xyz.deathsgun.modmanager.core.dummy import kotlinx.serialization.Serializable +import xyz.deathsgun.modmanager.core.api.mod.Mod @Serializable -data class SearchResponse( - val hits: List, -) +data class DummyMod( + val id: String, + val slug: String, + var author: String?, + val name: String, + var shortDescription: String, + val iconUrl: String?, + var description: String?, + val license: String?, +) { + fun toMod(): Mod { + return Mod(id, slug, author, name, shortDescription, iconUrl, description, license, emptyList()) + } +} diff --git a/src/test/kotlin/xyz/deathsgun/modmanager/core/dummy/DummyUtil.kt b/src/test/kotlin/xyz/deathsgun/modmanager/core/dummy/DummyUtil.kt new file mode 100644 index 0000000..ef5b73a --- /dev/null +++ b/src/test/kotlin/xyz/deathsgun/modmanager/core/dummy/DummyUtil.kt @@ -0,0 +1,37 @@ +/* + * Copyright 2022 ModManagerMC + * + * 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 + * + * http://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. + */ + +package xyz.deathsgun.modmanager.core.dummy + +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.decodeFromStream +import xyz.deathsgun.modmanager.core.api.mod.Mod + +@OptIn(ExperimentalSerializationApi::class) +object DummyUtil { + + private val json = Json { + ignoreUnknownKeys = true + } + + fun getDummyMod(): Mod? { + val dummyJson = DummyUtil::class.java.getResourceAsStream("/dummy_mod.json") ?: return null + return json.decodeFromStream(dummyJson).toMod() + } + + +} \ No newline at end of file diff --git a/src/test/kotlin/xyz/deathsgun/modmanager/core/gui/controller/ConfigControllerTest.kt b/src/test/kotlin/xyz/deathsgun/modmanager/core/gui/controller/ConfigControllerTest.kt new file mode 100644 index 0000000..e23ef41 --- /dev/null +++ b/src/test/kotlin/xyz/deathsgun/modmanager/core/gui/controller/ConfigControllerTest.kt @@ -0,0 +1,80 @@ +/* + * Copyright 2022 ModManagerMC + * + * 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 + * + * http://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. + */ + +package xyz.deathsgun.modmanager.core.gui.controller + +import org.junit.jupiter.api.AfterAll +import org.junit.jupiter.api.BeforeAll +import org.junit.jupiter.api.Test +import xyz.deathsgun.modmanager.core.ModManager +import xyz.deathsgun.modmanager.core.config.Config +import java.nio.file.Files +import java.nio.file.Paths +import java.util.* +import kotlin.test.assertEquals +import kotlin.test.assertNotEquals +import kotlin.test.assertTrue + +internal class ConfigControllerTest { + + companion object { + @BeforeAll + @JvmStatic + fun setUp() { + ModManager.init(Properties()) + } + + @AfterAll + @JvmStatic + fun tearDown() { + Paths.get("config", "modmanager", "modmanager.json").toFile().delete() + } + } + + @Test + fun saveConfig() { + assertTrue(Files.exists(Paths.get("config", "modmanager", "modmanager.json"))) + val localController = ConfigController() + assertEquals(ModManager.config.defaultProvider, localController.provider) + assertEquals(ModManager.config.hidden, localController.hidden) + assertEquals(ModManager.config.updateChannel, localController.updateChannel) + + localController.hidden.add("sodium") + localController.provider = "curseforge" + localController.updateChannel = Config.UpdateChannel.STABLE + assertNotEquals(localController.hidden, ModManager.config.hidden) + assertNotEquals(localController.provider, ModManager.config.defaultProvider) + assertNotEquals(localController.updateChannel, ModManager.config.updateChannel) + + localController.saveConfig() + assertEquals(localController.hidden, ModManager.config.hidden) + assertEquals(localController.provider, ModManager.config.defaultProvider) + assertEquals(localController.updateChannel, ModManager.config.updateChannel) + } + + @Test + fun nextChannel() { + ModManager.config = Config() + val controller = ConfigController() + controller.updateChannel = Config.UpdateChannel.values()[0] + for (k in 0..3) { + for (i in 0 until Config.UpdateChannel.values().size) { + assertEquals(Config.UpdateChannel.values()[i], controller.updateChannel) + controller.nextChannel() + } + } + } +} \ No newline at end of file diff --git a/src/test/kotlin/xyz/deathsgun/modmanager/core/icon/IconCacheTest.kt b/src/test/kotlin/xyz/deathsgun/modmanager/core/icon/IconCacheTest.kt new file mode 100644 index 0000000..fe25af0 --- /dev/null +++ b/src/test/kotlin/xyz/deathsgun/modmanager/core/icon/IconCacheTest.kt @@ -0,0 +1,91 @@ +/* + * Copyright 2022 ModManagerMC + * + * 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 + * + * http://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. + */ + +package xyz.deathsgun.modmanager.core.icon + +import net.minecraft.util.Identifier +import org.apache.commons.io.FileUtils +import org.apache.commons.lang3.time.StopWatch +import org.junit.jupiter.api.AfterAll +import org.junit.jupiter.api.BeforeAll +import org.junit.jupiter.api.Test +import xyz.deathsgun.modmanager.core.dummy.DummyUtil +import java.io.File +import java.io.InputStream +import java.io.RandomAccessFile +import java.nio.file.Files +import java.util.concurrent.TimeUnit +import kotlin.test.assertContains +import kotlin.test.assertEquals +import kotlin.test.assertTrue +import kotlin.test.fail + +internal object IconCacheTest { + + private val cacheDirectory = File("test_icons").toPath() + + @BeforeAll + @JvmStatic + fun setUp() { + IconCache.init(cacheDirectory, this::iconLoader) + } + + @Test + fun get() { + val mod = DummyUtil.getDummyMod() ?: fail("Couldn't load dummy mod data!") + var identifier: Identifier + val stopWatch = StopWatch() + while (true) { + identifier = IconCache.get(mod) + if (identifier.path.contains(mod.id, ignoreCase = true)) { + break + } + if (identifier.namespace == "minecraft") { + fail("Error while loading icon check the log for details") + } + if (!stopWatch.isStarted) { + stopWatch.start() + } + if (stopWatch.time >= 5000) { + stopWatch.stop() + fail("Retrieving the icon took longer than ${stopWatch.getTime(TimeUnit.SECONDS)} seconds!") + } + } + assertEquals("modmanager", identifier.namespace) + assertContains("mod_icons/${mod.id}", identifier.path, ignoreCase = true) + assert(Files.exists(cacheDirectory.resolve(mod.id))) + } + + @Test + fun clear() { + val f = RandomAccessFile(cacheDirectory.resolve("bigFile").toFile(), "rw") + f.setLength((1024 * 1024 * 20).toLong()) + f.close() + IconCache.clean() + assertTrue(Files.notExists(cacheDirectory.resolve("bigFile"))) + assertTrue(FileUtils.sizeOfDirectory(cacheDirectory.toFile()) <= 10000000, "Directory caching has not worked!") + } + + @AfterAll + @JvmStatic + fun tearDown() { + cacheDirectory.toFile().deleteRecursively() + } + + private fun iconLoader(stream: InputStream) { + stream.close() + } +} \ No newline at end of file diff --git a/src/test/kotlin/xyz/deathsgun/modmanager/core/modrinth/ModrinthTest.kt b/src/test/kotlin/xyz/deathsgun/modmanager/core/modrinth/ModrinthTest.kt new file mode 100644 index 0000000..862223c --- /dev/null +++ b/src/test/kotlin/xyz/deathsgun/modmanager/core/modrinth/ModrinthTest.kt @@ -0,0 +1,145 @@ +/* + * Copyright 2021-2022 ModManagerMC + * + * 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 + * + * http://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. + */ + +package xyz.deathsgun.modmanager.core.modrinth + +import net.minecraft.text.TranslatableText +import org.junit.jupiter.api.BeforeAll +import org.junit.jupiter.api.Test +import xyz.deathsgun.modmanager.core.ModManager +import xyz.deathsgun.modmanager.core.api.Category +import xyz.deathsgun.modmanager.core.api.http.CategoriesResult +import xyz.deathsgun.modmanager.core.api.http.ModResult +import xyz.deathsgun.modmanager.core.api.http.ModsResult +import xyz.deathsgun.modmanager.core.api.mod.Mod +import xyz.deathsgun.modmanager.core.api.provider.Sorting +import java.util.* + +import kotlin.test.* + +internal class ModrinthTest { + + private val modrinth = Modrinth() + + companion object { + @BeforeAll + @JvmStatic + fun setup() { + val properties = Properties() + properties.setProperty("version.target", "1.18") + properties.setProperty("version.minecraft", "1.18.1") + ModManager.init(properties) + } + } + + @Test + fun getCategories() { + val result = modrinth.getCategories() + if (result is CategoriesResult.Error) { + fail("Failed to retrieve categories", result.cause) + } + val categories = (result as CategoriesResult.Success).categories + assertTrue(categories.isNotEmpty()) + categories.forEach { + assertTrue(it.id.isNotEmpty()) + assertEquals(String.format("modmanager.category.%s", it.id), it.text.key) + assertNotEquals("fabric", it.id) + assertNotEquals("forge", it.id) + } + } + @Test + fun getModsBySorting() { + val result = modrinth.getMods(Sorting.NEWEST, 0, 10) + if (result is ModsResult.Error) { + result.cause?.let { + fail(result.text.key, it) + } + fail(result.text.key) + } + val mods = (result as ModsResult.Success).mods + checkMods(mods) + } + + @Test + fun getModsByCategory() { + val result = modrinth.getMods(listOf(Category("misc", TranslatableText(""))), Sorting.RELEVANCE, 0, 10) + if (result is ModsResult.Error) { + result.cause?.let { + fail(result.text.key, it) + } + fail(result.text.key) + } + val mods = (result as ModsResult.Success).mods + checkMods(mods) + } + + @Test + fun getModsByQuery() { + val result = modrinth.search("Mod", emptyList(), Sorting.DOWNLOADS, 0, 10) + if (result is ModsResult.Error) { + result.cause?.let { + fail(result.text.key, it) + } + fail(result.text.key) + } + val mods = (result as ModsResult.Success).mods + checkMods(mods) + } + + private fun checkMods(mods: List, modsMode: Boolean = true) { + assertTrue(mods.isNotEmpty()) + if (modsMode) { + assertEquals(mods.size, 10) + } + mods.forEach { + assertTrue(it.id.isNotEmpty()) + assertTrue(it.slug.isNotEmpty()) + assertTrue(it.name.isNotEmpty()) + assertNotNull(it.iconUrl) + assertTrue(it.shortDescription.isNotEmpty()) + assertTrue(it.categories.isNotEmpty()) + + if (modsMode) { + assertNotNull(it.author) + // Only filled when getMod(id) is called + assertNull(it.description, "description should be null as it's only loaded by getMod") + assertNull(it.license, "description should be null as it's only loaded by getMod") + return@forEach + } + assertNotNull(it.description, "description shouldn't be null as it's loaded by getMod") + assertNotNull(it.license, "license shouldn't be null as it's loaded by getMod") + } + } + + @Test + fun getMod() { + val testMod = modrinth.getMods(Sorting.NEWEST, 0, 1) + if (testMod is ModsResult.Error) { + testMod.cause?.let { + fail(testMod.text.key, it) + } + fail(testMod.text.key) + } + val result = modrinth.getMod((testMod as ModsResult.Success).mods[0].id) + if (result is ModResult.Error) { + result.cause?.let { + fail(result.text.key, it) + } + fail(result.text.key) + } + checkMods(listOf((result as ModResult.Success).mod), false) + } +} \ No newline at end of file diff --git a/src/test/resources/dummy_mod.json b/src/test/resources/dummy_mod.json new file mode 100644 index 0000000..41c8515 --- /dev/null +++ b/src/test/resources/dummy_mod.json @@ -0,0 +1,10 @@ +{ + "id": "6kq7BzRK", + "slug": "modmanager", + "name": "Mod Manager", + "author": "", + "shortDescription": "An extension for Mod Menu which allows you to manage your mods in game", + "iconUrl": "https://cdn.modrinth.com/data/6kq7BzRK/icon.png", + "description": "", + "license": "Apache License 2.0" +} \ No newline at end of file diff --git a/src/test/resources/fabric.mod.json b/src/test/resources/fabric.mod.json deleted file mode 100644 index 999f6b8..0000000 --- a/src/test/resources/fabric.mod.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "schemaVersion": 1, - "id": "core-test", - "name": "ModManager Core", - "version": "1.0", - "authors": [ - "DeathsGun" - ] -} \ No newline at end of file