This commit is contained in:
Color_yr committed 2025-09-22 13:43:14 +08:00
1 parent 3260637d02
commit db0f010dbd
24 files changed
+1263

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
[submodule "client"]
path = client
url = https://github.com/Coloryr/AllMusic_Client.git
Submodule
+1
Submodule client added at 6842736046.
+8
View File
@@ -30,3 +30,11 @@ set array2=folia server_top server
for %%i in (%array2%) do (
if not exist "%%i\src\main\java\com\coloryr\allmusic\server\bstats" mklink /j "%%i\src\main\java\com\coloryr\allmusic\server\bstats" "bstats"
)
set array1=neoforge_1_21_6
for %%i in (%array1%) do (
if not exist "onejar\%%i\src\main\java\com\coloryr\allmusic\server\core" mklink /j "onejar\%%i\src\main\java\com\coloryr\allmusic\server\core" "core"
if not exist "onejar\%%i\build" mkdir "onejar\%%i\build" && mklink /j "onejar\%%i\build\libs" "build\libs"
if not exist "onejar\%%i\src\main\java\com\coloryr\allmusic\server\codec" mklink /j "onejar\%%i\src\main\java\com\coloryr\allmusic\server\codec" "codec"
)
+5
View File
@@ -0,0 +1,5 @@
# Disable autocrlf on generated files, they always generate with LF
# Add any extra files or paths here to make git stop saying they
# are changed when only line endings change.
src/generated/**/.cache/cache text eol=lf
src/generated/**/*.json text eol=lf
+26
View File
@@ -0,0 +1,26 @@
# eclipse
bin
*.launch
.settings
.metadata
.classpath
.project
# idea
out
*.ipr
*.iws
*.iml
.idea
# gradle
build
.gradle
# other
eclipse
run
runs
# Files from Forge MDK
forge*changelog.txt
+198
View File
@@ -0,0 +1,198 @@
plugins {
id 'java-library'
id 'maven-publish'
id 'net.neoforged.gradle.userdev' version '7.0.189'
}
tasks.named('wrapper', Wrapper).configure {
// Define wrapper values here so as to not have to always do so when updating gradlew.properties.
// Switching this to Wrapper.DistributionType.ALL will download the full gradle sources that comes with
// documentation attached on cursor hover of gradle classes and methods. However, this comes with increased
// file size for Gradle. If you do switch this to ALL, run the Gradle wrapper task twice afterwards.
// (Verify by checking gradle/wrapper/gradle-wrapper.properties to see if distributionUrl now points to `-all`)
distributionType = Wrapper.DistributionType.BIN
}
def getVersionFromFile() {
def versionFile = file('../version')
if (versionFile.exists()) {
return versionFile.text.trim()
} else {
throw new GradleException("Version file not found: ${versionFile.absolutePath}")
}
}
version = getVersionFromFile()
mod_version = version
group = mod_group_id
repositories {
mavenLocal()
// maven {
// name = 'Kotlin for Forge'
// url = 'https://thedarkcolour.github.io/KotlinForForge/'
// content { includeGroup "thedarkcolour" }
// }
}
base {
archivesName = file_name
}
// Mojang ships Java 21 to end users starting in 1.20.5, so mods should target Java 21.
java.toolchain.languageVersion = JavaLanguageVersion.of(21)
// Enable the Jar-in-Jar system for your mod
jarJar.enable()
// Default run configurations.
// These can be tweaked, removed, or duplicated as needed.
runs {
// applies to all the run configs below
configureEach {
// Recommended logging data for a userdev environment
// The markers can be added/remove as needed separated by commas.
// "SCAN": For mods scan.
// "REGISTRIES": For firing of registry events.
// "REGISTRYDUMP": For getting the contents of all registries.
systemProperty 'forge.logging.markers', 'REGISTRIES'
// Recommended logging level for the console
// You can set various levels here.
// Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels
systemProperty 'forge.logging.console.level', 'debug'
modSource project.sourceSets.main
}
client {
// Comma-separated list of namespaces to load gametests from. Empty = all namespaces.
systemProperty 'neoforge.enabledGameTestNamespaces', project.mod_id
}
server {
systemProperty 'neoforge.enabledGameTestNamespaces', project.mod_id
argument '--nogui'
}
// This run config launches GameTestServer and runs all registered gametests, then exits.
// By default, the server will crash when no gametests are provided.
// The gametest system is also enabled by default for other run configs under the /test command.
gameTestServer {
systemProperty 'neoforge.enabledGameTestNamespaces', project.mod_id
}
clientData {
// example of overriding the workingDirectory set in configureEach above, uncomment if you want to use it
// workingDirectory project.file('run-data')
// Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources.
arguments.addAll '--mod', project.mod_id, '--all', '--output', file('src/generated/resources/').getAbsolutePath(), '--existing', file('src/main/resources/').getAbsolutePath()
}
}
// Include resources generated by data generators.
sourceSets.main.resources { srcDir 'src/generated/resources' }
// Sets up a dependency configuration called 'localRuntime'.
// This configuration should be used instead of 'runtimeOnly' to declare
// a dependency that will be present for runtime testing but that is
// "optional", meaning it will not be pulled by dependents of this mod.
configurations {
runtimeClasspath.extendsFrom localRuntime
}
dependencies {
// Specify the version of Minecraft to use.
// Depending on the plugin applied there are several options. We will assume you applied the userdev plugin as shown above.
// The group for userdev is net.neoforged, the module name is neoforge, and the version is the same as the neoforge version.
// You can however also use the vanilla plugin (net.neoforged.gradle.vanilla) to use a version of Minecraft without the neoforge loader.
// And its provides the option to then use net.minecraft as the group, and one of; client, server or joined as the module name, plus the game version as version.
// For all intends and purposes: You can treat this dependency as if it is a normal library you would use.
implementation "net.neoforged:neoforge:${neo_version}"
// Example optional mod dependency with JEI
// The JEI API is declared for compile time use, while the full JEI artifact is used at runtime
// compileOnly "mezz.jei:jei-${mc_version}-common-api:${jei_version}"
// compileOnly "mezz.jei:jei-${mc_version}-neoforge-api:${jei_version}"
// We add the full version to localRuntime, not runtimeOnly, so that we do not publish a dependency on it
// localRuntime "mezz.jei:jei-${mc_version}-neoforge:${jei_version}"
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
implementation 'org.xerial:sqlite-jdbc:3.48.0.0'
// implementation "thedarkcolour:kotlinforforge:$kff_version"
// jarJar (group: 'org.jetbrains.kotlin', name: 'kotlin-stdlib-jdk8', version: '[2.0, 2.1)')
// jarJar (group: 'org.jetbrains.kotlin', name: 'kotlin-stdlib-jdk7', version: '[2.0, 2.1)')
// jarJar (group: 'org.jetbrains.kotlin', name: 'kotlin-stdlib', version: '[2.0, 2.1)')
// jarJar (group: 'org.jetbrains.kotlin', name: 'kotlin-stdlib-common', version: '[2.0, 2.1)')
jarJar (group: 'com.squareup.okhttp3', name: 'okhttp', version: '[4.12, 5.0)')
jarJar (group: 'com.squareup.okio', name: 'okio-jvm', version: '[3.9, 4.0)')
jarJar (group: 'org.xerial', name: 'sqlite-jdbc', version: '[3.46, 4.0)')
// Example mod dependency using a mod jar from ./libs with a flat dir repository
// This maps to ./libs/coolmod-${mc_version}-${coolmod_version}.jar
// The group id is ignored when searching -- in this case, it is "blank"
// implementation "blank:coolmod-${mc_version}:${coolmod_version}"
// Example mod dependency using a file as dependency
// implementation files("libs/coolmod-${mc_version}-${coolmod_version}.jar")
// Example project dependency using a sister or child project:
// implementation project(":myproject")
// For more info:
// http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html
// http://www.gradle.org/docs/current/userguide/dependency_management.html
}
// This block of code expands all declared replace properties in the specified resource targets.
// A missing property will result in an error. Properties are expanded using ${} Groovy notation.
// When "copyIdeResources" is enabled, this will also run before the game launches in IDE environments.
// See https://docs.gradle.org/current/dsl/org.gradle.language.jvm.tasks.ProcessResources.html
tasks.withType(ProcessResources).configureEach {
var replaceProperties = [
minecraft_version : minecraft_version,
minecraft_version_range: minecraft_version_range,
neo_version : neo_version,
neo_version_range : neo_version_range,
mod_id : mod_id,
mod_name : mod_name,
mod_license : mod_license,
mod_version : mod_version,
mod_authors : mod_authors,
mod_description : mod_description
]
inputs.properties replaceProperties
filesMatching(['META-INF/neoforge.mods.toml']) {
expand replaceProperties
}
}
// Example configuration to allow publishing using the maven-publish plugin
publishing {
publications {
register('mavenJava', MavenPublication) {
from components.java
}
}
repositories {
maven {
url "file://${project.projectDir}/repo"
}
}
}
tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation
}
// IDEA no longer automatically downloads sources/javadoc jars for dependencies, so we need to explicitly enable the behavior.
idea {
module {
downloadSources = true
downloadJavadoc = true
}
}
+47
View File
@@ -0,0 +1,47 @@
# Sets default memory used for gradle commands. Can be overridden by user or command line properties.
org.gradle.jvmargs=-Xmx1G
org.gradle.daemon=true
org.gradle.parallel=true
org.gradle.caching=true
org.gradle.configuration-cache=true
#read more on this at https://github.com/neoforged/NeoGradle/blob/NG_7.0/README.md#apply-parchment-mappings
# you can also find the latest versions at: https://parchmentmc.org/docs/getting-started
neogradle.subsystems.parchment.minecraftVersion=1.21.5
neogradle.subsystems.parchment.mappingsVersion=2025.06.15
# Environment Properties
# You can find the latest versions here: https://projects.neoforged.net/neoforged/neoforge
# The Minecraft version must agree with the Neo version to get a valid artifact
minecraft_version=1.21.6
# The Minecraft version range can use any release version of Minecraft as bounds.
# Snapshots, pre-releases, and release candidates are not guaranteed to sort properly
# as they do not follow standard versioning conventions.
minecraft_version_range=[1.21.6]
# The Neo version must agree with the Minecraft version to get a valid artifact
neo_version=21.6.20-beta
# The Neo version range can use any version of Neo as bounds
neo_version_range=[21.6.20-beta,)
kff_version=5.7.0
## Mod Properties
file_name = [neoforge-1.21.6]AllMusic_Server
# The unique mod identifier for the mod. Must be lowercase in English locale. Must fit the regex [a-z][a-z0-9_]{1,63}
# Must match the String constant located in the main mod class annotated with @Mod.
mod_id=allmusic_server
# The human-readable display name for the mod.
mod_name=AllMusic Server
# The license of the mod. Review your options at https://choosealicense.com/. All Rights Reserved is the default.
mod_license=GPL-3.0
# The mod version. See https://semver.org/
mod_version=3.3.2
# The group ID for the mod. It is only important when publishing as an artifact to a Maven repository.
# This should match the base package used for the mod sources.
# See https://maven.apache.org/guides/mini/guide-naming-conventions.html
mod_group_id=com.coloryr.allmusic.server
# The authors of the mod. This is a simple text string that is used for display purposes in the mod list.
mod_authors=Color_yr
# The description of the mod. This is a simple multiline text string that is used for display purposes in the mod list.
mod_description=AllMusic Server Mod
Binary file not shown.
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+240
View File
@@ -0,0 +1,240 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for 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/.
#
##############################################################################
# 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
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&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 ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$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
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 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" )
# 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" )
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
done
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 \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# 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.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+91
View File
@@ -0,0 +1,91 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+13
View File
@@ -0,0 +1,13 @@
pluginManagement {
repositories {
mavenLocal()
gradlePluginPortal()
maven { url = 'https://maven.neoforged.net/releases' }
}
}
plugins {
id 'org.gradle.toolchains.foojay-resolver-convention' version '0.9.0'
}
rootProject.name = 'AllMusic_Server'
@@ -0,0 +1,104 @@
package com.coloryr.allmusic.server;
import com.coloryr.allmusic.server.core.AllMusic;
import com.coloryr.allmusic.server.side.forge.CommandForge;
import com.coloryr.allmusic.server.side.forge.LogForge;
import com.coloryr.allmusic.server.side.forge.PackData;
import com.coloryr.allmusic.server.side.forge.SideForge;
import com.mojang.brigadier.CommandDispatcher;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.neoforged.bus.api.IEventBus;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.Mod;
import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent;
import net.neoforged.neoforge.common.NeoForge;
import net.neoforged.neoforge.event.RegisterCommandsEvent;
import net.neoforged.neoforge.event.entity.player.PlayerEvent;
import net.neoforged.neoforge.event.server.ServerStartedEvent;
import net.neoforged.neoforge.event.server.ServerStoppingEvent;
import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent;
import net.neoforged.neoforge.network.handling.IPayloadContext;
import net.neoforged.neoforge.network.handling.IPayloadHandler;
import net.neoforged.neoforge.network.registration.PayloadRegistrar;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.Locale;
// The value here should match an entry in the META-INF/mods.toml file
@Mod(AllMusicForge.MODID)
public class AllMusicForge {
public static final ResourceLocation channel = ResourceLocation.fromNamespaceAndPath("allmusic", "channel");
// Define mod id in a common place for everything to reference
public static final String MODID = "allmusic_server";
// Directly reference a slf4j logger
public static final Logger LOGGER = LoggerFactory.getLogger("AllMusic_Server");
public static MinecraftServer server;
// Create a Deferred Register to hold Blocks which will all be registered under the "examplemod" namespace
public AllMusicForge(IEventBus modEventBus) {
// Register the commonSetup method for modloading
modEventBus.addListener(this::commonSetup);
modEventBus.addListener(this::register);
// Register ourselves for server and other game events we are interested in
NeoForge.EVENT_BUS.register(this);
}
private void commonSetup(final FMLCommonSetupEvent event) {
String path = String.format(Locale.ROOT, "config/%s/", "allmusic");
AllMusic.log = new LogForge();
AllMusic.side = new SideForge();
new AllMusic().init(new File(path));
}
public void register(final RegisterPayloadHandlersEvent event) {
LOGGER.info("注册插件信道");
final PayloadRegistrar registrar = event.registrar("1.0");
registrar.optional().playToClient(PackData.TYPE, PackData.CODEC, new HandelPack());
}
@SubscribeEvent
public void onRegisterCommands(RegisterCommandsEvent event) {
LOGGER.info("注册指令");
CommandDispatcher<CommandSourceStack> dispatcher = event.getDispatcher();
CommandForge.instance.register(dispatcher);
}
// You can use SubscribeEvent and let the Event Bus discover methods to call
@SubscribeEvent
public void onServerStarting(ServerStartedEvent event) {
server = event.getServer();
AllMusic.start();
Tasks.init();
}
@SubscribeEvent
public void onServerStopping(ServerStoppingEvent event) {
AllMusic.stop();
}
@SubscribeEvent
public void onPlayerLoggedOut(PlayerEvent.PlayerLoggedOutEvent event) {
AllMusic.removeNowPlayPlayer(event.getEntity().getName().getString());
}
@SubscribeEvent
public void onPlayerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) {
AllMusic.joinPlay(event.getEntity().getName().getString());
}
private static class HandelPack implements IPayloadHandler<PackData> {
@Override
public void handle(@NotNull PackData payload, IPayloadContext context) {
//context.handle(payload);
}
}
}
@@ -0,0 +1,6 @@
package com.coloryr.allmusic.server;
public class TaskItem {
public int tick;
public Runnable run;
}
@@ -0,0 +1,27 @@
package com.coloryr.allmusic.server;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class Tasks {
private static final List<TaskItem> taskItems = new CopyOnWriteArrayList<>();
public static void init() {
AllMusicForge.server.addTickable(Tasks::tick);
}
public static void tick() {
for (TaskItem item : new ArrayList<>(taskItems)) {
item.tick--;
if (item.tick <= 0) {
taskItems.remove(item);
item.run.run();
}
}
}
public static void add(TaskItem item) {
taskItems.add(item);
}
}
@@ -0,0 +1,67 @@
package com.coloryr.allmusic.server.side.forge;
import com.coloryr.allmusic.server.core.command.CommandEX;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.suggestion.SuggestionProvider;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Predicate;
public class CommandForge implements Command<CommandSourceStack>, Predicate<CommandSourceStack>, SuggestionProvider<CommandSourceStack> {
public static CommandForge instance = new CommandForge();
public void register(CommandDispatcher<CommandSourceStack> dispatcher) {
dispatcher.register(((Commands.literal("music").requires(this)).executes(this))
.then(Commands.argument("args", StringArgumentType.greedyString())
.suggests(this).executes(this)));
}
@Override
public int run(CommandContext<CommandSourceStack> context) {
var item = context.getSource();
var source = item.source;
var input = context.getInput();
var temp = input.split(" ");
var arg = new String[temp.length - 1];
System.arraycopy(temp, 1, arg, 0, arg.length);
CommandEX.execute(source, context.getSource().getTextName(), arg);
return 0;
}
@Override
public boolean test(CommandSourceStack stack) {
return true;
}
@Override
public CompletableFuture<Suggestions> getSuggestions(CommandContext<CommandSourceStack> context, SuggestionsBuilder builder) {
var item = context.getSource();
var input = context.getInput();
var temp = input.split(" ");
var arg = new String[input.endsWith(" ") ? temp.length : temp.length - 1];
System.arraycopy(temp, 1, arg, 0, temp.length - 1);
if (input.endsWith(" "))
builder = builder.createOffset(builder.getInput().lastIndexOf(32) + 1);
List<String> results = CommandEX.getTabList(item, item.getTextName(), arg);
for (String s : results) {
builder.suggest(s);
}
return builder.buildFuture();
}
}
@@ -0,0 +1,44 @@
package com.coloryr.allmusic.server.side.forge;
import com.coloryr.allmusic.server.AllMusicForge;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.protocol.game.ClientboundSetActionBarTextPacket;
import net.minecraft.server.level.ServerPlayer;
public class ForgeApi {
public static void sendMessageRun(Object obj, String message, String end, String command) {
CommandSourceStack sender = (CommandSourceStack) obj;
MutableComponent send = Component.literal(message);
MutableComponent endtext = Component.literal(end);
endtext.setStyle(endtext.getStyle().withClickEvent(new ClickEvent.RunCommand(command)));
send.append(endtext);
sender.sendSystemMessage(send);
}
public static void sendMessageSuggest(Object obj, String message, String end, String command) {
CommandSourceStack sender = (CommandSourceStack) obj;
MutableComponent send = Component.literal(message);
MutableComponent endtext = Component.literal(end);
endtext.setStyle(endtext.getStyle().withClickEvent(new ClickEvent.SuggestCommand(command)));
send.append(endtext);
sender.sendSystemMessage(send);
}
public static void sendBar(ServerPlayer player, String message) {
var pack = new ClientboundSetActionBarTextPacket(Component.literal(message));
player.connection.send(pack);
}
public static void sendMessageBqRun(String message, String end, String command) {
MutableComponent send = Component.literal(message);
MutableComponent endtext = Component.literal(end);
endtext.setStyle(endtext.getStyle().withClickEvent(new ClickEvent.SuggestCommand(command)));
send.append(endtext);
for (ServerPlayer player : AllMusicForge.server.getPlayerList().getPlayers()) {
player.sendSystemMessage(send);
}
}
}
@@ -0,0 +1,16 @@
package com.coloryr.allmusic.server.side.forge;
import com.coloryr.allmusic.server.AllMusicForge;
import com.coloryr.allmusic.server.core.side.IMyLogger;
public class LogForge implements IMyLogger {
@Override
public void warning(String data) {
AllMusicForge.LOGGER.warn(data);
}
@Override
public void info(String data) {
AllMusicForge.LOGGER.info(data);
}
}
@@ -0,0 +1,32 @@
package com.coloryr.allmusic.server.side.forge;
import com.coloryr.allmusic.server.AllMusicForge;
import com.coloryr.allmusic.server.codec.PacketCodec;
import com.coloryr.allmusic.server.core.objs.enums.ComType;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import org.jetbrains.annotations.NotNull;
public record PackData(ComType cmd, String data, int data1) implements CustomPacketPayload {
public static final Type<PackData> TYPE = new Type<>(AllMusicForge.channel);
public static final StreamCodec<RegistryFriendlyByteBuf, PackData> CODEC = new PackCodec();
@Override
public @NotNull Type<? extends CustomPacketPayload> type() {
return TYPE;
}
public static class PackCodec implements StreamCodec<RegistryFriendlyByteBuf, PackData> {
@Override
public @NotNull PackData decode(RegistryFriendlyByteBuf pack) {
pack.clear();
return new PackData(ComType.CLEAR, "", 0);
}
@Override
public void encode(@NotNull RegistryFriendlyByteBuf pack, PackData buffer) {
PacketCodec.pack(pack, buffer.cmd, buffer.data, buffer.data1);
}
}
}
@@ -0,0 +1,177 @@
package com.coloryr.allmusic.server.side.forge;
import com.coloryr.allmusic.server.AllMusicForge;
import com.coloryr.allmusic.server.TaskItem;
import com.coloryr.allmusic.server.Tasks;
import com.coloryr.allmusic.server.core.AllMusic;
import com.coloryr.allmusic.server.core.objs.enums.ComType;
import com.coloryr.allmusic.server.core.objs.music.MusicObj;
import com.coloryr.allmusic.server.core.objs.music.SongInfoObj;
import com.coloryr.allmusic.server.core.side.BaseSide;
import com.coloryr.allmusic.server.side.forge.event.MusicAddEvent;
import com.coloryr.allmusic.server.side.forge.event.MusicPlayEvent;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.neoforged.neoforge.common.NeoForge;
import net.neoforged.neoforge.network.PacketDistributor;
import java.io.File;
import java.util.Collection;
import java.util.Locale;
public class SideForge extends BaseSide {
@Override
public void runTask(Runnable run) {
AllMusicForge.server.execute(run);
}
@Override
public void runTask(Runnable run1, int delay) {
Tasks.add(new TaskItem() {{
tick = delay;
run = run1;
}});
}
@Override
public boolean checkPermission(Object player, String permission) {
return checkPermission(player);
}
@Override
public boolean checkPermission(Object player) {
CommandSourceStack source = (CommandSourceStack) player;
return source.hasPermission(2);
}
@Override
public boolean isPlayer(Object player) {
CommandSourceStack source = (CommandSourceStack) player;
return source.isPlayer();
}
@Override
public boolean needPlay(boolean islist) {
for (ServerPlayer player : AllMusicForge.server.getPlayerList().getPlayers()) {
if (!AllMusic.isSkip(player.getName().getString(), null, false, islist)) {
return true;
}
}
return false;
}
@Override
public Collection<?> getPlayers() {
return AllMusicForge.server.getPlayerList().getPlayers();
}
@Override
public String getPlayerName(Object player) {
if (player instanceof ServerPlayer player1) {
return player1.getName().getString();
}
return null;
}
@Override
public String getPlayerServer(Object player) {
return null;
}
@Override
public void send(Object player, ComType type, String data, int data1) {
if (player instanceof ServerPlayer player1) {
send(player1, new PackData(type, data, data1));
}
}
@Override
public Object getPlayer(String player) {
return AllMusicForge.server.getPlayerList().getPlayerByName(player);
}
@Override
public void sendBar(Object player, String data) {
if (player instanceof ServerPlayer player1) {
ForgeApi.sendBar(player1, data);
}
}
@Override
public File getFolder() {
return new File(String.format(Locale.ROOT, "config/%s/", "allmusic"));
}
@Override
public void broadcast(String message) {
if (message == null || message.isEmpty()) {
return;
}
for (ServerPlayer player : AllMusicForge.server.getPlayerList().getPlayers()) {
if (!AllMusic.isSkip(player.getName().getString(), null, false)) {
player.sendSystemMessage(Component.literal(message));
}
}
}
@Override
public void broadcastWithRun(String message, String end, String command) {
if (message == null || message.isEmpty()) {
return;
}
ForgeApi.sendMessageBqRun(message, end, command);
}
@Override
public void sendMessage(Object obj, String message) {
if (message == null || message.isEmpty()) {
return;
}
CommandSourceStack source = (CommandSourceStack) obj;
source.sendSystemMessage(Component.literal(message));
}
@Override
public void sendMessageRun(Object obj, String message, String end, String command) {
if (message == null || message.isEmpty()) {
return;
}
ForgeApi.sendMessageRun(obj, message, end, command);
}
@Override
public void sendMessageSuggest(Object obj, String message, String end, String command) {
if (message == null || message.isEmpty()) {
return;
}
ForgeApi.sendMessageSuggest(obj, message, end, command);
}
@Override
public boolean onMusicPlay(SongInfoObj obj) {
MusicPlayEvent event = new MusicPlayEvent(obj);
NeoForge.EVENT_BUS.post(event);
return event.isCancel();
}
@Override
public boolean onMusicAdd(Object obj, MusicObj music) {
CommandSourceStack source = (CommandSourceStack) obj;
MusicAddEvent event = new MusicAddEvent(music, source.getPlayer());
NeoForge.EVENT_BUS.post(event);
return event.isCancel();
}
private void send(ServerPlayer players, PackData data) {
if (players == null)
return;
try {
runTask(() -> PacketDistributor.sendToPlayer(players, data));
} catch (Exception e) {
AllMusic.log.warning("§c数据发送发生错误");
e.printStackTrace();
}
}
}
@@ -0,0 +1,39 @@
package com.coloryr.allmusic.server.side.forge.event;
import com.coloryr.allmusic.server.core.objs.music.MusicObj;
import net.minecraft.server.level.ServerPlayer;
import net.neoforged.bus.api.Event;
public class MusicAddEvent extends Event {
/**
* 添加的音乐
*/
private final MusicObj music;
/**
* 添加者
*/
private final ServerPlayer player;
private boolean cancel;
public MusicAddEvent(MusicObj id, ServerPlayer player) {
this.music = id;
this.player = player;
}
public boolean isCancel() {
return cancel;
}
public void setCancel(boolean cancel) {
this.cancel = cancel;
}
public ServerPlayer getPlayer() {
return player;
}
public MusicObj getMusic() {
return music;
}
}
@@ -0,0 +1,25 @@
package com.coloryr.allmusic.server.side.forge.event;
import com.coloryr.allmusic.server.core.objs.music.SongInfoObj;
import net.neoforged.bus.api.Event;
public class MusicPlayEvent extends Event {
private final SongInfoObj music;
private boolean cancel;
public MusicPlayEvent(SongInfoObj music) {
this.music = music;
}
public boolean isCancel() {
return cancel;
}
public void setCancel(boolean cancel) {
this.cancel = cancel;
}
public SongInfoObj getMusic() {
return music;
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

@@ -0,0 +1,87 @@
# This is an example neoforge.mods.toml file. It contains the data relating to the loading mods.
# There are several mandatory fields (#mandatory), and many more that are optional (#optional).
# The overall format is standard TOML format, v0.5.0.
# Note that there are a couple of TOML lists in this file.
# Find more information on toml format here: https://github.com/toml-lang/toml
# The license for you mod. This is mandatory metadata and allows for easier comprehension of your redistributive properties.
# Review your options at https://choosealicense.com/. All rights reserved is the default copyright stance, and is thus the default here.
license="${mod_license}"
# A URL to refer people to when problems occur with this mod
#issueTrackerURL="https://change.me.to.your.issue.tracker.example.invalid/" #optional
# A list of mods - how many allowed here is determined by the individual mod loader
[[mods]] #mandatory
# The modid of the mod
modId="${mod_id}" #mandatory
# The version number of the mod
version="${mod_version}" #mandatory
# A display name for the mod
displayName="${mod_name}" #mandatory
# A URL to query for updates for this mod. See the JSON update specification https://docs.neoforged.net/docs/misc/updatechecker/
#updateJSONURL="https://change.me.example.invalid/updates.json" #optional
# A URL for the "homepage" for this mod, displayed in the mod UI
#displayURL="https://change.me.to.your.mods.homepage.example.invalid/" #optional
# A file name (in the root of the mod JAR) containing a logo for display
#logoFile="examplemod.png" #optional
# A text field displayed in the mod UI
#credits="" #optional
# A text field displayed in the mod UI
authors="${mod_authors}" #optional
# The description text for the mod (multi line!) (#mandatory)
description='''${mod_description}'''
# The [[mixins]] block allows you to declare your mixin config to FML so that it gets loaded.
#[[mixins]]
#config="${mod_id}.mixins.json"
# The [[accessTransformers]] block allows you to declare where your AT file is.
# If this block is omitted, a fallback attempt will be made to load an AT from META-INF/accesstransformer.cfg
#[[accessTransformers]]
#file="META-INF/accesstransformer.cfg"
# The coremods config file path is not configurable and is always loaded from META-INF/coremods.json
# A dependency - use the . to indicate dependency for a specific modid. Dependencies are optional.
[[dependencies.${mod_id}]] #optional
# the modid of the dependency
modId="neoforge" #mandatory
# The type of the dependency. Can be one of "required", "optional", "incompatible" or "discouraged" (case insensitive).
# 'required' requires the mod to exist, 'optional' does not
# 'incompatible' will prevent the game from loading when the mod exists, and 'discouraged' will show a warning
type="required" #mandatory
# Optional field describing why the dependency is required or why it is incompatible
# reason="..."
# The version range of the dependency
versionRange="${neo_version_range}" #mandatory
# An ordering relationship for the dependency.
# BEFORE - This mod is loaded BEFORE the dependency
# AFTER - This mod is loaded AFTER the dependency
ordering="NONE"
# Side this dependency is applied on - BOTH, CLIENT, or SERVER
side="BOTH"
# Here's another dependency
[[dependencies.${mod_id}]]
modId="minecraft"
type="required"
# This version range declares a minimum of the current minecraft version up to but not including the next major version
versionRange="${minecraft_version_range}"
ordering="NONE"
side="BOTH"
# Features are specific properties of the game environment, that you may want to declare you require. This example declares
# that your mod requires GL version 3.2 or higher. Other features will be added. They are side aware so declaring this won't
# stop your mod loading on the server for example.
#[features.${mod_id}]
#openGLVersion="[3.2,)"