1
0
mirror of https://github.com/Suiranoil/SkinRestorer.git synced 2026-01-16 04:42:12 +00:00

Compare commits

..

33 Commits

Author SHA1 Message Date
01a045541c update CHANGELOG 2025-07-13 20:30:43 +03:00
5bab96e269 bump version 2025-07-13 20:30:28 +03:00
a0b557be51 add 1.21.7 to mc version list 2025-07-13 20:21:36 +03:00
7fad7de710 check name and id for null
fixes #60 and #61
2025-07-13 20:20:14 +03:00
8af1dd8f12 update CHANGELOG 2025-07-09 21:37:18 +03:00
1c7f97551d bump version 2025-07-09 21:37:18 +03:00
a8cc81e570 better exception logging 2025-07-09 21:37:18 +03:00
6ce3484824 rethrow io exception 2025-07-07 01:02:12 +03:00
b518305028 add exception logging 2025-07-07 00:56:32 +03:00
96ea077004 update CHANGELOG 2025-07-05 19:39:23 +03:00
91eead3d1f bump version 2025-07-05 19:39:00 +03:00
2ea4d3f3e7 formatting 2025-07-05 19:21:45 +03:00
e65501e620 support custom skins for player head block 2025-07-05 19:15:22 +03:00
1b8a6c2f5d update CHANGELOG 2025-06-21 11:06:52 +03:00
4cc12e23dc bump version 2025-06-21 11:06:38 +03:00
28db1ee84c Revert "use server side"
This reverts commit ad6d64e8d4.
2025-06-21 11:03:39 +03:00
df58fe8c89 update CHANGELOG 2025-06-19 06:01:20 +03:00
2325b3b35c bump version 2025-06-19 06:00:49 +03:00
ad6d64e8d4 use server side 2025-06-19 05:55:44 +03:00
07b4887f60 update to minecraft 1.21.6 2025-06-19 05:55:43 +03:00
30d21c9424 update parchment 2025-06-18 19:04:28 +03:00
1c51796409 add mojmap layer version to parchment on forge 2025-06-18 19:03:33 +03:00
1b6afd5d6e update mineskin client to 3.0.6 2025-06-11 01:26:34 +03:00
7e05f1eec9 decouple publish task from jar tasks 2025-06-01 19:12:57 +03:00
81d05fe991 Revert "remove shadow of public method getPlayers"
This reverts commit 6c159d6aa2.
2025-06-01 18:38:17 +03:00
757d46b231 Revert "remove shadow of server from PlayerListMixin"
This reverts commit 8119a08c80.
2025-06-01 18:38:17 +03:00
3b15f7b341 Revert "remove shadow from ServerLoginPacketListenerImplMixin"
This reverts commit 5b384c32d6.
2025-06-01 18:38:17 +03:00
38a2fd7214 update gitignore 2025-06-01 18:20:04 +03:00
e4c9e1b3cd bump version 2025-06-01 13:55:20 +03:00
3ef3318ed3 update CHANGELOG.md 2025-06-01 13:48:54 +03:00
5b384c32d6 remove shadow from ServerLoginPacketListenerImplMixin 2025-05-30 22:35:56 +03:00
8119a08c80 remove shadow of server from PlayerListMixin 2025-05-30 21:46:42 +03:00
6c159d6aa2 remove shadow of public method getPlayers 2025-05-30 21:29:42 +03:00
54 changed files with 613 additions and 238 deletions

1
.gitignore vendored
View File

@@ -30,3 +30,4 @@ bin/
.architectury-transformer/
run/
scripts/

View File

