├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── changelog.md ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src └── main ├── java └── net │ └── replaceitem │ └── scarpet │ └── additions │ ├── HttpUtils.java │ ├── ScarpetAdditions.java │ ├── ScarpetFunctions.java │ └── mixins │ └── ServerMetadataMixin.java └── resources ├── assets └── scarpet-additions │ └── icon.png ├── fabric.mod.json └── scarpet-additions.mixins.json /.gitignore: -------------------------------------------------------------------------------- 1 | # gradle 2 | 3 | .gradle/ 4 | build/ 5 | out/ 6 | classes/ 7 | 8 | # idea 9 | 10 | .idea/ 11 | *.iml 12 | *.ipr 13 | *.iws 14 | 15 | # vscode 16 | 17 | .settings/ 18 | .vscode/ 19 | bin/ 20 | .classpath 21 | .project 22 | 23 | # fabric 24 | 25 | run/ 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 replaceitem 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # scarpet-additions 2 | 3 | [Available for fabric](https://fabricmc.net/) 4 | [See me on GitHub](https://github.com/replaceitem) 5 | [Available on Modrinth](https://modrinth.com/mod/scarpet-additions) 6 | [Chat on Discord](https://discord.gg/etTDQAVSgt) 7 | 8 | ![scarpet-additions](https://raw.githubusercontent.com/replaceitem/scarpet-additions/master/src/main/resources/assets/scarpet-additions/icon.png) 9 | 10 | ## A [Carpet mod](https://modrinth.com/mod/carpet) extension for some additional [scarpet](https://github.com/gnembon/fabric-carpet/wiki/Scarpet) functions 11 | 12 | **Reqires [Carpet mod](https://modrinth.com/mod/carpet)** 13 | 14 | ## Functions 15 | 16 | ### `convert_color(color,model,output)` 17 | 18 | Converts a color from one `model` to another. 19 | 20 | `color` -> List: Depending on specified `model` 21 | 22 | `model` -> String: Input color model, can be `RGB`, `RGBA` or `HSB` 23 | 24 | * RGB: List of a red, green and blue value 25 | * RGBA: List of a red, green, blue and alpha value 26 | * HSB: List of a hue, saturation and brightnes value 27 | 28 | `output` -> String: Output color model, can be `RGB`, `RGBA`, `HEX` or `NUM` 29 | 30 | * RGB: List of a red, green and blue value 31 | * RGBA: List of a red, green, blue and alpha value 32 | * HEX: String of hex characters (without leading '#') Can be used for `format()` 33 | * NUM: Number representing the color as 4 bytes: 0xRRGGBBAA. Can be used for `'color'` parameter in `draw_shape()` 34 | 35 | Examples: 36 | 37 | `convert_color([255,128,0],'rgb','hex');` -> `'FF8000'` 38 | 39 | `convert_color([255,128,0],'rgb','num');` -> `0xff7f00ff` 40 | 41 | `convert_color([0,255,255],'hsb','hex');` -> `'FF0000'` 42 | 43 | `convert_color([120,255,255],'hsb','hex');` -> `'00FF00'` 44 | 45 | Example: 46 | 47 | ```py 48 | __on_tick() -> ( 49 | if((tick_time() % 2) == 0, 50 | headerHue = tick_time()%360; 51 | headerGlossIndex = (floor(tick_time()/3)%40)-10; 52 | header = []; 53 | title = 'MinecraftServer'; 54 | for(range(length(title)), 55 | if(abs(_-headerGlossIndex) < 3, 56 | c = convert_color([headerHue,abs(_-headerGlossIndex)/3*255,255],'hsb','hex'); 57 | , 58 | if(_ < 7, 59 | c = convert_color([headerHue,255,190],'hsb','hex'); 60 | , 61 | c = convert_color([headerHue,255,255],'hsb','hex'); 62 | ); 63 | ); 64 | put(header,null,str('b#%s %s',c,slice(title,_,_+1))); 65 | ); 66 | header = format(header); 67 | footer = format('r to the server!'); 68 | set_tab_text(header,footer); 69 | ) 70 | ); 71 | ``` 72 | 73 | ### `http_request(options)` 74 | 75 | Performs a http request specified by the given `options`. 76 | 77 | This call is blocking, so you should use it in a `task()`! 78 | 79 | The `options` parameter is a map value with the following keys: 80 | 81 | * `uri` (String): The URI to request from 82 | * `method` (String, optional): The http request method. For example `GET`, `POST`, `DELETE`,... Defaults to `GET` 83 | * `headers` (Map, optional): Each map entry is a string key pointing to a string, or list of strings 84 | * `body` (String): The body for `POST` or other requests 85 | 86 | The function returns a map with the following entries: 87 | 88 | * `status_code` (number): The status code of the request 89 | * `body` (String): The body returned from the request 90 | * `headers` (Map: string -> [strings]): The received response headers 91 | * `uri` (String): The originally requested URI 92 | 93 | When the request fails, a `http_request_error` exception is thrown, which can be caught with `try()`. 94 | This is only for actual failures to make the request (such as a network error). 95 | Successful requests with a 400 or 500 status code will not throw an exception. 96 | 97 | Note that the response body is not parsed as json or html escaped. 98 | Use the `escape_html` and `unescape_html` functions, 99 | as well as the scarpet-builtins `encode_json` and `decode_json`. 100 | 101 | 102 | Example usage: 103 | 104 | ```js 105 | // simple get request and parsing 106 | 107 | response = http_request({ 108 | 'uri'->'https://opentdb.com/api.php?amount=1' 109 | }); 110 | 111 | print('Response: ' + response); 112 | 113 | if(response:'status_code' != 200, 114 | print('Request failed: ' + response:'status_code'); 115 | , 116 | body = decode_json(response:'body'); 117 | print('\n\nBody: ' + body); 118 | 119 | question_data = body:'results':0; 120 | question = unescape_html(question_data:'question'); 121 | answer = unescape_html(question_data:'correct_answer'); 122 | 123 | print('\n\n\n' + question + '\n' + answer); 124 | ); 125 | ``` 126 | 127 | ### `escape_html(html)` 128 | 129 | Returns the escaped html string (e.g. `"` -> `"`) 130 | 131 | ### `unescape_html(html)` 132 | 133 | Returns the unescaped html string (e.g. `"` -> `"`) 134 | 135 | ### `list_text(header, footer, player?)` 136 | 137 | Sets header and footer in tab menu of all players, or changes it for one player if `player?` is given. 138 | 139 | ### `set_motd(motd)` 140 | 141 | Sets the message of the day of the server. 142 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'fabric-loom' version '1.8-SNAPSHOT' 3 | id 'maven-publish' 4 | id "com.modrinth.minotaur" version "2.+" 5 | } 6 | 7 | repositories { 8 | maven { 9 | url 'https://masa.dy.fi/maven' 10 | } 11 | mavenCentral() 12 | } 13 | 14 | sourceCompatibility = JavaVersion.VERSION_21 15 | targetCompatibility = JavaVersion.VERSION_21 16 | 17 | archivesBaseName = project.archives_base_name 18 | version = project.minecraft_version+'-'+project.mod_version 19 | group = project.maven_group 20 | 21 | dependencies { 22 | minecraft "com.mojang:minecraft:${project.minecraft_version}" 23 | mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2" 24 | modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" 25 | modImplementation "carpet:fabric-carpet:${project.carpet_minecraft_version}-${project.carpet_core_version}" 26 | implementation 'org.apache.commons:commons-text:1.9' 27 | include 'org.apache.commons:commons-text:1.9' 28 | } 29 | 30 | processResources { 31 | inputs.property "version", project.version 32 | 33 | filesMatching("fabric.mod.json") { 34 | expand "version": project.mod_version 35 | } 36 | } 37 | 38 | tasks.withType(JavaCompile).configureEach { 39 | it.options.encoding = "UTF-8" 40 | it.options.release = 21 41 | } 42 | 43 | java { 44 | withSourcesJar() 45 | } 46 | 47 | jar { 48 | from("LICENSE") { 49 | rename { "${it}_${project.archivesBaseName}"} 50 | } 51 | } 52 | 53 | import com.modrinth.minotaur.dependencies.ModDependency 54 | 55 | modrinth { 56 | token = System.getenv("MODRINTH_TOKEN") 57 | projectId = "vXQQF1r2" 58 | versionNumber = project.mod_version 59 | versionType = "release" 60 | uploadFile = remapJar 61 | loaders = ["fabric"] 62 | dependencies = [ 63 | // carpet 64 | new ModDependency("TQTTVgYE" ,"required") 65 | ] 66 | changelog = rootProject.file("changelog.md").text 67 | syncBodyFrom = rootProject.file("README.md").text 68 | } 69 | -------------------------------------------------------------------------------- /changelog.md: -------------------------------------------------------------------------------- 1 | * http requests failing will now throw a custom scarpet exception type `http_request_error` 2 | * -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Done to increase the memory available to gradle. 2 | org.gradle.jvmargs=-Xmx1G 3 | 4 | # Fabric Properties 5 | minecraft_version=1.21.4 6 | yarn_mappings=1.21.4+build.1 7 | loader_version=0.16.9 8 | 9 | carpet_minecraft_version=1.21.4 10 | carpet_core_version=1.4.161+v241203 11 | 12 | # Mod Properties 13 | 14 | mod_version = 1.1.3 15 | maven_group = net.replaceitem 16 | archives_base_name = scarpet-additions -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/replaceitem/scarpet-additions/01ca3c1c6ba51a73b377a66c55918d5012e1fc44/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s 90 | ' "$PWD" ) || exit 91 | 92 | # Use the maximum available, or set MAX_FD != -1 to use that value. 93 | MAX_FD=maximum 94 | 95 | warn () { 96 | echo "$*" 97 | } >&2 98 | 99 | die () { 100 | echo 101 | echo "$*" 102 | echo 103 | exit 1 104 | } >&2 105 | 106 | # OS specific support (must be 'true' or 'false'). 107 | cygwin=false 108 | msys=false 109 | darwin=false 110 | nonstop=false 111 | case "$( uname )" in #( 112 | CYGWIN* ) cygwin=true ;; #( 113 | Darwin* ) darwin=true ;; #( 114 | MSYS* | MINGW* ) msys=true ;; #( 115 | NONSTOP* ) nonstop=true ;; 116 | esac 117 | 118 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 119 | 120 | 121 | # Determine the Java command to use to start the JVM. 122 | if [ -n "$JAVA_HOME" ] ; then 123 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 124 | # IBM's JDK on AIX uses strange locations for the executables 125 | JAVACMD=$JAVA_HOME/jre/sh/java 126 | else 127 | JAVACMD=$JAVA_HOME/bin/java 128 | fi 129 | if [ ! -x "$JAVACMD" ] ; then 130 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 131 | 132 | Please set the JAVA_HOME variable in your environment to match the 133 | location of your Java installation." 134 | fi 135 | else 136 | JAVACMD=java 137 | if ! command -v java >/dev/null 2>&1 138 | then 139 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 140 | 141 | Please set the JAVA_HOME variable in your environment to match the 142 | location of your Java installation." 143 | fi 144 | fi 145 | 146 | # Increase the maximum file descriptors if we can. 147 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 148 | case $MAX_FD in #( 149 | max*) 150 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 151 | # shellcheck disable=SC2039,SC3045 152 | MAX_FD=$( ulimit -H -n ) || 153 | warn "Could not query maximum file descriptor limit" 154 | esac 155 | case $MAX_FD in #( 156 | '' | soft) :;; #( 157 | *) 158 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 159 | # shellcheck disable=SC2039,SC3045 160 | ulimit -n "$MAX_FD" || 161 | warn "Could not set maximum file descriptor limit to $MAX_FD" 162 | esac 163 | fi 164 | 165 | # Collect all arguments for the java command, stacking in reverse order: 166 | # * args from the command line 167 | # * the main class name 168 | # * -classpath 169 | # * -D...appname settings 170 | # * --module-path (only if needed) 171 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 172 | 173 | # For Cygwin or MSYS, switch paths to Windows format before running java 174 | if "$cygwin" || "$msys" ; then 175 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 176 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 177 | 178 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 179 | 180 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 181 | for arg do 182 | if 183 | case $arg in #( 184 | -*) false ;; # don't mess with options #( 185 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 186 | [ -e "$t" ] ;; #( 187 | *) false ;; 188 | esac 189 | then 190 | arg=$( cygpath --path --ignore --mixed "$arg" ) 191 | fi 192 | # Roll the args list around exactly as many times as the number of 193 | # args, so each arg winds up back in the position where it started, but 194 | # possibly modified. 195 | # 196 | # NB: a `for` loop captures its iteration list before it begins, so 197 | # changing the positional parameters here affects neither the number of 198 | # iterations, nor the values presented in `arg`. 199 | shift # remove old arg 200 | set -- "$@" "$arg" # push replacement arg 201 | done 202 | fi 203 | 204 | 205 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 206 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 207 | 208 | # Collect all arguments for the java command: 209 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 210 | # and any embedded shellness will be escaped. 211 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 212 | # treated as '${Hostname}' itself on the command line. 213 | 214 | set -- \ 215 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 216 | -classpath "$CLASSPATH" \ 217 | org.gradle.wrapper.GradleWrapperMain \ 218 | "$@" 219 | 220 | # Stop when "xargs" is not available. 221 | if ! command -v xargs >/dev/null 2>&1 222 | then 223 | die "xargs is not available" 224 | fi 225 | 226 | # Use "xargs" to parse quoted args. 227 | # 228 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 229 | # 230 | # In Bash we could simply go: 231 | # 232 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 233 | # set -- "${ARGS[@]}" "$@" 234 | # 235 | # but POSIX shell has neither arrays nor command substitution, so instead we 236 | # post-process each arg (as a line of input to sed) to backslash-escape any 237 | # character that might be a shell metacharacter, then use eval to reverse 238 | # that process (while maintaining the separation between arguments), and wrap 239 | # the whole thing up as a single "set" statement. 240 | # 241 | # This will of course break if any of these variables contains a newline or 242 | # an unmatched quote. 243 | # 244 | 245 | eval "set -- $( 246 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 247 | xargs -n1 | 248 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 249 | tr '\n' ' ' 250 | )" '"$@"' 251 | 252 | exec "$JAVACMD" "$@" 253 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 74 | 75 | 76 | @rem Execute Gradle 77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 78 | 79 | :end 80 | @rem End local scope for the variables with windows NT shell 81 | if %ERRORLEVEL% equ 0 goto mainEnd 82 | 83 | :fail 84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 85 | rem the _cmd.exe /c_ return code! 86 | set EXIT_CODE=%ERRORLEVEL% 87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 89 | exit /b %EXIT_CODE% 90 | 91 | :mainEnd 92 | if "%OS%"=="Windows_NT" endlocal 93 | 94 | :omega 95 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | jcenter() 4 | maven { 5 | name = 'Fabric' 6 | url = 'https://maven.fabricmc.net/' 7 | } 8 | gradlePluginPortal() 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/net/replaceitem/scarpet/additions/HttpUtils.java: -------------------------------------------------------------------------------- 1 | package net.replaceitem.scarpet.additions; 2 | 3 | import carpet.script.exception.InternalExpressionException; 4 | import carpet.script.exception.ThrowStatement; 5 | import carpet.script.value.*; 6 | 7 | import java.io.IOException; 8 | import java.net.URI; 9 | import java.net.http.HttpClient; 10 | import java.net.http.HttpRequest; 11 | import java.net.http.HttpResponse; 12 | import java.util.HashMap; 13 | import java.util.List; 14 | import java.util.Map; 15 | import java.util.Set; 16 | 17 | public class HttpUtils { 18 | 19 | public static HttpClient client = HttpClient.newBuilder().build(); 20 | 21 | public static Value httpRequest(Map options) { 22 | HttpRequest.Builder builder = HttpRequest.newBuilder(); 23 | 24 | String uri = getOption(options, "uri", true).getString(); 25 | builder.uri(URI.create(uri)); 26 | 27 | Value methodValue = getOption(options, "method", false); 28 | String method = methodValue == null ? "GET" : methodValue.getString(); 29 | 30 | Value bodyValue = getOption(options, "body", false); 31 | HttpRequest.BodyPublisher bodyPublisher; 32 | if(bodyValue == null) { 33 | bodyPublisher = HttpRequest.BodyPublishers.noBody(); 34 | } else { 35 | bodyPublisher = HttpRequest.BodyPublishers.ofString(bodyValue.getString()); 36 | } 37 | builder.method(method, bodyPublisher); 38 | 39 | Value headerValue = getOption(options, "headers", false); 40 | if(headerValue != null) { 41 | if(!(headerValue instanceof MapValue headerMapValue)) throw new InternalExpressionException("'headers' needs to be a map"); 42 | Map header = headerMapValue.getMap(); 43 | for (Map.Entry entry : header.entrySet()) { 44 | String keyString = entry.getKey().getString(); 45 | Value value = entry.getValue(); 46 | if (value instanceof ListValue listValue) { 47 | for (Value listVal : listValue) { 48 | builder.header(keyString, listVal.getString()); 49 | } 50 | } else { 51 | builder.header(keyString, value.getString()); 52 | } 53 | } 54 | } 55 | 56 | HttpRequest request = builder.build(); 57 | 58 | HttpResponse response; 59 | try { 60 | response = client.send(request, HttpResponse.BodyHandlers.ofString()); 61 | } catch (IOException | InterruptedException e) { 62 | ScarpetAdditions.LOGGER.error("Error sending http request", e); 63 | throw new ThrowStatement("Error sending http request: " + e.getMessage(), ScarpetAdditions.HTTP_REQUEST_ERROR); 64 | } 65 | 66 | Map responseMap = new HashMap<>(); 67 | responseMap.put(StringValue.of("status_code"), NumericValue.of(response.statusCode())); 68 | responseMap.put(StringValue.of("body"), StringValue.of(response.body())); 69 | 70 | Set>> headerEntries = response.headers().map().entrySet(); 71 | Map headersValueMap = new HashMap<>(); 72 | for (Map.Entry> headerEntry : headerEntries) { 73 | headersValueMap.put(StringValue.of(headerEntry.getKey()), ListValue.wrap(headerEntry.getValue().stream().map(StringValue::of))); 74 | } 75 | responseMap.put(StringValue.of("headers"), MapValue.wrap(headersValueMap)); 76 | responseMap.put(StringValue.of("uri"), StringValue.of(response.uri().toString())); 77 | 78 | return MapValue.wrap(responseMap); 79 | } 80 | 81 | private static Value getOption(Map options, String key, boolean required) { 82 | Value value = options.get(StringValue.of(key)); 83 | if(required && value == null) throw new InternalExpressionException("Missing '" + key + "' value for http request"); 84 | return value; 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/main/java/net/replaceitem/scarpet/additions/ScarpetAdditions.java: -------------------------------------------------------------------------------- 1 | package net.replaceitem.scarpet.additions; 2 | 3 | import carpet.CarpetExtension; 4 | import carpet.CarpetServer; 5 | import carpet.script.CarpetExpression; 6 | import carpet.script.annotation.AnnotationParser; 7 | import carpet.script.exception.Throwables; 8 | import com.mojang.brigadier.CommandDispatcher; 9 | import net.fabricmc.api.ModInitializer; 10 | import net.minecraft.command.CommandRegistryAccess; 11 | import net.minecraft.server.MinecraftServer; 12 | import net.minecraft.server.command.ServerCommandSource; 13 | import net.minecraft.server.network.ServerPlayerEntity; 14 | import net.minecraft.text.Text; 15 | import org.apache.logging.log4j.LogManager; 16 | import org.apache.logging.log4j.Logger; 17 | 18 | public class ScarpetAdditions implements CarpetExtension, ModInitializer { 19 | public static final Logger LOGGER = LogManager.getLogger("scarpet-additions"); 20 | public static Text MOTD = null; 21 | 22 | public static final Throwables HTTP_REQUEST_ERROR = Throwables.register("http_request_error", Throwables.IO_EXCEPTION); 23 | 24 | @Override 25 | public void onInitialize() { 26 | CarpetServer.manageExtension(new ScarpetAdditions()); 27 | LOGGER.info("Scarpet-additions loaded"); 28 | } 29 | 30 | @Override 31 | public void onGameStarted() { 32 | AnnotationParser.parseFunctionClass(ScarpetFunctions.class); 33 | } 34 | 35 | @Override 36 | public void onServerLoaded(MinecraftServer server) { 37 | 38 | } 39 | 40 | @Override 41 | public void onTick(MinecraftServer server) { 42 | } 43 | 44 | @Override 45 | public void registerCommands(CommandDispatcher dispatcher, CommandRegistryAccess commandBuildContext) { 46 | } 47 | 48 | @Override 49 | public carpet.api.settings.SettingsManager extensionSettingsManager() { 50 | return null; 51 | } 52 | 53 | @Override 54 | public void onPlayerLoggedIn(ServerPlayerEntity player) { 55 | } 56 | 57 | @Override 58 | public void onPlayerLoggedOut(ServerPlayerEntity player) { 59 | } 60 | 61 | @Override 62 | public void scarpetApi(CarpetExpression expression) { 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/net/replaceitem/scarpet/additions/ScarpetFunctions.java: -------------------------------------------------------------------------------- 1 | package net.replaceitem.scarpet.additions; 2 | 3 | import carpet.script.CarpetContext; 4 | import carpet.script.Context; 5 | import carpet.script.annotation.ScarpetFunction; 6 | import carpet.script.exception.InternalExpressionException; 7 | import carpet.script.value.EntityValue; 8 | import carpet.script.value.FormattedTextValue; 9 | import carpet.script.value.ListValue; 10 | import carpet.script.value.NumericValue; 11 | import carpet.script.value.StringValue; 12 | import carpet.script.value.Value; 13 | import net.minecraft.network.packet.s2c.play.PlayerListHeaderS2CPacket; 14 | import net.minecraft.server.MinecraftServer; 15 | import net.minecraft.server.network.ServerPlayerEntity; 16 | import net.minecraft.text.Text; 17 | import org.apache.commons.text.StringEscapeUtils; 18 | 19 | import java.awt.*; 20 | import java.util.List; 21 | import java.util.Map; 22 | 23 | @SuppressWarnings("unused") 24 | public class ScarpetFunctions { 25 | 26 | @ScarpetFunction 27 | public void set_motd(Context c, Value text) { 28 | if(text == null || text.isNull()) { 29 | ScarpetAdditions.MOTD = null; 30 | } else { 31 | ScarpetAdditions.MOTD = FormattedTextValue.getTextByValue(text); 32 | } 33 | } 34 | 35 | 36 | @ScarpetFunction 37 | public Value convert_color(Value input, String model, String out) { 38 | if(!(input instanceof ListValue)) throw new InternalExpressionException("'convert_color' requires a List as the first argument"); 39 | 40 | List col = ((ListValue) input).getItems(); 41 | 42 | Color color; 43 | 44 | if(model.equalsIgnoreCase("RGB")) { 45 | if(col.size() == 3) { 46 | float v1 = (float)(col.get(0) instanceof NumericValue?((NumericValue) col.get(0)).getInt():0); 47 | float v2 = (float)(col.get(1) instanceof NumericValue?((NumericValue) col.get(1)).getInt():0); 48 | float v3 = (float)(col.get(2) instanceof NumericValue?((NumericValue) col.get(2)).getInt():0); 49 | 50 | color = new Color(v1/255,v2/255,v3/255); 51 | } else 52 | throw new InternalExpressionException("Color model " + model + " needs a List of three values as the first argument"); 53 | } else if (model.equalsIgnoreCase("RGBA")) { 54 | if(col.size() == 4) { 55 | float v1 = (float)(col.get(0) instanceof NumericValue?((NumericValue) col.get(0)).getInt():0); 56 | float v2 = (float)(col.get(1) instanceof NumericValue?((NumericValue) col.get(1)).getInt():0); 57 | float v3 = (float)(col.get(2) instanceof NumericValue?((NumericValue) col.get(2)).getInt():0); 58 | float v4 = (float)(col.get(3) instanceof NumericValue?((NumericValue) col.get(3)).getInt():0); 59 | 60 | color = new Color(v1/255,v2/255,v3/255,v4/255); 61 | } else 62 | throw new InternalExpressionException("Color model " + model + " needs a List of four values as the first argument"); 63 | } else if (model.equalsIgnoreCase("HSB")) { 64 | if(col.size() == 3) { 65 | float v1 = (float) (col.get(0) instanceof NumericValue ? ((NumericValue) col.get(0)).getInt() : 0); 66 | float v2 = (float) (col.get(1) instanceof NumericValue ? ((NumericValue) col.get(1)).getInt() : 0); 67 | float v3 = (float) (col.get(2) instanceof NumericValue ? ((NumericValue) col.get(2)).getInt() : 0); 68 | 69 | color = Color.getHSBColor(v1 / 360, v2 / 255, v3 / 255); 70 | } else { 71 | throw new InternalExpressionException("Color model " + model + " needs a List of three values as the first argument"); 72 | } 73 | } else { 74 | throw new InternalExpressionException("Invalid input color model " + model); 75 | } 76 | 77 | if(out.equalsIgnoreCase("RGB")) { 78 | return ListValue.of(NumericValue.of(color.getRed()),NumericValue.of(color.getGreen()),NumericValue.of(color.getBlue())); 79 | } else if(out.equalsIgnoreCase("RGBA")) { 80 | return ListValue.of(NumericValue.of(color.getRed()),NumericValue.of(color.getGreen()),NumericValue.of(color.getBlue()),NumericValue.of(color.getAlpha())); 81 | } else if(out.equalsIgnoreCase("NUM")) { 82 | return NumericValue.of((((long)(color.getRGB() & 0xFFFFFF))<<8) | (color.getAlpha())); 83 | } else if(out.equalsIgnoreCase("HEX")) { 84 | return StringValue.of(String.format("%02X%02X%02X", color.getRed(), color.getGreen(), color.getBlue())); 85 | } else { 86 | throw new InternalExpressionException("Invalid output color model " + model); 87 | } 88 | } 89 | 90 | @ScarpetFunction 91 | public Value http_request(Map options) { 92 | return HttpUtils.httpRequest(options); 93 | } 94 | 95 | @ScarpetFunction 96 | public String escape_html(String html) { 97 | return StringEscapeUtils.escapeHtml4(html); 98 | } 99 | 100 | @ScarpetFunction 101 | public String unescape_html(String html) { 102 | return StringEscapeUtils.unescapeHtml4(html); 103 | } 104 | 105 | @ScarpetFunction(maxParams = 3) 106 | public void list_text(Context c, Value headerValue, Value footerValue, Value... optionalPlayer) { 107 | Text header = FormattedTextValue.getTextByValue(headerValue); 108 | Text footer = FormattedTextValue.getTextByValue(footerValue); 109 | PlayerListHeaderS2CPacket packet = new PlayerListHeaderS2CPacket(header, footer); 110 | MinecraftServer server = ((CarpetContext) c).server(); 111 | ServerPlayerEntity player = optionalPlayer.length == 1 ? EntityValue.getPlayerByValue(server, optionalPlayer[0]) : null; 112 | if (player == null) { 113 | server.getPlayerManager().sendToAll(packet); 114 | } else { 115 | player.networkHandler.sendPacket(packet); 116 | } 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/main/java/net/replaceitem/scarpet/additions/mixins/ServerMetadataMixin.java: -------------------------------------------------------------------------------- 1 | package net.replaceitem.scarpet.additions.mixins; 2 | 3 | import net.minecraft.server.ServerMetadata; 4 | import net.minecraft.text.Text; 5 | import net.replaceitem.scarpet.additions.ScarpetAdditions; 6 | import org.spongepowered.asm.mixin.Mixin; 7 | import org.spongepowered.asm.mixin.injection.At; 8 | import org.spongepowered.asm.mixin.injection.Inject; 9 | import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; 10 | 11 | @Mixin(ServerMetadata.class) 12 | public class ServerMetadataMixin { 13 | @Inject(method = "description", at = @At("HEAD"), cancellable = true) 14 | private void getScarpetMotd(CallbackInfoReturnable cir) { 15 | if(ScarpetAdditions.MOTD != null) cir.setReturnValue(ScarpetAdditions.MOTD); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/resources/assets/scarpet-additions/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/replaceitem/scarpet-additions/01ca3c1c6ba51a73b377a66c55918d5012e1fc44/src/main/resources/assets/scarpet-additions/icon.png -------------------------------------------------------------------------------- /src/main/resources/fabric.mod.json: -------------------------------------------------------------------------------- 1 | { 2 | "schemaVersion": 1, 3 | "id": "scarpet-additions", 4 | "version": "${version}", 5 | 6 | "name": "Scarpet Additions", 7 | "description": "Adds a couple scarpet functions", 8 | "authors": [ 9 | "replaceitem" 10 | ], 11 | "contact": { 12 | "homepage": "https://github.com/replaceitem", 13 | "sources": "https://github.com/replaceitem/scarpet-additions" 14 | }, 15 | 16 | "license": "MIT", 17 | "icon": "assets/scarpet-additions/icon.png", 18 | 19 | "environment": "*", 20 | "entrypoints": { 21 | "main": [ 22 | "net.replaceitem.scarpet.additions.ScarpetAdditions" 23 | ] 24 | }, 25 | "mixins": [ 26 | "scarpet-additions.mixins.json" 27 | ], 28 | 29 | "depends": { 30 | "minecraft": ">=1.20.5", 31 | "fabricloader": ">=0.15.10", 32 | "carpet": ">=1.4.140", 33 | "java": ">=21" 34 | }, 35 | 36 | "custom": { 37 | "modmenu": { 38 | "parent": "carpet", 39 | "links": { 40 | "modmenu.discord": "https://discord.gg/etTDQAVSgt" 41 | } 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/resources/scarpet-additions.mixins.json: -------------------------------------------------------------------------------- 1 | { 2 | "required": true, 3 | "package": "net.replaceitem.scarpet.additions.mixins", 4 | "compatibilityLevel": "JAVA_21", 5 | "mixins": [ 6 | ], 7 | "client": [ 8 | ], 9 | "server": [ 10 | "ServerMetadataMixin" 11 | ], 12 | "injectors": { 13 | "defaultRequire": 1 14 | } 15 | } 16 | 17 | --------------------------------------------------------------------------------