@@ -4,6 +4,34 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [2.4.2] - 2025-07-13
### Fixed
- Fix crash when head profile name is null (fixes [#60](https://github.com/Suiranoil/SkinRestorer/issues/60) and [#61](https://github.com/Suiranoil/SkinRestorer/issues/61))
## [2.4.1] - 2025-07-09
### Changed
- Log full exception and argument when unable to fetch/set skin
### Fixed
- Fixed mojang provider using offline uuids when unable to fetch actual uuid resulting in `no profile with uuid` error
## [2.4.0] - 2025-07-05
### Fixed
- Added support for player heads
## [2.3.5] - 2025-06-21
### Fixed
- Fix mod not loading on client
## [2.3.4] - 2025-06-19
### Added
- Added support for minecraft 1.21.6
## [2.3.3] - 2025-06-01
### Fixed
- Fixed forge mixin crash (closes [#54](https://github.com/Suiranoil/SkinRestorer/issues/53))
### Removed
- Removed minecraft 1.19 support
## [2.3.2] - 2025-05-24
### Fixed
- Fixed mixin incompatibility with ModernFix (closes [#42](https://github.com/Suiranoil/SkinRestorer/issues/52))

View File

@@ -1,2 +1,2 @@
### Fixed
- Fixed mixin incompatibility with ModernFix (closes [#42](https://github.com/Suiranoil/SkinRestorer/issues/52))
- Fix crash when head profile name is null (fixes [#60](https://github.com/Suiranoil/SkinRestorer/issues/60) and [#61](https://github.com/Suiranoil/SkinRestorer/issues/61))

View File

@@ -3,12 +3,7 @@ plugins {
}
publishMods {
if (project.name == 'fabric')
file = remapJar.archiveFile
else if (project.name == 'neoforge')
file = jar.archiveFile
else
file = tasks.named('jarJar').get().archiveFile
file = project.layout.buildDirectory.file("libs/${project.archivesBaseName}-${project.version}.jar").map { it.asFile }.getOrNull()
modLoaders.add(project.name)
type = STABLE

View File

@@ -1,10 +1,12 @@
package net.lionarius.skinrestorer;
import com.google.common.base.Throwables;
import com.mojang.authlib.GameProfile;
import com.mojang.brigadier.CommandDispatcher;
import net.lionarius.skinrestorer.command.SkinCommand;
import net.lionarius.skinrestorer.config.Config;
import net.lionarius.skinrestorer.config.provider.BuiltInProviderConfig;
import net.lionarius.skinrestorer.exception.TransparentException;
import net.lionarius.skinrestorer.platform.Services;
import net.lionarius.skinrestorer.skin.SkinIO;
import net.lionarius.skinrestorer.skin.SkinStorage;
@@ -63,7 +65,7 @@ public final class SkinRestorer {
}
public static ResourceLocation resourceLocation(String name) {
return new ResourceLocation(SkinRestorer.MOD_ID, name);
return ResourceLocation.fromNamespaceAndPath(SkinRestorer.MOD_ID, name);
}
public static String assetPath(String name) {
@@ -147,7 +149,7 @@ public final class SkinRestorer {
var skinResult = result.get();
if (skinResult.isError())
return Result.<Collection<ServerPlayer>, String>error(skinResult.getErrorValue().getMessage());
throw new TransparentException(Throwables.getRootCause(skinResult.getErrorValue()));
var skinValue = SkinValue.fromProviderContextWithValue(context, skinResult.getSuccessValue().orElse(null));
@@ -156,7 +158,7 @@ public final class SkinRestorer {
return Result.<Collection<ServerPlayer>, String>success(acceptedPlayers);
}, server)
.exceptionally(e -> {
SkinRestorer.LOGGER.error(e.toString());
SkinRestorer.LOGGER.error("Failed to set skin '{}:{}'", context.name(), context.argument(), e);
return Result.error(e.getMessage());
});
}

View File

@@ -128,7 +128,7 @@ public final class SkinCommand {
boolean save,
boolean setByOperator
) {
src.sendSuccess(Translation.translatableWithFallback(Translation.COMMAND_SKIN_LOADING_KEY), false);
src.sendSystemMessage(Translation.translatableWithFallback(Translation.COMMAND_SKIN_LOADING_KEY));
SkinRestorer.setSkinAsync(src.getServer(), targets, context, save).thenAccept(result -> {
if (result.isError()) {
@@ -169,7 +169,7 @@ public final class SkinCommand {
private static int configReloadSubcommand(CommandContext<CommandSourceStack> context) {
SkinRestorer.reloadConfig();
context.getSource().sendSuccess(Translation.translatableWithFallback(
context.getSource().sendSuccess(() -> Translation.translatableWithFallback(
Translation.COMMAND_SKIN_CONFIG_RELOADED_KEY
), true);
@@ -178,7 +178,7 @@ public final class SkinCommand {
private static void sendResponse(CommandSourceStack src, Collection<ServerPlayer> updatedPlayers, boolean setByOperator) {
if (updatedPlayers.isEmpty()) {
src.sendSuccess(Translation.translatableWithFallback(
src.sendSuccess(() -> Translation.translatableWithFallback(
Translation.COMMAND_SKIN_NO_CHANGES_KEY
), true);
return;
@@ -187,12 +187,12 @@ public final class SkinCommand {
if (setByOperator) {
var playersComponent = PlayerUtils.createPlayerListComponent(updatedPlayers);
src.sendSuccess(Translation.translatableWithFallback(
src.sendSuccess(() -> Translation.translatableWithFallback(
Translation.COMMAND_SKIN_AFFECTED_PLAYERS_KEY,
playersComponent
), true);
} else {
src.sendSuccess(Translation.translatableWithFallback(
src.sendSuccess(() -> Translation.translatableWithFallback(
Translation.COMMAND_SKIN_OK_KEY
), true);
}

View File

@@ -0,0 +1,55 @@
package net.lionarius.skinrestorer.compat.skinshuffle;
import net.lionarius.skinrestorer.SkinRestorer;
import net.lionarius.skinrestorer.platform.Services;
import net.lionarius.skinrestorer.skin.SkinValue;
import net.lionarius.skinrestorer.skin.provider.SkinShuffleSkinProvider;
import net.lionarius.skinrestorer.util.PlayerUtils;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import java.util.Collections;
public class SkinShuffleCompatibility {
public static final String MOD_ID = "skinshuffle";
private static final boolean SHOULD_APPLY = !Services.PLATFORM.isModLoaded(SkinShuffleCompatibility.MOD_ID);
private SkinShuffleCompatibility() {}
public static boolean shouldApply() {
return SkinShuffleCompatibility.SHOULD_APPLY;
}
public static ResourceLocation resourceLocation(String name) {
return ResourceLocation.fromNamespaceAndPath(SkinShuffleCompatibility.MOD_ID, name);
}
public static void onPlayerJoin(ServerPlayer player) {
Services.COMPATIBILITY.skinShuffle_sendHandshake(player);
}
public static void handleSkinRefresh(MinecraftServer server, ServerPlayer player, SkinShuffleSkinRefreshPayload payload) {
var property = payload.textureProperty();
if (!property.name().equals(PlayerUtils.TEXTURES_KEY))
return;
if (!property.hasSignature())
return;
server.execute(() -> {
SkinRestorer.applySkin(
server,
Collections.singleton(player.getGameProfile()),
new SkinValue(SkinShuffleSkinProvider.PROVIDER_NAME, null, null, property),
!server.usesAuthentication()
);
if (server.usesAuthentication() && SkinRestorer.getSkinStorage().hasSavedSkin(player.getUUID()))
SkinRestorer.getSkinStorage().deleteSkin(player.getUUID());
});
}
}

View File

@@ -0,0 +1,19 @@
package net.lionarius.skinrestorer.compat.skinshuffle;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import org.jetbrains.annotations.NotNull;
public record SkinShuffleHandshakePayload() implements CustomPacketPayload {
public static final SkinShuffleHandshakePayload INSTANCE = new SkinShuffleHandshakePayload();
public static final CustomPacketPayload.Type<SkinShuffleHandshakePayload> PACKET_ID = new CustomPacketPayload.Type<>(SkinShuffleCompatibility.resourceLocation("handshake"));
public static final StreamCodec<FriendlyByteBuf, SkinShuffleHandshakePayload> PACKET_CODEC = StreamCodec.unit(INSTANCE);
@Override
public CustomPacketPayload.@NotNull Type<? extends CustomPacketPayload> type() {
return PACKET_ID;
}
}

View File

@@ -0,0 +1,7 @@
package net.lionarius.skinrestorer.compat.skinshuffle;
import com.mojang.authlib.properties.Property;
public interface SkinShuffleSkinRefreshPayload {
Property textureProperty();
}

View File

@@ -0,0 +1,34 @@
package net.lionarius.skinrestorer.compat.skinshuffle;
import com.mojang.authlib.properties.Property;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import org.jetbrains.annotations.NotNull;
public record SkinShuffleSkinRefreshV1Payload(
Property textureProperty) implements CustomPacketPayload, SkinShuffleSkinRefreshPayload {
public static final CustomPacketPayload.Type<SkinShuffleSkinRefreshV1Payload> PACKET_ID = new CustomPacketPayload.Type<>(SkinShuffleCompatibility.resourceLocation("refresh"));
public static final StreamCodec<FriendlyByteBuf, SkinShuffleSkinRefreshV1Payload> PACKET_CODEC = StreamCodec.of(
SkinShuffleSkinRefreshV1Payload::encode,
SkinShuffleSkinRefreshV1Payload::decode
);
public static void encode(FriendlyByteBuf buf, SkinShuffleSkinRefreshV1Payload value) {
var textureProperty = value.textureProperty();
buf.writeUtf(textureProperty.name());
buf.writeUtf(textureProperty.value());
buf.writeNullable(textureProperty.signature(), FriendlyByteBuf::writeUtf);
}
public static SkinShuffleSkinRefreshV1Payload decode(FriendlyByteBuf buf) {
return new SkinShuffleSkinRefreshV1Payload(new Property(buf.readUtf(), buf.readUtf(), buf.readNullable(FriendlyByteBuf::readUtf)));
}
@Override
public @NotNull CustomPacketPayload.Type<? extends CustomPacketPayload> type() {
return PACKET_ID;
}
}

View File

@@ -0,0 +1,42 @@
package net.lionarius.skinrestorer.compat.skinshuffle;
import com.mojang.authlib.properties.Property;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import org.jetbrains.annotations.NotNull;
public record SkinShuffleSkinRefreshV2Payload(
Property textureProperty) implements CustomPacketPayload, SkinShuffleSkinRefreshPayload {
public static final CustomPacketPayload.Type<SkinShuffleSkinRefreshV2Payload> PACKET_ID = new CustomPacketPayload.Type<>(SkinShuffleCompatibility.resourceLocation("skin_refresh"));
public static final StreamCodec<FriendlyByteBuf, SkinShuffleSkinRefreshV2Payload> PACKET_CODEC = StreamCodec.of(
SkinShuffleSkinRefreshV2Payload::encode,
SkinShuffleSkinRefreshV2Payload::decode
);
public static void encode(FriendlyByteBuf buf, SkinShuffleSkinRefreshV2Payload value) {
var textureProperty = value.textureProperty();
buf.writeBoolean(textureProperty.hasSignature());
buf.writeUtf(textureProperty.name());
buf.writeUtf(textureProperty.value());
if (textureProperty.hasSignature()) {
assert textureProperty.signature() != null;
buf.writeUtf(textureProperty.signature());
}
}
public static SkinShuffleSkinRefreshV2Payload decode(FriendlyByteBuf buf) {
if (buf.readBoolean()) {
return new SkinShuffleSkinRefreshV2Payload(new Property(buf.readUtf(), buf.readUtf(), buf.readUtf()));
}
return new SkinShuffleSkinRefreshV2Payload(new Property(buf.readUtf(), buf.readUtf(), null));
}
@Override
public @NotNull CustomPacketPayload.Type<? extends CustomPacketPayload> type() {
return PACKET_ID;
}
}

View File

@@ -5,20 +5,20 @@ import net.lionarius.skinrestorer.SkinRestorer;
public final class CacheConfig {
private boolean enabled;
private long duration;
public CacheConfig(boolean enabled, long duration) {
this.enabled = enabled;
this.duration = duration;
}
public boolean enabled() {
return enabled;
}
public long duration() {
return duration;
}
void validate(CacheConfig defaultValue) {
if (this.duration <= 0) {
SkinRestorer.LOGGER.warn("Cache duration is less than or equal to zero, defaulting to {}", defaultValue.duration());

View File

@@ -9,41 +9,41 @@ public final class ProvidersConfig implements GsonPostProcessable {
new ElyByProviderConfig(),
new MineskinProviderConfig()
);
private MojangProviderConfig mojang;
private ElyByProviderConfig ely_by;
private MineskinProviderConfig mineskin;
public ProvidersConfig(MojangProviderConfig mojang, ElyByProviderConfig ely_by, MineskinProviderConfig mineskin) {
this.mojang = mojang;
this.ely_by = ely_by;
this.mineskin = mineskin;
}
public MojangProviderConfig mojang() {
return this.mojang;
}
public ElyByProviderConfig ely_by() {
return this.ely_by;
}
public MineskinProviderConfig mineskin() {
return this.mineskin;
}
@Override
public void gsonPostProcess() {
if (this.mojang == null) {
SkinRestorer.LOGGER.warn("Mojang provider config is null, using default");
this.mojang = ProvidersConfig.DEFAULT.mojang();
}
if (this.ely_by == null) {
SkinRestorer.LOGGER.warn("Ely.By provider config is null, using default");
this.ely_by = ProvidersConfig.DEFAULT.ely_by();
}
if (this.mineskin == null) {
SkinRestorer.LOGGER.warn("Mineskin provider config is null, using default");
this.mineskin = ProvidersConfig.DEFAULT.mineskin();

View File

@@ -0,0 +1,19 @@
package net.lionarius.skinrestorer.exception;
import org.jetbrains.annotations.NotNull;
public class TransparentException extends RuntimeException {
public TransparentException(@NotNull Throwable cause) {
super(cause);
}
@Override
public String getMessage() {
return this.getCause().getMessage();
}
@Override
public String toString() {
return this.getLocalizedMessage();
}
}

View File

@@ -32,8 +32,8 @@ public class Java11RequestHandler extends RequestHandler {
private final Gson gson;
private final HttpClient httpClient;
public Java11RequestHandler(String userAgent, String apiKey, int timeout, Gson gson, InetSocketAddress proxy) {
super(userAgent, apiKey, timeout, gson);
public Java11RequestHandler(String baseUrl, String userAgent, String apiKey, int timeout, Gson gson, InetSocketAddress proxy) {
super(baseUrl, userAgent, apiKey, timeout, gson);
this.gson = gson;
HttpClient.Builder clientBuilder = HttpClient.newBuilder()
@@ -85,6 +85,7 @@ public class Java11RequestHandler extends RequestHandler {
public <T, R extends MineSkinResponse<T>> R getJson(String url, Class<T> clazz, ResponseConstructor<T, R> constructor)
throws IOException {
url = this.baseUrl + url;
MineSkinClientImpl.LOGGER.fine("GET " + url);
HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
@@ -110,6 +111,7 @@ public class Java11RequestHandler extends RequestHandler {
public <T, R extends MineSkinResponse<T>> R postJson(String url, JsonObject data, Class<T> clazz, ResponseConstructor<T, R> constructor)
throws IOException {
url = this.baseUrl + url;
MineSkinClientImpl.LOGGER.fine("POST " + url);
HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
@@ -137,6 +139,7 @@ public class Java11RequestHandler extends RequestHandler {
public <T, R extends MineSkinResponse<T>> R postFormDataFile(String url, String key, String filename, InputStream in, Map<String, String> data, Class<T> clazz, ResponseConstructor<T, R> constructor)
throws IOException {
url = this.baseUrl + url;
MineSkinClientImpl.LOGGER.fine("POST " + url);
String boundary = "mineskin-" + System.currentTimeMillis();

View File

@@ -4,6 +4,7 @@ import net.lionarius.skinrestorer.SkinRestorer;
import net.minecraft.network.Connection;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.network.CommonListenerCookie;
import net.minecraft.server.players.PlayerList;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
@@ -38,7 +39,7 @@ public abstract class PlayerListMixin {
}
@Inject(method = "placeNewPlayer", at = @At("HEAD"))
private void placeNewPlayer(Connection connection, ServerPlayer player, CallbackInfo ci) {
private void placeNewPlayer(Connection connection, ServerPlayer player, CommonListenerCookie cookie, CallbackInfo ci) {
var delay = SkinRestorer.getConfig().skinApplyDelayOnJoin();
if (delay <= 0) {

View File

@@ -21,24 +21,20 @@ import java.util.concurrent.CompletableFuture;
public abstract class ServerLoginPacketListenerImplMixin {
@Shadow @Nullable
private GameProfile gameProfile;
private GameProfile authenticatedProfile;
@Unique
private CompletableFuture<Void> skinrestorer$pendingSkin;
@Shadow
protected abstract GameProfile createFakeProfile(GameProfile original);
@Inject(method = "handleAcceptedLogin", at = @At(value = "HEAD"), cancellable = true)
@Inject(method = "verifyLoginAndFinishConnectionSetup", at = @At(value = "INVOKE",
target = "Lnet/minecraft/server/players/PlayerList;canPlayerLogin(Ljava/net/SocketAddress;Lcom/mojang/authlib/GameProfile;)Lnet/minecraft/network/chat/Component;"),
cancellable = true)
public void waitForSkin(CallbackInfo ci) {
if (skinrestorer$pendingSkin == null) {
skinrestorer$pendingSkin = CompletableFuture.supplyAsync(() -> {
var profile = gameProfile;
final var profile = authenticatedProfile;
assert profile != null;
if (!profile.isComplete())
profile = createFakeProfile(profile);
var originalSkin = PlayerUtils.getPlayerSkin(profile);
if (SkinRestorer.getSkinStorage().hasSavedSkin(profile.getId())) {
@@ -86,7 +82,7 @@ public abstract class ServerLoginPacketListenerImplMixin {
var value = SkinValue.fromProviderContextWithValue(context, result.getSuccessValue().orElse(null));
SkinRestorer.getSkinStorage().setSkin(profile.getId(), value);
} else {
SkinRestorer.LOGGER.warn("Failed to fetch skin: {}", result.getErrorValue().getMessage());
SkinRestorer.LOGGER.warn("Failed to fetch skin '{}:{}'", context.name(), context.argument(), result.getErrorValue());
}
}
}

View File

@@ -0,0 +1,60 @@
package net.lionarius.skinrestorer.mixin;
import com.mojang.authlib.GameProfile;
import net.lionarius.skinrestorer.SkinRestorer;
import net.lionarius.skinrestorer.util.PlayerUtils;
import net.minecraft.server.Services;
import net.minecraft.world.level.block.entity.SkullBlockEntity;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.function.BooleanSupplier;
@Mixin(SkullBlockEntity.class)
public abstract class SkullBlockEntityMixin {
@Inject(method = "fetchProfileByName", at = @At("HEAD"),
cancellable = true)
private static void fetchProfileByName(String name, Services services, CallbackInfoReturnable<CompletableFuture<Optional<GameProfile>>> cir) {
if (name == null)
return;
var profileOpt = services.profileCache().get(name);
skinrestorer$replaceSkin(profileOpt, cir);
}
@Inject(method = "fetchProfileById", at = @At("HEAD"),
cancellable = true)
private static void fetchProfileById(UUID id, Services services, BooleanSupplier cacheUninitialized, CallbackInfoReturnable<CompletableFuture<Optional<GameProfile>>> cir) {
if (id == null)
return;
var profileOpt = services.profileCache().get(id);
skinrestorer$replaceSkin(profileOpt, cir);
}
@Unique
private static void skinrestorer$replaceSkin(Optional<GameProfile> profileOpt, CallbackInfoReturnable<CompletableFuture<Optional<GameProfile>>> cir) {
if (profileOpt.isEmpty())
return;
var profile = PlayerUtils.cloneGameProfile(profileOpt.get());
if (SkinRestorer.getSkinStorage().hasSavedSkin(profile.getId())) {
cir.setReturnValue(CompletableFuture.supplyAsync(() -> {
var skin = SkinRestorer.getSkinStorage().getSkin(profile.getId(), false);
PlayerUtils.applyRestoredSkin(profile, skin.value());
return Optional.of(profile);
}));
}
}
}

View File

@@ -8,11 +8,11 @@ import java.util.ServiceLoader;
public final class Services {
private Services() {}
public final static PlatformHelper PLATFORM = load(PlatformHelper.class);
public final static CompatibilityHelper COMPATIBILITY = load(CompatibilityHelper.class);
private Services() {}
private static <T> T load(Class<T> clazz) {
final T loadedService = ServiceLoader.load(clazz)
.findFirst()

View File

@@ -1,4 +1,8 @@
package net.lionarius.skinrestorer.platform.services;
import net.minecraft.server.level.ServerPlayer;
public interface CompatibilityHelper {
void skinShuffle_sendHandshake(ServerPlayer player);
}

View File

@@ -17,15 +17,22 @@ public class SkinStorage {
return this.skinMap.containsKey(uuid) || this.skinIO.skinExists(uuid);
}
public SkinValue getSkin(UUID uuid) {
public SkinValue getSkin(UUID uuid, boolean cache) {
if (!skinMap.containsKey(uuid)) {
var skin = skinIO.loadSkin(uuid);
if (!cache)
return skin;
setSkin(uuid, skin);
}
return skinMap.get(uuid);
}
public SkinValue getSkin(UUID uuid) {
return this.getSkin(uuid, true);
}
public void removeSkin(UUID uuid, boolean save) {
var skin = skinMap.remove(uuid);
if (skin != null && save)

View File

@@ -9,25 +9,11 @@ import org.jetbrains.annotations.Nullable;
import java.util.Objects;
public final class SkinValue implements GsonPostProcessable {
public record SkinValue(@NotNull String provider, @Nullable String argument, @Nullable SkinVariant variant,
@Nullable Property value, @Nullable Property originalValue) implements GsonPostProcessable {
public static final SkinValue EMPTY = new SkinValue(EmptySkinProvider.PROVIDER_NAME, null, null, null);
private @NotNull String provider;
private @Nullable String argument;
private @Nullable SkinVariant variant;
private @Nullable Property value;
private @Nullable Property originalValue;
public SkinValue(@NotNull String provider, @Nullable String argument, @Nullable SkinVariant variant,
@Nullable Property value, @Nullable Property originalValue) {
this.provider = provider;
this.argument = argument;
this.variant = variant;
this.value = value;
this.originalValue = originalValue;
}
public SkinValue(String provider, String argument, SkinVariant variant, Property value) {
this(provider, argument, variant, value, null);
}
@@ -52,23 +38,4 @@ public final class SkinValue implements GsonPostProcessable {
public void gsonPostProcess() {
Objects.requireNonNull(this.provider);
}
public @NotNull String provider() {
return provider;
}
public @Nullable String argument() {
return argument;
}
public @Nullable SkinVariant variant() {
return variant;}
public @Nullable Property value() {
return value;
}
public @Nullable Property originalValue() {
return originalValue;
}
}

View File

@@ -9,7 +9,11 @@ import com.mojang.authlib.properties.Property;
import com.mojang.authlib.yggdrasil.response.MinecraftProfilePropertiesResponse;
import net.lionarius.skinrestorer.SkinRestorer;
import net.lionarius.skinrestorer.skin.SkinVariant;
import net.lionarius.skinrestorer.util.*;
import net.lionarius.skinrestorer.util.JsonUtils;
import net.lionarius.skinrestorer.util.PlayerUtils;
import net.lionarius.skinrestorer.util.Result;
import net.lionarius.skinrestorer.util.WebUtils;
import net.minecraft.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
@@ -67,7 +71,7 @@ public final class ElyBySkinProvider implements SkinProvider {
@Override
public Result<Optional<Property>, Exception> fetchSkin(String username, SkinVariant variant) {
try {
if (!StringUtils.isValidPlayerName(username))
if (!StringUtil.isValidPlayerName(username))
throw new IllegalArgumentException("invalid username");
var usernameLowerCase = username.toLowerCase(Locale.ROOT);
@@ -102,6 +106,6 @@ public final class ElyBySkinProvider implements SkinProvider {
if (response.statusCode() != 200)
throw new IllegalArgumentException("no profile with name " + username);
return PlayerUtils.toProfile(JsonUtils.fromJson(response.body(), MinecraftProfilePropertiesResponse.class));
return JsonUtils.fromJson(response.body(), MinecraftProfilePropertiesResponse.class).toProfile();
}
}

View File

@@ -43,7 +43,8 @@ public final class MineskinSkinProvider implements SkinProvider {
.userAgent(WebUtils.USER_AGENT)
.gson(JsonUtils.GSON)
.timeout((int) Duration.ofSeconds(config.requestTimeout()).toMillis())
.requestHandler((userAgent, apiKey, timeout, gson) -> new Java11RequestHandler(
.requestHandler((baseUrl, userAgent, apiKey, timeout, gson) -> new Java11RequestHandler(
baseUrl,
userAgent,
apiKey,
timeout,

View File

@@ -8,10 +8,16 @@ import com.mojang.authlib.*;
import com.mojang.authlib.properties.Property;
import com.mojang.authlib.yggdrasil.YggdrasilEnvironment;
import com.mojang.authlib.yggdrasil.response.MinecraftProfilePropertiesResponse;
import com.mojang.util.UndashedUuid;
import net.lionarius.skinrestorer.SkinRestorer;
import net.lionarius.skinrestorer.exception.TransparentException;
import net.lionarius.skinrestorer.skin.SkinVariant;
import net.lionarius.skinrestorer.util.*;
import net.lionarius.skinrestorer.util.JsonUtils;
import net.lionarius.skinrestorer.util.PlayerUtils;
import net.lionarius.skinrestorer.util.Result;
import net.lionarius.skinrestorer.util.WebUtils;
import net.minecraft.server.players.GameProfileCache;
import net.minecraft.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
@@ -39,19 +45,32 @@ public final class MojangSkinProvider implements SkinProvider {
try {
ENVIRONMENT = EnvironmentParser.getEnvironmentFromProperties().orElse(YggdrasilEnvironment.PROD.getEnvironment());
SERVICES_SERVER_URI = new URI(ENVIRONMENT.getServicesHost());
SESSION_SERVER_URI = new URI(ENVIRONMENT.getSessionHost());
SERVICES_SERVER_URI = new URI(ENVIRONMENT.servicesHost());
SESSION_SERVER_URI = new URI(ENVIRONMENT.sessionHost());
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
PROFILE_CACHE = new GameProfileCache((names, agent, callback) -> {
for (var name : names) {
PROFILE_CACHE = new GameProfileCache(new GameProfileRepository() {
@Override
public void findProfilesByNames(String[] names, ProfileLookupCallback callback) {
for (var name : names) {
try {
var profile = MojangSkinProvider.getProfile(name);
callback.onProfileLookupSucceeded(profile);
} catch (IOException e) {
throw new TransparentException(e);
}
}
}
@Override
public Optional<GameProfile> findProfileByName(String name) {
try {
var profile = MojangSkinProvider.getProfile(name);
callback.onProfileLookupSucceeded(profile);
return Optional.of(profile);
} catch (IOException e) {
callback.onProfileLookupFailed(new GameProfile(null, name), e);
throw new TransparentException(e);
}
}
}, SkinRestorer.getConfigDir().resolve(PROFILE_CACHE_FILENAME).toFile());
@@ -92,7 +111,7 @@ public final class MojangSkinProvider implements SkinProvider {
@Override
public Result<Optional<Property>, Exception> fetchSkin(String username, SkinVariant variant) {
try {
if (!StringUtils.isValidPlayerName(username))
if (!StringUtil.isValidPlayerName(username))
throw new IllegalArgumentException("invalid username");
var cachedProfile = MojangSkinProvider.PROFILE_CACHE.get(username);
@@ -136,7 +155,7 @@ public final class MojangSkinProvider implements SkinProvider {
var request = HttpRequest.newBuilder()
.uri(MojangSkinProvider.SESSION_SERVER_URI
.resolve("/session/minecraft/profile/")
.resolve(uuid.toString() + "?unsigned=false")
.resolve(UndashedUuid.toString(uuid) + "?unsigned=false")
)
.GET()
.build();
@@ -147,6 +166,6 @@ public final class MojangSkinProvider implements SkinProvider {
if (response.statusCode() != 200)
throw new IllegalArgumentException("no profile with uuid " + uuid);
return PlayerUtils.toProfile(JsonUtils.fromJson(response.body(), MinecraftProfilePropertiesResponse.class));
return JsonUtils.fromJson(response.body(), MinecraftProfilePropertiesResponse.class).toProfile();
}
}

View File

@@ -39,11 +39,11 @@ public final class Translation {
}
public static MutableComponent translatableWithFallback(String key) {
return Component.translatable(Translation.get(key));
return Component.translatableWithFallback(key, Translation.get(key));
}
public static MutableComponent translatableWithFallback(String key, Object... args) {
return Component.translatable(Translation.get(key), args);
return Component.translatableWithFallback(key, Translation.get(key), args);
}
public static void reloadTranslations() {

View File

@@ -1,6 +1,9 @@
package net.lionarius.skinrestorer.util;
import com.google.gson.*;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.properties.Property;
import com.mojang.authlib.properties.PropertyMap;
@@ -19,7 +22,7 @@ public final class JsonUtils {
.registerTypeAdapterFactory(new PostProcessingEnabler())
.registerTypeAdapter(UUID.class, new UUIDTypeAdapter())
.registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer())
.registerTypeAdapter(GameProfile.class, new GameProfileSerializer())
.registerTypeAdapter(GameProfile.class, new GameProfile.Serializer())
.setPrettyPrinting()
.create();
@@ -47,7 +50,7 @@ public final class JsonUtils {
public static JsonObject skinPropertyToJson(Property property) {
try {
JsonObject json = GSON.fromJson(new String(Base64.getDecoder().decode(property.getValue()), StandardCharsets.UTF_8), JsonObject.class);
JsonObject json = GSON.fromJson(new String(Base64.getDecoder().decode(property.value()), StandardCharsets.UTF_8), JsonObject.class);
if (json != null)
json.remove("timestamp");
@@ -57,26 +60,4 @@ public final class JsonUtils {
return null;
}
}
private static class GameProfileSerializer implements JsonSerializer<GameProfile>, JsonDeserializer<GameProfile> {
@Override
public GameProfile deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {
final JsonObject object = (JsonObject) json;
final UUID id = object.has("id") ? context.deserialize(object.get("id"), UUID.class) : null;
final String name = object.has("name") ? object.getAsJsonPrimitive("name").getAsString() : null;
return new GameProfile(id, name);
}
@Override
public JsonElement serialize(final GameProfile src, final Type typeOfSrc, final JsonSerializationContext context) {
final JsonObject result = new JsonObject();
if (src.getId() != null) {
result.add("id", context.serialize(src.getId()));
}
if (src.getName() != null) {
result.addProperty("name", src.getName());
}
return result;
}
}
}

View File

@@ -13,7 +13,6 @@ import net.minecraft.server.level.ChunkMap;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.players.PlayerList;
import net.minecraft.world.level.biome.BiomeManager;
import java.util.*;
@@ -40,12 +39,16 @@ public final class PlayerUtils {
}
public static void refreshPlayer(ServerPlayer player) {
ServerLevel serverLevel = player.getLevel();
ServerLevel serverLevel = player.level();
PlayerList playerList = serverLevel.getServer().getPlayerList();
ChunkMap chunkMap = serverLevel.getChunkSource().chunkMap;
playerList.broadcastAll(new ClientboundPlayerInfoPacket(ClientboundPlayerInfoPacket.Action.REMOVE_PLAYER, player));
playerList.broadcastAll(new ClientboundPlayerInfoPacket(ClientboundPlayerInfoPacket.Action.ADD_PLAYER, player));
playerList.broadcastAll(new ClientboundBundlePacket(
List.of(
new ClientboundPlayerInfoRemovePacket(List.of(player.getUUID())),
ClientboundPlayerInfoUpdatePacket.createPlayerInitializing(Collections.singleton(player))
)
));
var trackedEntity = (TrackedEntityAccessorInvoker) ((ChunkMapAccessor) chunkMap).getEntityMap().get(player.getId());
if (trackedEntity != null) {
@@ -64,19 +67,12 @@ public final class PlayerUtils {
}
if (!player.isDeadOrDying()) {
player.connection.send(
new ClientboundRespawnPacket(
player.getLevel().dimensionTypeId(),
player.getLevel().dimension(),
BiomeManager.obfuscateSeed(player.getLevel().getSeed()),
player.gameMode.getGameModeForPlayer(),
player.gameMode.getPreviousGameModeForPlayer(),
player.getLevel().isDebug(),
player.getLevel().isFlat(),
true,
player.getLastDeathLocation()
player.connection.send(new ClientboundBundlePacket(
List.of(
new ClientboundRespawnPacket(player.createCommonSpawnInfo(serverLevel), ClientboundRespawnPacket.KEEP_ALL_DATA),
new ClientboundGameEventPacket(ClientboundGameEventPacket.LEVEL_CHUNKS_LOAD_START, 0)
)
);
));
player.connection.teleport(player.getX(), player.getY(), player.getZ(), player.getYRot(), player.getXRot());
player.connection.send(new ClientboundSetEntityMotionPacket(player));
var vehicle = player.getVehicle();
@@ -90,16 +86,23 @@ public final class PlayerUtils {
playerList.sendPlayerPermissionLevel(player);
playerList.sendLevelInfo(player, serverLevel);
playerList.sendAllPlayerInfo(player);
PlayerUtils.sendActivePlayerEffects(player);
playerList.sendActivePlayerEffects(player);
}
}
private static void sendActivePlayerEffects(ServerPlayer player) {
for (var effect : player.getActiveEffects()) {
player.connection.send(new ClientboundUpdateMobEffectPacket(player.getId(), effect));
player.connection.send(new ClientboundUpdateMobEffectPacket(player.getId(), effect, false));
}
}
public static GameProfile cloneGameProfile(GameProfile profile) {
var newProfile = new GameProfile(profile.getId(), profile.getName());
newProfile.getProperties().putAll(profile.getProperties());
return newProfile;
}
public static Property getPlayerSkin(GameProfile profile) {
return Iterables.getFirst(profile.getProperties().get(TEXTURES_KEY), null);
}
@@ -131,8 +134,8 @@ public final class PlayerUtils {
}
public static GameProfile toProfile(MinecraftProfilePropertiesResponse response) {
final GameProfile profile = new GameProfile(response.getId(), response.getName());
profile.getProperties().putAll(response.getProperties());
final GameProfile profile = new GameProfile(response.id(), response.name());
profile.getProperties().putAll(response.properties());
return profile;
}
}

View File

@@ -19,6 +19,18 @@ public class Result<S, E> {
this.errorValue = errorValue;
}
public static <S, E> Result<S, E> success(@NotNull S successValue) {
return new Result<>(successValue, null);
}
public static <S, E> Result<S, E> error(@NotNull E errorValue) {
return new Result<>(null, errorValue);
}
public static <S, E> Result<Optional<S>, E> ofNullable(S successValue) {
return Result.success(Optional.ofNullable(successValue));
}
public S getSuccessValue() {
return successValue;
}
@@ -69,16 +81,4 @@ public class Result<S, E> {
public int hashCode() {
return Objects.hash(successValue, errorValue);
}
public static <S, E> Result<S, E> success(@NotNull S successValue) {
return new Result<>(successValue, null);
}
public static <S, E> Result<S, E> error(@NotNull E errorValue) {
return new Result<>(null, errorValue);
}
public static <S, E> Result<Optional<S>, E> ofNullable(S successValue) {
return Result.success(Optional.ofNullable(successValue));
}
}

View File

@@ -13,8 +13,6 @@ import java.time.temporal.ChronoUnit;
public final class WebUtils {
private WebUtils() {}
public static final String USER_AGENT;
private static HttpClient HTTP_CLIENT = null;
@@ -23,6 +21,8 @@ public final class WebUtils {
USER_AGENT = String.format("SkinRestorer/%d", System.currentTimeMillis() % 65535);
}
private WebUtils() {}
public static void recreateHttpClient() {
HTTP_CLIENT = WebUtils.buildClient();
}

View File

@@ -9,7 +9,8 @@
"ChunkMapAccessor",
"PlayerListMixin",
"ServerLoginPacketListenerImplMixin",
"TrackedEntityAccessorInvoker"
"TrackedEntityAccessorInvoker",
"SkullBlockEntityMixin"
],
"injectors": {
"defaultRequire": 1

View File

@@ -14,6 +14,8 @@ dependencies {
}
modImplementation "net.fabricmc:fabric-loader:${fabric_loader_version}"
modCompileOnly "net.fabricmc.fabric-api:fabric-api:${fabric_api_version}"
include implementation("org.mineskin:java-client:${mineskin_client_version}")
}

View File

@@ -1,2 +1,5 @@
# Fabric, see https://fabricmc.net/develop/ for new versions
fabric_loader_version=0.15.0
fabric_api_version=0.127.0+1.21.6
optional_dependencies=fabric-api

View File

@@ -2,11 +2,18 @@ package net.lionarius.skinrestorer.fabric;
import net.fabricmc.api.ModInitializer;
import net.lionarius.skinrestorer.SkinRestorer;
import net.lionarius.skinrestorer.compat.skinshuffle.SkinShuffleCompatibility;
import net.lionarius.skinrestorer.platform.Services;
public final class SkinRestorerFabric implements ModInitializer {
public static final boolean FABRIC_API_LOADED = Services.PLATFORM.isModLoaded("fabric-api");
@Override
public void onInitialize() {
SkinRestorer.onInitialize();
if (SkinShuffleCompatibility.shouldApply())
net.lionarius.skinrestorer.fabric.compat.skinshuffle.SkinShuffleCompatibility.initialize();
}
}

View File

@@ -0,0 +1,37 @@
package net.lionarius.skinrestorer.fabric.compat.skinshuffle;
import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.lionarius.skinrestorer.SkinRestorer;
import net.lionarius.skinrestorer.compat.skinshuffle.SkinShuffleHandshakePayload;
import net.lionarius.skinrestorer.compat.skinshuffle.SkinShuffleSkinRefreshPayload;
import net.lionarius.skinrestorer.compat.skinshuffle.SkinShuffleSkinRefreshV1Payload;
import net.lionarius.skinrestorer.compat.skinshuffle.SkinShuffleSkinRefreshV2Payload;
import net.lionarius.skinrestorer.fabric.SkinRestorerFabric;
public final class SkinShuffleCompatibility {
private SkinShuffleCompatibility() {}
public static void initialize() {
if (!SkinRestorerFabric.FABRIC_API_LOADED) {
SkinRestorer.LOGGER.warn("fabric-api is not loaded, SkinShuffle compatibility will not be available");
return;
}
PayloadTypeRegistry.playS2C().register(SkinShuffleHandshakePayload.PACKET_ID, SkinShuffleHandshakePayload.PACKET_CODEC);
PayloadTypeRegistry.playC2S().register(SkinShuffleSkinRefreshV1Payload.PACKET_ID, SkinShuffleSkinRefreshV1Payload.PACKET_CODEC);
PayloadTypeRegistry.playC2S().register(SkinShuffleSkinRefreshV2Payload.PACKET_ID, SkinShuffleSkinRefreshV2Payload.PACKET_CODEC);
ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> net.lionarius.skinrestorer.compat.skinshuffle.SkinShuffleCompatibility.onPlayerJoin(handler.getPlayer()));
ServerPlayNetworking.registerGlobalReceiver(SkinShuffleSkinRefreshV1Payload.PACKET_ID, SkinShuffleCompatibility::handleSkinRefreshPacket);
ServerPlayNetworking.registerGlobalReceiver(SkinShuffleSkinRefreshV2Payload.PACKET_ID, SkinShuffleCompatibility::handleSkinRefreshPacket);
}
private static void handleSkinRefreshPacket(SkinShuffleSkinRefreshPayload payload, ServerPlayNetworking.Context context) {
net.lionarius.skinrestorer.compat.skinshuffle.SkinShuffleCompatibility.handleSkinRefresh(context.player().getServer(), context.player(), payload);
}
}

View File

@@ -11,7 +11,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
public abstract class MinecraftServerMixin {
@Inject(method = "runServer",
at = @At(value = "INVOKE", target = "Lnet/minecraft/Util;getMillis()J", ordinal = 0))
at = @At(value = "INVOKE", target = "Lnet/minecraft/Util;getNanos()J", ordinal = 0))
private void onServerStarted(CallbackInfo ci) {
SkinRestorer.Events.onServerStarted((MinecraftServer) (Object) this);
}

View File

@@ -1,6 +1,13 @@
package net.lionarius.skinrestorer.fabric.platform;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.lionarius.skinrestorer.compat.skinshuffle.SkinShuffleHandshakePayload;
import net.lionarius.skinrestorer.platform.services.CompatibilityHelper;
import net.minecraft.server.level.ServerPlayer;
public final class FabricCompatibilityHelper implements CompatibilityHelper {
@Override
public void skinShuffle_sendHandshake(ServerPlayer player) {
ServerPlayNetworking.send(player, SkinShuffleHandshakePayload.INSTANCE);
}
}

View File

@@ -28,5 +28,8 @@
"fabricloader": ">=${fabric_loader_version}",
"minecraft": ">=${minecraft_version}",
"java": ">=${java_version}"
},
"suggests": {
"fabric-api": "*"
}
}

View File

@@ -17,19 +17,19 @@ mixin {
jarJar.enable()
tasks.named('jar') {
archiveClassifier = 'thin'
}
tasks.named('jarJar') {
archiveClassifier = ''
}
jar.finalizedBy('jarJar')
minecraft {
mappings channel: 'parchment', version: "${parchment_version}-${parchment_minecraft}"
mappings channel: 'parchment', version: "${parchment_minecraft}-${parchment_version}-${minecraft_version}"
copyIdeResources = true //Calls processResources when in dev
reobf = false // Forge 1.20.6+ uses official mappings at runtime, so we shouldn't reobf from official to SRG
// Automatically enable forge AccessTransformers if the file exists
// This location is hardcoded in Forge and can not be changed.
// https://github.com/MinecraftForge/MinecraftForge/blob/be1698bb1554f9c8fa2f58e32b9ab70bc4385e60/fmlloader/src/main/java/net/minecraftforge/fml/loading/moddiscovery/ModFile.java#L123
@@ -43,6 +43,7 @@ minecraft {
workingDirectory rootProject.file('run/client')
ideaModule "${rootProject.name}.${project.name}.main"
taskName 'Client'
property 'eventbus.api.strictRuntimeChecks', 'true'
mods {
modClientRun {
source sourceSets.main
@@ -54,6 +55,7 @@ minecraft {
workingDirectory rootProject.file('run/server')
ideaModule "${rootProject.name}.${project.name}.main"
taskName 'Server'
property 'eventbus.api.strictRuntimeChecks', 'true'
mods {
modServerRun {
source sourceSets.main
@@ -66,6 +68,8 @@ minecraft {
dependencies {
minecraft "net.minecraftforge:forge:${forge_minecraft_version}-${forge_version}"
annotationProcessor('net.minecraftforge:eventbus-validator:7.0-beta.7')
annotationProcessor('org.spongepowered:mixin:0.8.5-SNAPSHOT:processor')
implementation('net.sf.jopt-simple:jopt-simple:5.0.4') { version { strictly '5.0.4' } }

View File

@@ -1,5 +1,5 @@
# Forge, see https://files.minecraftforge.net/net/minecraftforge/forge/ for new versions
forge_version=41.0.1
forge_loader_version_range=[41,)
forge_version=56.0.0
forge_loader_version_range=[56,)
# Forge sometimes skips minor minecraft versions (like 1.20.5)
forge_minecraft_version=1.19
forge_minecraft_version=1.21.6

View File

@@ -1,9 +1,10 @@
package net.lionarius.skinrestorer.forge;
import net.lionarius.skinrestorer.SkinRestorer;
import net.lionarius.skinrestorer.compat.skinshuffle.SkinShuffleCompatibility;
import net.minecraftforge.event.RegisterCommandsEvent;
import net.minecraftforge.event.server.ServerStartedEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.eventbus.api.listener.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
@Mod(SkinRestorer.MOD_ID)
@@ -12,6 +13,9 @@ public final class SkinRestorerForge {
public SkinRestorerForge() {
SkinRestorer.onInitialize();
if (SkinShuffleCompatibility.shouldApply())
net.lionarius.skinrestorer.forge.compat.skinshuffle.SkinShuffleCompatibility.initialize();
}
@SubscribeEvent

View File

@@ -0,0 +1,14 @@
package net.lionarius.skinrestorer.forge.compat.skinshuffle;
import net.minecraftforge.event.entity.player.PlayerEvent;
public final class SkinShuffleCompatibility {
private SkinShuffleCompatibility() {}
public static void initialize() {
PlayerEvent.PlayerLoggedInEvent.BUS.addListener(SkinShuffleGameEventHandler::onPlayerLoggedIn);
SkinShufflePacketHandler.initialize();
}
}

View File

@@ -0,0 +1,14 @@
package net.lionarius.skinrestorer.forge.compat.skinshuffle;
import net.lionarius.skinrestorer.compat.skinshuffle.SkinShuffleCompatibility;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.event.entity.player.PlayerEvent;
public final class SkinShuffleGameEventHandler {
private SkinShuffleGameEventHandler() {}
public static void onPlayerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) {
SkinShuffleCompatibility.onPlayerJoin((ServerPlayer) event.getEntity());
}
}

View File

@@ -0,0 +1,45 @@
package net.lionarius.skinrestorer.forge.compat.skinshuffle;
import net.lionarius.skinrestorer.SkinRestorer;
import net.lionarius.skinrestorer.compat.skinshuffle.*;
import net.lionarius.skinrestorer.compat.skinshuffle.SkinShuffleCompatibility;
import net.minecraft.network.Connection;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraftforge.event.network.CustomPayloadEvent;
import net.minecraftforge.network.Channel;
import net.minecraftforge.network.ChannelBuilder;
public class SkinShufflePacketHandler {
private static final Channel<CustomPacketPayload> INSTANCE = ChannelBuilder
.named(SkinRestorer.resourceLocation("skin_shuffle_compat"))
.optional()
.payloadChannel()
.any()
.clientbound()
.add(SkinShuffleHandshakePayload.PACKET_ID, SkinShuffleHandshakePayload.PACKET_CODEC, (payload, context) -> {
})
.serverbound()
.add(SkinShuffleSkinRefreshV1Payload.PACKET_ID, SkinShuffleSkinRefreshV1Payload.PACKET_CODEC, SkinShufflePacketHandler::handleSkinRefreshPacket)
.add(SkinShuffleSkinRefreshV2Payload.PACKET_ID, SkinShuffleSkinRefreshV2Payload.PACKET_CODEC, SkinShufflePacketHandler::handleSkinRefreshPacket)
.build();
private SkinShufflePacketHandler() {
}
protected static void initialize() {
// NO-OP
}
public static void sendHandshake(Connection connection) {
INSTANCE.send(SkinShuffleHandshakePayload.INSTANCE, connection);
}
private static void handleSkinRefreshPacket(SkinShuffleSkinRefreshPayload payload, CustomPayloadEvent.Context context) {
var sender = context.getSender();
if (!context.isServerSide() || sender == null)
return;
SkinShuffleCompatibility.handleSkinRefresh(sender.getServer(), sender, payload);
}
}

View File

@@ -1,6 +1,13 @@
package net.lionarius.skinrestorer.forge.platform;
import net.lionarius.skinrestorer.forge.compat.skinshuffle.SkinShufflePacketHandler;
import net.lionarius.skinrestorer.platform.services.CompatibilityHelper;
import net.minecraft.server.level.ServerPlayer;
public final class ForgeCompatibilityHelper implements CompatibilityHelper {
@Override
public void skinShuffle_sendHandshake(ServerPlayer player) {
SkinShufflePacketHandler.sendHandshake(player.connection.getConnection());
}
}

View File

@@ -1,14 +1,14 @@
# Project
group=net.lionarius
java_version=17
java_version=21
# Common
minecraft_version=1.19
minecraft_version_list=1.19
minecraft_version_range=[1.19,1.19.1)
minecraft_version=1.21.6
minecraft_version_list=1.21.6,1.21.7
minecraft_version_range=[1.21.6, 1.22)
mod_id=skinrestorer
mod_name=SkinRestorer
mod_version=2.3.2
mod_version=2.4.2
mod_author=Lionarius
mod_homepage=https://modrinth.com/mod/skinrestorer
mod_sources=https://github.com/Suiranoil/SkinRestorer
@@ -18,11 +18,11 @@ credits=
description=A server-side mod for managing skins.
# Dependencies
mineskin_client_version=3.0.1-SNAPSHOT
mineskin_client_version=3.0.6-SNAPSHOT
# ParchmentMC mappings, see https://parchmentmc.org/docs/getting-started#choose-a-version for new versions
parchment_minecraft=1.19.2
parchment_version=2022.11.27
parchment_minecraft=1.21.5
parchment_version=2025.06.15
# Publishing
curseforge_id=443823

View File

@@ -1,3 +1,3 @@
# NeoForge, see https://projects.neoforged.net/neoforged/neoforge for new versions
neoforge_version=20.2.3-beta
neoforge_loader_version_range=[1,)
neoforge_version=21.6.0-beta
neoforge_loader_version_range=[4,)

View File

@@ -3,12 +3,13 @@ package net.lionarius.skinrestorer.neoforge;
import net.lionarius.skinrestorer.SkinRestorer;
import net.lionarius.skinrestorer.compat.skinshuffle.SkinShuffleCompatibility;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.fml.common.Mod;
import net.neoforged.neoforge.event.RegisterCommandsEvent;
import net.neoforged.neoforge.event.server.ServerStartedEvent;
@Mod(SkinRestorer.MOD_ID)
@Mod.EventBusSubscriber(modid = SkinRestorer.MOD_ID)
@EventBusSubscriber(modid = SkinRestorer.MOD_ID)
public final class SkinRestorerNeoForge {
public SkinRestorerNeoForge() {

View File

@@ -1,5 +1,7 @@
package net.lionarius.skinrestorer.neoforge.compat.skinshuffle;
import net.lionarius.skinrestorer.SkinRestorer;
import net.neoforged.fml.ModList;
import net.neoforged.neoforge.common.NeoForge;
public final class SkinShuffleCompatibility {
@@ -9,6 +11,7 @@ public final class SkinShuffleCompatibility {
public static void initialize() {
NeoForge.EVENT_BUS.register(SkinShuffleGameEventHandler.class);
SkinShufflePacketHandler.initialize();
final var mod = ModList.get().getModContainerById(SkinRestorer.MOD_ID).get();
mod.getEventBus().register(SkinShuffleModEventHandler.class);
}
}

View File

@@ -0,0 +1,31 @@
package net.lionarius.skinrestorer.neoforge.compat.skinshuffle;
import net.lionarius.skinrestorer.compat.skinshuffle.*;
import net.lionarius.skinrestorer.compat.skinshuffle.SkinShuffleCompatibility;
import net.minecraft.server.level.ServerPlayer;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent;
import net.neoforged.neoforge.network.handling.IPayloadContext;
import net.neoforged.neoforge.network.registration.HandlerThread;
public final class SkinShuffleModEventHandler {
private SkinShuffleModEventHandler() {}
@SubscribeEvent
public static void onRegisterPayloadHandlers(RegisterPayloadHandlersEvent event) {
final var registrar = event.registrar("1").optional().executesOn(HandlerThread.NETWORK);
registrar
.playToClient(SkinShuffleHandshakePayload.PACKET_ID, SkinShuffleHandshakePayload.PACKET_CODEC,
(payload, context) -> {})
.playToServer(SkinShuffleSkinRefreshV1Payload.PACKET_ID, SkinShuffleSkinRefreshV1Payload.PACKET_CODEC,
SkinShuffleModEventHandler::handleSkinRefreshPacket)
.playToServer(SkinShuffleSkinRefreshV2Payload.PACKET_ID, SkinShuffleSkinRefreshV2Payload.PACKET_CODEC,
SkinShuffleModEventHandler::handleSkinRefreshPacket);
}
private static void handleSkinRefreshPacket(SkinShuffleSkinRefreshPayload payload, IPayloadContext context) {
var player = (ServerPlayer) context.player();
SkinShuffleCompatibility.handleSkinRefresh(player.getServer(), player, payload);
}
}

View File

@@ -1,55 +0,0 @@
package net.lionarius.skinrestorer.neoforge.compat.skinshuffle;
import net.lionarius.skinrestorer.compat.skinshuffle.SkinShuffleCompatibility;
import net.lionarius.skinrestorer.compat.skinshuffle.*;
import net.neoforged.neoforge.network.NetworkConstants;
import net.neoforged.neoforge.network.NetworkEvent;
import net.neoforged.neoforge.network.NetworkRegistry;
import net.neoforged.neoforge.network.event.EventNetworkChannel;
public final class SkinShufflePacketHandler {
private SkinShufflePacketHandler() {
}
// there is no need for handshake channel but register it to not allow other mods to use it
private static final EventNetworkChannel HANDSHAKE_INSTANCE = NetworkRegistry.ChannelBuilder
.named(SkinShuffleHandshakePayload.PACKET_ID)
.serverAcceptedVersions(NetworkRegistry.acceptMissingOr("1"))
.clientAcceptedVersions(NetworkRegistry.acceptMissingOr("1"))
.networkProtocolVersion(() -> NetworkConstants.NETVERSION)
.eventNetworkChannel();
private static final EventNetworkChannel SKIN_REFRESH_V1_INSTANCE = NetworkRegistry.ChannelBuilder
.named(SkinShuffleSkinRefreshV1Payload.PACKET_ID)
.serverAcceptedVersions(NetworkRegistry.acceptMissingOr("1"))
.clientAcceptedVersions(NetworkRegistry.acceptMissingOr("1"))
.networkProtocolVersion(() -> NetworkConstants.NETVERSION)
.eventNetworkChannel();
private static final EventNetworkChannel SKIN_REFRESH_V2_INSTANCE = NetworkRegistry.ChannelBuilder
.named(SkinShuffleSkinRefreshV2Payload.PACKET_ID)
.serverAcceptedVersions(NetworkRegistry.acceptMissingOr("1"))
.clientAcceptedVersions(NetworkRegistry.acceptMissingOr("1"))
.networkProtocolVersion(() -> NetworkConstants.NETVERSION)
.eventNetworkChannel();
static void initialize() {
SKIN_REFRESH_V1_INSTANCE.addListener(SkinShufflePacketHandler::skinRefreshV1Listener);
SKIN_REFRESH_V2_INSTANCE.addListener(SkinShufflePacketHandler::skinRefreshV2Listener);
}
private static void skinRefreshV1Listener(NetworkEvent.ServerCustomPayloadEvent event) {
var payload = SkinShuffleSkinRefreshV1Payload.decode(event.getPayload());
handleSkinRefreshPacket(payload, event.getSource());
}
private static void skinRefreshV2Listener(NetworkEvent.ServerCustomPayloadEvent event) {
var payload = SkinShuffleSkinRefreshV2Payload.decode(event.getPayload());
handleSkinRefreshPacket(payload, event.getSource());
}
private static void handleSkinRefreshPacket(SkinShuffleSkinRefreshPayload payload, NetworkEvent.Context context) {
var player = context.getSender();
SkinShuffleCompatibility.handleSkinRefresh(player.getServer(), player, payload);
}
}

View File

@@ -10,6 +10,6 @@ public final class NeoForgeCompatibilityHelper implements CompatibilityHelper {
@Override
public void skinShuffle_sendHandshake(ServerPlayer player) {
// we can't use the packet distributor here because neoforge doesn't support sending packets to non-neoforge players
player.connection.connection.send(new ClientboundCustomPayloadPacket(SkinShuffleHandshakePayload.INSTANCE));
player.connection.getConnection().send(new ClientboundCustomPayloadPacket(SkinShuffleHandshakePayload.INSTANCE));
}
}

View File

@@ -17,14 +17,14 @@ config = "${mod_id}.mixins.json"
[[dependencies.${mod_id}]]
modId = "neoforge"
mandatory = true
type = "required"
versionRange = "[${neoforge_version},)"
ordering = "NONE"
side = "BOTH"
[[dependencies.${mod_id}]]
modId = "minecraft"
mandatory = true
type = "required"
versionRange = "${minecraft_version_range}"
ordering = "NONE"
side = "BOTH"

View File

@@ -71,5 +71,4 @@ rootProject.name = 'skin-restorer'
include('common')
include('fabric')
include('forge')
// There is no NeoForge for versions <1.20.2
// include('neoforge')
include('neoforge')