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

Compare commits

...

55 Commits

Author SHA1 Message Date
0524b5dab8 the worst bug I encountered in gson 2.10.1 2026-01-14 23:39:53 +03:00
301428147d update CHANGELOG 2026-01-14 21:53:09 +03:00
2e655ce1f3 bump version 2026-01-14 19:06:02 +03:00
7dcd1d4e81 reorder mixins 2026-01-14 18:33:21 +03:00
1aa606038e add forceFirstJoinSkinFetch config 2026-01-14 18:33:18 +03:00
e832e02fd4 add collection provider 2026-01-14 18:32:58 +03:00
ffd2a0dba7 update mineskin 2026-01-12 23:28:32 +03:00
76e801c944 use parchment 2026-01-10 14:55:31 +03:00
69a561f679 port 1.21.11 2025-12-15 23:27:30 +03:00
f36390a3d5 port to 1.21.9 2025-10-04 22:56:14 +03:00
583205febc update CHANGELOG 2025-08-17 17:02:22 +03:00
fb7a4d11e9 bump version 2025-08-17 17:02:22 +03:00
1d8472e35c fix server freeze when loading head 2025-08-17 17:02:00 +03:00
f604ac2c8b add support for additional modloaders when publishing 2025-07-24 03:33:05 +03:00
8d4c2e9f83 add 1.21.8 to supported versions 2025-07-24 03:22:56 +03:00
84a06898a2 do not replace skin for head if on client and not in singleplayer 2025-07-24 03:21:43 +03:00
11ecf88eb2 add OnServerStopped event 2025-07-24 03:20:16 +03:00
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
760ac65ab3 bump version 2025-05-24 13:50:29 +03:00
2e7a9edc20 update CHANGELOG.md 2025-05-24 13:50:17 +03:00
8457e6f4ab apply mixins at higher priority (fixes #52) 2025-05-24 13:33:11 +03:00
66a9c1fbbf update mixins compatibilityLevel to java 17 2025-05-24 13:31:57 +03:00
e3754cda90 update bug_report.yaml 2025-05-24 12:03:52 +03:00
58 changed files with 649 additions and 169 deletions

View File

@@ -58,10 +58,12 @@ body:
id: steps
attributes:
label: Reproduction Steps
description: Provide step-by-step instructions or a video showing how to reproduce the issue.
placeholder: |
1.
2.
3.
Or a video demonstrating the issue.
validations:
required: true

1
.gitignore vendored
View File

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

View File

@@ -4,6 +4,48 @@ 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.5.0] - 2026-01-14
### Added
- Added collection skin provider (allows assigning random skins from a predefined set)
- Added `forceFirstJoinSkinFetch` config option to force skin fetch on first join even if player already has a skin
## [2.4.3] - 2025-07-25
### Fixed
- Fixed crash on client when loading player head skin (fixes [#63](https://github.com/Suiranoil/SkinRestorer/issues/63) and [#64](https://github.com/Suiranoil/SkinRestorer/issues/64))
- Fixed server freeze when loading player head skin
## [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))
## [2.3.1] - 2025-05-03
### Added
- Added support for minecraft 1.19-1.19.4

View File

@@ -1,4 +1,3 @@
### Added
- Added support for minecraft 1.19-1.19.4
### Changed
- Use services and session server urls from environment
- Added collection skin provider (allows assigning random skins from a predefined set) (see [wiki](https://github.com/Suiranoil/SkinRestorer/wiki/Configuration#providerscollection))
- Added `forceFirstJoinSkinFetch` config option to force skin fetch on first join even if player already has a skin (see [wiki](https://github.com/Suiranoil/SkinRestorer/wiki/Configuration#forcefirstjoinskinfetch))

View File

@@ -1,6 +1,6 @@
plugins {
// see https://fabricmc.net/develop/ for new versions
id 'fabric-loom' version '1.10-SNAPSHOT' apply false
id 'fabric-loom' version '1.13-SNAPSHOT' apply false
// see https://projects.neoforged.net/neoforged/moddevgradle for new versions
id 'net.neoforged.moddev' version '2.0.+' apply false
// see https://files.minecraftforge.net/net/minecraftforge/gradle/ForgeGradle/ for new versions

View File

@@ -3,14 +3,17 @@ 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)
if (project.hasProperty('additional_modloaders') && !additional_modloaders.isEmpty())
{
def loaders = additional_modloaders.split(',')
for (loader in loaders)
modLoaders.add(loader)
}
type = STABLE
version = project.version
displayName = "[${project.name.capitalize()}] ${mod_name} ${mod_version}"

View File

@@ -1,10 +1,12 @@
package net.lionarius.skinrestorer;
import com.mojang.authlib.GameProfile;
import com.google.common.base.Throwables;
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.mixin.PlayerAccessor;
import net.lionarius.skinrestorer.platform.Services;
import net.lionarius.skinrestorer.skin.SkinIO;
import net.lionarius.skinrestorer.skin.SkinStorage;
@@ -13,10 +15,11 @@ import net.lionarius.skinrestorer.skin.provider.*;
import net.lionarius.skinrestorer.translation.Translation;
import net.lionarius.skinrestorer.util.*;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.level.storage.LevelResource;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -35,6 +38,7 @@ public final class SkinRestorer {
private static Path configDir;
private static Config config;
private static TickedScheduler tickedScheduler;
private static MinecraftServer minecraftServer;
private SkinRestorer() {}
@@ -58,12 +62,16 @@ public final class SkinRestorer {
return SkinRestorer.tickedScheduler;
}
public static @Nullable MinecraftServer getMinecraftServer() {
return SkinRestorer.minecraftServer;
}
public static Optional<SkinProvider> getProvider(String name) {
return Optional.ofNullable(SkinRestorer.providersRegistry.get(name));
}
public static ResourceLocation resourceLocation(String name) {
return ResourceLocation.fromNamespaceAndPath(SkinRestorer.MOD_ID, name);
public static Identifier resourceLocation(String name) {
return Identifier.fromNamespaceAndPath(SkinRestorer.MOD_ID, name);
}
public static String assetPath(String name) {
@@ -80,6 +88,7 @@ public final class SkinRestorer {
SkinRestorer.registerDefaultSkinProvider(MojangSkinProvider.PROVIDER_NAME, SkinProvider.MOJANG, SkinRestorer.getConfig().providersConfig().mojang());
SkinRestorer.registerDefaultSkinProvider(ElyBySkinProvider.PROVIDER_NAME, SkinProvider.ELY_BY, SkinRestorer.getConfig().providersConfig().ely_by());
SkinRestorer.registerDefaultSkinProvider(MineskinSkinProvider.PROVIDER_NAME, SkinProvider.MINESKIN, SkinRestorer.getConfig().providersConfig().mineskin());
SkinRestorer.registerDefaultSkinProvider(CollectionSkinProvider.PROVIDER_NAME, SkinProvider.COLLECTION, SkinRestorer.getConfig().providersConfig().collection());
}
private static void registerDefaultSkinProvider(String defaultName, SkinProvider provider, BuiltInProviderConfig config) {
@@ -98,25 +107,29 @@ public final class SkinRestorer {
MojangSkinProvider.reload();
ElyBySkinProvider.reload();
MineskinSkinProvider.reload();
CollectionSkinProvider.reload();
}
public static Collection<ServerPlayer> applySkin(MinecraftServer server, Iterable<GameProfile> targets, SkinValue value, boolean save) {
public static Collection<ServerPlayer> applySkin(MinecraftServer server, Iterable<ServerPlayer> targets, SkinValue value, boolean save) {
var acceptedPlayers = new HashSet<ServerPlayer>();
for (var profile : targets) {
if (!SkinRestorer.getSkinStorage().hasSavedSkin(profile.getId()))
value = value.setOriginalValue(PlayerUtils.getPlayerSkin(profile));
for (var player : targets) {
var profile = player.getGameProfile();
var skin = PlayerUtils.getPlayerSkin(profile);
if (PlayerUtils.areSkinPropertiesEquals(value.value(), PlayerUtils.getPlayerSkin(profile)))
if (!SkinRestorer.getSkinStorage().hasSavedSkin(profile.id()))
value = value.setOriginalValue(skin);
if (PlayerUtils.areSkinPropertiesEquals(value.value(), skin))
continue;
if (save)
SkinRestorer.getSkinStorage().setSkin(profile.getId(), value);
SkinRestorer.getSkinStorage().setSkin(profile.id(), value);
PlayerUtils.applyRestoredSkin(profile, value.value());
var newProfile = PlayerUtils.applyRestoredSkin(profile, value.value());
((PlayerAccessor) player).setGameProfile(newProfile);
var player = server.getPlayerList().getPlayer(profile.getId());
if (player == null)
if (player.connection == null)
continue;
PlayerUtils.refreshPlayer(player);
@@ -128,13 +141,13 @@ public final class SkinRestorer {
return acceptedPlayers;
}
public static Collection<ServerPlayer> applySkin(MinecraftServer server, Iterable<GameProfile> targets, SkinValue value) {
public static Collection<ServerPlayer> applySkin(MinecraftServer server, Iterable<ServerPlayer> targets, SkinValue value) {
return SkinRestorer.applySkin(server, targets, value, true);
}
public static CompletableFuture<Result<Collection<ServerPlayer>, String>> setSkinAsync(
MinecraftServer server,
Collection<GameProfile> targets,
Collection<ServerPlayer> targets,
SkinProviderContext context,
boolean save
) {
@@ -147,7 +160,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 +169,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());
});
}
@@ -171,6 +184,14 @@ public final class SkinRestorer {
SkinRestorer.skinStorage = new SkinStorage(new SkinIO(worldSkinDirectory));
SkinRestorer.tickedScheduler = new TickedScheduler(server);
server.addTickable(SkinRestorer.tickedScheduler);
SkinRestorer.minecraftServer = server;
}
public static void onServerStopped(MinecraftServer server) {
SkinRestorer.skinStorage = null;
SkinRestorer.tickedScheduler = null;
SkinRestorer.minecraftServer = null;
}
public static void onCommandRegister(CommandDispatcher<CommandSourceStack> dispatcher) {

View File

@@ -1,6 +1,5 @@
package net.lionarius.skinrestorer.command;
import com.mojang.authlib.GameProfile;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.ArgumentBuilder;
@@ -16,12 +15,15 @@ import net.lionarius.skinrestorer.skin.provider.SkinProviderContext;
import net.lionarius.skinrestorer.translation.Translation;
import net.lionarius.skinrestorer.util.PlayerUtils;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.GameProfileArgument;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.players.NameAndId;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Objects;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
@@ -54,7 +56,7 @@ public final class SkinCommand {
base.then(
literal("config")
.requires(commandSourceStack -> commandSourceStack.hasPermission(4))
.requires(commandSourceStack -> Commands.LEVEL_OWNERS.check(commandSourceStack.permissions()))
.then(literal("reload").executes(SkinCommand::configReloadSubcommand))
);
@@ -72,37 +74,41 @@ public final class SkinCommand {
SkinProviderContext context = null;
var save = true;
if (!SkinRestorer.getSkinStorage().hasSavedSkin(profile.getId())) {
if (profile.getProperties().containsKey(PlayerUtils.TEXTURES_KEY)) {
if (!SkinRestorer.getSkinStorage().hasSavedSkin(profile.id())) {
if (profile.properties().containsKey(PlayerUtils.TEXTURES_KEY)) {
save = false;
context = MojangSkinProvider.skinProviderContextFromProfile(profile);
}
} else {
context = SkinRestorer.getSkinStorage().getSkin(profile.getId()).toProviderContext();
context = SkinRestorer.getSkinStorage().getSkin(profile.id()).toProviderContext();
}
if (context == null)
return 0;
return SkinCommand.setSubcommand(src, Collections.singleton(profile), context, save, false);
return SkinCommand.setSubcommand(src, Collections.singleton(new NameAndId(profile)), context, save, false);
}
private static int resetSubcommand(
CommandSourceStack src,
Collection<GameProfile> targets,
Collection<NameAndId> targets,
boolean setByOperator
) {
var updatedPlayers = new HashSet<ServerPlayer>();
for (var profile : targets) {
for (var nameAndId : targets) {
SkinValue skin = null;
if (SkinRestorer.getSkinStorage().hasSavedSkin(profile.getId()))
skin = SkinRestorer.getSkinStorage().getSkin(profile.getId()).replaceValueWithOriginal();
if (SkinRestorer.getSkinStorage().hasSavedSkin(nameAndId.id()))
skin = SkinRestorer.getSkinStorage().getSkin(nameAndId.id()).replaceValueWithOriginal();
if (skin == null)
continue;
var updatedPlayer = SkinRestorer.applySkin(src.getServer(), Collections.singleton(profile), skin, false);
SkinRestorer.getSkinStorage().deleteSkin(profile.getId());
var player = src.getServer().getPlayerList().getPlayer(nameAndId.id());
if (player == null)
continue;
var updatedPlayer = SkinRestorer.applySkin(src.getServer(), Collections.singleton(player), skin, false);
SkinRestorer.getSkinStorage().deleteSkin(nameAndId.id());
updatedPlayers.addAll(updatedPlayer);
}
@@ -118,19 +124,24 @@ public final class SkinCommand {
if (src.getPlayer() == null)
return 0;
return resetSubcommand(src, Collections.singleton(src.getPlayer().getGameProfile()), false);
return resetSubcommand(src, Collections.singleton(src.getPlayer().nameAndId()), false);
}
private static int setSubcommand(
CommandSourceStack src,
Collection<GameProfile> targets,
Collection<NameAndId> targets,
SkinProviderContext context,
boolean save,
boolean setByOperator
) {
src.sendSystemMessage(Translation.translatableWithFallback(Translation.COMMAND_SKIN_LOADING_KEY));
SkinRestorer.setSkinAsync(src.getServer(), targets, context, save).thenAccept(result -> {
var profileTargets = targets.stream()
.map(nameAndId -> src.getServer().getPlayerList().getPlayer(nameAndId.id()))
.filter(Objects::nonNull)
.toList();
SkinRestorer.setSkinAsync(src.getServer(), profileTargets, context, save).thenAccept(result -> {
if (result.isError()) {
src.sendFailure(Translation.translatableWithFallback(
Translation.COMMAND_SKIN_FAILED_KEY,
@@ -149,7 +160,7 @@ public final class SkinCommand {
private static int setSubcommand(
CommandSourceStack src,
Collection<GameProfile> targets,
Collection<NameAndId> targets,
SkinProviderContext context,
boolean setByOperator
) {
@@ -163,7 +174,7 @@ public final class SkinCommand {
if (src.getPlayer() == null)
return 0;
return setSubcommand(src, Collections.singleton(src.getPlayer().getGameProfile()), context, false);
return setSubcommand(src, Collections.singleton(src.getPlayer().nameAndId()), context, false);
}
private static int configReloadSubcommand(CommandContext<CommandSourceStack> context) {
@@ -256,10 +267,10 @@ public final class SkinCommand {
}
private static RequiredArgumentBuilder<CommandSourceStack, GameProfileArgument.Result> makeTargetsArgument(
BiFunction<CommandContext<CommandSourceStack>, Collection<GameProfile>, Integer> consumer
BiFunction<CommandContext<CommandSourceStack>, Collection<NameAndId>, Integer> consumer
) {
return argument("targets", GameProfileArgument.gameProfile())
.requires(source -> source.hasPermission(2))
.requires(source -> Commands.LEVEL_GAMEMASTERS.check(source.permissions()))
.executes(context -> consumer.apply(context, GameProfileArgument.getGameProfiles(context, "targets")));
}
}

View File

@@ -5,7 +5,7 @@ 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.resources.Identifier;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
@@ -23,8 +23,8 @@ public class SkinShuffleCompatibility {
return SkinShuffleCompatibility.SHOULD_APPLY;
}
public static ResourceLocation resourceLocation(String name) {
return ResourceLocation.fromNamespaceAndPath(SkinShuffleCompatibility.MOD_ID, name);
public static Identifier resourceLocation(String name) {
return Identifier.fromNamespaceAndPath(SkinShuffleCompatibility.MOD_ID, name);
}
public static void onPlayerJoin(ServerPlayer player) {
@@ -43,7 +43,7 @@ public class SkinShuffleCompatibility {
server.execute(() -> {
SkinRestorer.applySkin(
server,
Collections.singleton(player.getGameProfile()),
Collections.singleton(player),
new SkinValue(SkinShuffleSkinProvider.PROVIDER_NAME, null, null, property),
!server.usesAuthentication()
);

View File

@@ -22,7 +22,7 @@ public record SkinShuffleSkinRefreshV1Payload(
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)));
}

View File

@@ -14,7 +14,7 @@ public record SkinShuffleSkinRefreshV2Payload(
SkinShuffleSkinRefreshV2Payload::encode,
SkinShuffleSkinRefreshV2Payload::decode
);
public static void encode(FriendlyByteBuf buf, SkinShuffleSkinRefreshV2Payload value) {
var textureProperty = value.textureProperty();
@@ -27,7 +27,7 @@ public record SkinShuffleSkinRefreshV2Payload(
buf.writeUtf(textureProperty.signature());
}
}
public static SkinShuffleSkinRefreshV2Payload decode(FriendlyByteBuf buf) {
if (buf.readBoolean()) {
return new SkinShuffleSkinRefreshV2Payload(new Property(buf.readUtf(), buf.readUtf(), buf.readUtf()));

View File

@@ -22,6 +22,8 @@ public final class Config implements GsonPostProcessable {
private boolean fetchSkinOnFirstJoin = true;
private boolean forceFirstJoinSkinFetch = false;
private FirstJoinSkinProvider firstJoinSkinProvider = FirstJoinSkinProvider.MOJANG;
private String proxy = "";
@@ -47,6 +49,10 @@ public final class Config implements GsonPostProcessable {
return this.fetchSkinOnFirstJoin;
}
public boolean forceFirstJoinSkinFetch() {
return this.forceFirstJoinSkinFetch;
}
public FirstJoinSkinProvider firstJoinSkinProvider() {
return this.firstJoinSkinProvider;
}

View File

@@ -1,6 +1,7 @@
package net.lionarius.skinrestorer.config;
import com.google.gson.annotations.SerializedName;
import net.lionarius.skinrestorer.skin.provider.CollectionSkinProvider;
import net.lionarius.skinrestorer.skin.provider.ElyBySkinProvider;
import net.lionarius.skinrestorer.skin.provider.MojangSkinProvider;
@@ -8,7 +9,9 @@ public enum FirstJoinSkinProvider {
@SerializedName(value = "MOJANG", alternate = {"mojang"})
MOJANG(MojangSkinProvider.PROVIDER_NAME),
@SerializedName(value = "ELY.BY", alternate = {"ely.by", "ELY_BY", "ely_by"})
ELY_BY(ElyBySkinProvider.PROVIDER_NAME);
ELY_BY(ElyBySkinProvider.PROVIDER_NAME),
@SerializedName(value = "COLLECTION", alternate = {"collection"})
COLLECTION(CollectionSkinProvider.PROVIDER_NAME);
private final String name;

View File

@@ -8,8 +8,13 @@ public abstract class BuiltInProviderConfig implements GsonPostProcessable {
protected String name;
protected CacheConfig cache;
public BuiltInProviderConfig(String name, CacheConfig cache) {
this.enabled = true;
this(name, cache, true);
}
public BuiltInProviderConfig(String name, CacheConfig cache, boolean enabled) {
this.enabled = enabled;
this.name = name;
this.cache = cache;
}

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

@@ -1,52 +1,65 @@
package net.lionarius.skinrestorer.config.provider;
import net.lionarius.skinrestorer.SkinRestorer;
import net.lionarius.skinrestorer.config.provider.collection.CollectionProviderConfig;
import net.lionarius.skinrestorer.util.gson.GsonPostProcessable;
public final class ProvidersConfig implements GsonPostProcessable {
public static final ProvidersConfig DEFAULT = new ProvidersConfig(
new MojangProviderConfig(),
new ElyByProviderConfig(),
new MineskinProviderConfig()
new MineskinProviderConfig(),
new CollectionProviderConfig()
);
private MojangProviderConfig mojang;
private ElyByProviderConfig ely_by;
private MineskinProviderConfig mineskin;
public ProvidersConfig(MojangProviderConfig mojang, ElyByProviderConfig ely_by, MineskinProviderConfig mineskin) {
private CollectionProviderConfig collection;
public ProvidersConfig(MojangProviderConfig mojang, ElyByProviderConfig ely_by, MineskinProviderConfig mineskin, CollectionProviderConfig collection) {
this.mojang = mojang;
this.ely_by = ely_by;
this.mineskin = mineskin;
this.collection = collection;
}
public MojangProviderConfig mojang() {
return this.mojang;
}
public ElyByProviderConfig ely_by() {
return this.ely_by;
}
public MineskinProviderConfig mineskin() {
return this.mineskin;
}
public CollectionProviderConfig collection() {
return this.collection;
}
@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();
}
if (this.collection == null) {
SkinRestorer.LOGGER.warn("Collection provider config is null, using default");
this.collection = ProvidersConfig.DEFAULT.collection();
}
}
}

View File

@@ -0,0 +1,32 @@
package net.lionarius.skinrestorer.config.provider.collection;
import com.google.gson.annotations.JsonAdapter;
import net.lionarius.skinrestorer.config.provider.BuiltInProviderConfig;
import net.lionarius.skinrestorer.config.provider.CacheConfig;
import net.lionarius.skinrestorer.skin.provider.CollectionSkinProvider;
import net.lionarius.skinrestorer.util.gson.GsonPostProcessable;
import java.util.ArrayList;
import java.util.List;
public final class CollectionProviderConfig extends BuiltInProviderConfig implements GsonPostProcessable {
private static final CacheConfig DEFAULT_CACHE_VALUE = new CacheConfig(true, 604800);
@JsonAdapter(CollectionSkinSourceListDeserializer.class)
private List<CollectionSkinSource> sources = new ArrayList<>();
public CollectionProviderConfig() {
super(CollectionSkinProvider.PROVIDER_NAME, DEFAULT_CACHE_VALUE, false);
}
public List<CollectionSkinSource> sources() {
return this.sources;
}
@Override
public void gsonPostProcess() {
if (this.sources == null) {
this.sources = new ArrayList<>();
}
}
}

View File

@@ -0,0 +1,60 @@
package net.lionarius.skinrestorer.config.provider.collection;
import net.lionarius.skinrestorer.SkinRestorer;
import net.lionarius.skinrestorer.skin.SkinVariant;
import net.lionarius.skinrestorer.util.gson.GsonPostProcessable;
import org.jetbrains.annotations.Nullable;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
public final class CollectionSkinFile implements CollectionSkinSource, GsonPostProcessable {
private String path = "";
private SkinVariant variant = SkinVariant.CLASSIC;
@Override
public @Nullable URI uri() {
if (this.path.isEmpty())
return null;
try {
var filePath = SkinRestorer.getConfigDir().resolve(this.path);
if (!Files.exists(filePath)) {
SkinRestorer.LOGGER.warn("Skin file does not exist: {}", this.path);
return null;
}
if (!Files.isRegularFile(filePath)) {
SkinRestorer.LOGGER.warn("Skin path is not a file: {}", this.path);
return null;
}
if (!this.path.toLowerCase().endsWith(".png")) {
SkinRestorer.LOGGER.warn("Skin file is not a PNG file: {}", this.path);
return null;
}
return filePath.toUri();
} catch (Exception e) {
SkinRestorer.LOGGER.warn("Invalid file path: {}", this.path, e);
return null;
}
}
@Override
public SkinVariant variant() {
return this.variant;
}
@Override
public void gsonPostProcess() {
if (this.path == null) {
this.path = "";
}
if (this.variant == null) {
this.variant = SkinVariant.CLASSIC;
}
}
}

View File

@@ -0,0 +1,12 @@
package net.lionarius.skinrestorer.config.provider.collection;
import net.lionarius.skinrestorer.skin.SkinVariant;
import org.jetbrains.annotations.Nullable;
import java.net.URI;
public interface CollectionSkinSource {
@Nullable URI uri();
SkinVariant variant();
}

View File

@@ -0,0 +1,35 @@
package net.lionarius.skinrestorer.config.provider.collection;
import com.google.gson.*;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class CollectionSkinSourceListDeserializer implements JsonSerializer<List<CollectionSkinSource>>, JsonDeserializer<List<CollectionSkinSource>> {
@Override
public JsonElement serialize(List<CollectionSkinSource> src, Type typeOfT, JsonSerializationContext context) {
return context.serialize(src, List.class);
}
@Override
public List<CollectionSkinSource> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
List<CollectionSkinSource> sources = new ArrayList<>();
if (json.isJsonArray()) {
for (JsonElement element : json.getAsJsonArray()) {
if (element.isJsonObject()) {
JsonObject obj = element.getAsJsonObject();
if (obj.has("url")) {
sources.add(context.deserialize(obj, CollectionSkinUrl.class));
} else if (obj.has("path")) {
sources.add(context.deserialize(obj, CollectionSkinFile.class));
}
}
}
}
return sources;
}
}

View File

@@ -0,0 +1,41 @@
package net.lionarius.skinrestorer.config.provider.collection;
import net.lionarius.skinrestorer.SkinRestorer;
import net.lionarius.skinrestorer.skin.SkinVariant;
import net.lionarius.skinrestorer.util.gson.GsonPostProcessable;
import org.jetbrains.annotations.Nullable;
import java.net.URI;
public final class CollectionSkinUrl implements CollectionSkinSource, GsonPostProcessable {
private String url = "";
private SkinVariant variant = SkinVariant.CLASSIC;
@Override
public @Nullable URI uri() {
try {
if (this.url.isEmpty())
return null;
return new URI(this.url);
} catch (Exception e) {
SkinRestorer.LOGGER.warn("Invalid URI: {}", this.url, e);
return null;
}
}
@Override
public SkinVariant variant() {
return this.variant;
}
@Override
public void gsonPostProcess() {
if (this.url == null) {
this.url = "";
}
if (this.variant == null) {
this.variant = SkinVariant.CLASSIC;
}
}
}

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

@@ -9,5 +9,5 @@ import org.spongepowered.asm.mixin.gen.Accessor;
public interface ChunkMapAccessor {
@Accessor
Int2ObjectMap<Object> getEntityMap();
Int2ObjectMap<TrackedEntityAccessorInvoker> getEntityMap();
}

View File

@@ -0,0 +1,15 @@
package net.lionarius.skinrestorer.mixin;
import com.mojang.authlib.GameProfile;
import net.minecraft.world.entity.player.Player;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Mutable;
import org.spongepowered.asm.mixin.gen.Accessor;
@Mixin(Player.class)
public interface PlayerAccessor {
@Accessor("gameProfile")
@Mutable
void setGameProfile(GameProfile properties);
}

View File

@@ -57,6 +57,6 @@ public abstract class PlayerListMixin {
@Unique
private static void skinrestorer$tryApplySkin(MinecraftServer server, ServerPlayer player) {
if (SkinRestorer.getSkinStorage().hasSavedSkin(player.getUUID()))
SkinRestorer.applySkin(server, Collections.singleton(player.getGameProfile()), SkinRestorer.getSkinStorage().getSkin(player.getUUID()));
SkinRestorer.applySkin(server, Collections.singleton(player), SkinRestorer.getSkinStorage().getSkin(player.getUUID()));
}
}

View File

@@ -2,6 +2,7 @@ package net.lionarius.skinrestorer.mixin;
import com.mojang.authlib.GameProfile;
import net.lionarius.skinrestorer.SkinRestorer;
import net.lionarius.skinrestorer.config.FirstJoinSkinProvider;
import net.lionarius.skinrestorer.skin.SkinValue;
import net.lionarius.skinrestorer.skin.provider.SkinProviderContext;
import net.lionarius.skinrestorer.util.PlayerUtils;
@@ -27,7 +28,7 @@ public abstract class ServerLoginPacketListenerImplMixin {
private CompletableFuture<Void> skinrestorer$pendingSkin;
@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;"),
target = "Lnet/minecraft/server/players/PlayerList;canPlayerLogin(Ljava/net/SocketAddress;Lnet/minecraft/server/players/NameAndId;)Lnet/minecraft/network/chat/Component;"),
cancellable = true)
public void waitForSkin(CallbackInfo ci) {
if (skinrestorer$pendingSkin == null) {
@@ -37,14 +38,14 @@ public abstract class ServerLoginPacketListenerImplMixin {
assert profile != null;
var originalSkin = PlayerUtils.getPlayerSkin(profile);
if (SkinRestorer.getSkinStorage().hasSavedSkin(profile.getId())) {
if (SkinRestorer.getSkinStorage().hasSavedSkin(profile.id())) {
if (originalSkin != null) { // update to the latest official skin
var value = SkinRestorer.getSkinStorage().getSkin(profile.getId());
SkinRestorer.getSkinStorage().setSkin(profile.getId(), value.setOriginalValue(originalSkin));
var value = SkinRestorer.getSkinStorage().getSkin(profile.id());
SkinRestorer.getSkinStorage().setSkin(profile.id(), value.setOriginalValue(originalSkin));
}
if (SkinRestorer.getConfig().refreshSkinOnJoin()) {
var currentSkin = SkinRestorer.getSkinStorage().getSkin(profile.getId());
var currentSkin = SkinRestorer.getSkinStorage().getSkin(profile.id());
var context = currentSkin.toProviderContext();
skinrestorer$fetchSkin(profile, context);
@@ -53,10 +54,16 @@ public abstract class ServerLoginPacketListenerImplMixin {
return null;
}
if (originalSkin == null && SkinRestorer.getConfig().fetchSkinOnFirstJoin()) {
var config = SkinRestorer.getConfig();
var provider = config.firstJoinSkinProvider();
var shouldFetch = (originalSkin == null && config.fetchSkinOnFirstJoin()) ||
(originalSkin != null && config.forceFirstJoinSkinFetch() && provider != FirstJoinSkinProvider.MOJANG);
if (shouldFetch) {
var context = new SkinProviderContext(
SkinRestorer.getConfig().firstJoinSkinProvider().getName(),
profile.getName(),
provider.getName(),
profile.name(),
null
);
skinrestorer$fetchSkin(profile, context);
@@ -72,7 +79,7 @@ public abstract class ServerLoginPacketListenerImplMixin {
@Unique
private static void skinrestorer$fetchSkin(GameProfile profile, SkinProviderContext context) {
SkinRestorer.LOGGER.debug("Fetching {}'s skin", profile.getName());
SkinRestorer.LOGGER.debug("Fetching {}'s skin", profile.name());
var result = SkinRestorer.getProvider(context.name()).map(
provider -> provider.fetchSkin(context.argument(), context.variant())
@@ -80,9 +87,9 @@ public abstract class ServerLoginPacketListenerImplMixin {
if (!result.isError()) {
var value = SkinValue.fromProviderContextWithValue(context, result.getSuccessValue().orElse(null));
SkinRestorer.getSkinStorage().setSkin(profile.getId(), value);
SkinRestorer.getSkinStorage().setSkin(profile.id(), 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

@@ -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

@@ -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

@@ -1,8 +1,11 @@
package net.lionarius.skinrestorer.skin;
import com.google.gson.annotations.SerializedName;
public enum SkinVariant {
@SerializedName(value = "classic", alternate = {"CLASSIC"})
CLASSIC("classic"),
@SerializedName(value = "slim", alternate = {"SLIM"})
SLIM("slim");
private final String name;

View File

@@ -0,0 +1,91 @@
package net.lionarius.skinrestorer.skin.provider;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.mojang.authlib.properties.Property;
import it.unimi.dsi.fastutil.Pair;
import net.lionarius.skinrestorer.SkinRestorer;
import net.lionarius.skinrestorer.config.provider.collection.CollectionSkinSource;
import net.lionarius.skinrestorer.skin.SkinVariant;
import net.lionarius.skinrestorer.util.Result;
import org.jetbrains.annotations.NotNull;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
public final class CollectionSkinProvider implements SkinProvider {
public static final String PROVIDER_NAME = "collection";
private static LoadingCache<Integer, Optional<Property>> SKIN_CACHE;
private static List<Pair<URI, SkinVariant>> COLLECTION_SKINS;
public static void reload() {
COLLECTION_SKINS = loadCollectionSkins();
createCache();
}
private static List<Pair<URI, SkinVariant>> loadCollectionSkins() {
List<Pair<URI, SkinVariant>> skins = new ArrayList<>();
var config = SkinRestorer.getConfig().providersConfig().collection();
for (CollectionSkinSource source : config.sources()) {
var uri = source.uri();
if (uri != null) {
skins.add(Pair.of(uri, source.variant()));
}
}
return skins;
}
private static void createCache() {
var config = SkinRestorer.getConfig().providersConfig().collection();
var time = config.cache().enabled() ? config.cache().duration() : 0;
SKIN_CACHE = CacheBuilder.newBuilder()
.expireAfterWrite(time, TimeUnit.SECONDS)
.build(new CacheLoader<>() {
@Override
public @NotNull Optional<Property> load(@NotNull Integer key) throws Exception {
var skinEntry = COLLECTION_SKINS.get(key);
return MineskinSkinProvider.loadSkin(skinEntry.first(), skinEntry.second());
}
});
}
@Override
public String getArgumentName() {
return "seed";
}
@Override
public boolean hasVariantSupport() {
return false;
}
@Override
public Result<Optional<Property>, Exception> fetchSkin(String argument, SkinVariant variant) {
if (COLLECTION_SKINS.isEmpty()) {
return Result.error(new IllegalStateException("No collection skins configured"));
}
var skinIndex = Math.abs(argument.hashCode()) % COLLECTION_SKINS.size();
try {
return Result.success(SKIN_CACHE.get(skinIndex));
} catch (UncheckedExecutionException e) {
return Result.error((Exception) e.getCause());
} catch (Exception e) {
return Result.error(e);
}
}
}

View File

@@ -106,6 +106,6 @@ public final class ElyBySkinProvider implements SkinProvider {
if (response.statusCode() != 200)
throw new IllegalArgumentException("no profile with name " + username);
return JsonUtils.fromJson(response.body(), MinecraftProfilePropertiesResponse.class).toProfile();
return JsonUtils.fromJson(response.body(), MinecraftProfilePropertiesResponse.class).profile();
}
}

View File

@@ -22,6 +22,8 @@ import org.mineskin.response.QueueResponse;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
@@ -43,7 +45,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,
@@ -93,13 +96,18 @@ public final class MineskinSkinProvider implements SkinProvider {
}
}
private static Optional<Property> loadSkin(URI uri, SkinVariant variant) throws Exception {
static Optional<Property> loadSkin(URI uri, SkinVariant variant) throws Exception {
var mineskinVariant = switch (variant) {
case CLASSIC -> Variant.CLASSIC;
case SLIM -> Variant.SLIM;
};
var request = GenerateRequest.url(uri)
var request = "file".equals(uri.getScheme())
? GenerateRequest.upload(Files.newInputStream(Path.of(uri)))
.variant(mineskinVariant)
.name("skinrestorer-skin")
.visibility(Visibility.UNLISTED)
: GenerateRequest.url(uri)
.variant(mineskinVariant)
.name("skinrestorer-skin")
.visibility(Visibility.UNLISTED);

View File

@@ -8,14 +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.authlib.yggdrasil.response.NameAndId;
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.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.server.players.CachedUserNameToIdResolver;
import net.minecraft.util.StringUtil;
import org.jetbrains.annotations.NotNull;
@@ -30,13 +32,11 @@ import java.util.concurrent.TimeUnit;
public final class MojangSkinProvider implements SkinProvider {
public static final String PROVIDER_NAME = "mojang";
public static final String PROFILE_CACHE_FILENAME = "mojang_profile_cache.json";
private static final Environment ENVIRONMENT;
private static final URI SERVICES_SERVER_URI;
private static final URI SESSION_SERVER_URI;
public static final String PROFILE_CACHE_FILENAME = "mojang_profile_cache.json";
private static final GameProfileCache PROFILE_CACHE;
private static final CachedUserNameToIdResolver PROFILE_CACHE;
private static LoadingCache<UUID, Optional<Property>> SKIN_CACHE;
@@ -50,26 +50,26 @@ public final class MojangSkinProvider implements SkinProvider {
throw new IllegalArgumentException(e);
}
PROFILE_CACHE = new GameProfileCache(new GameProfileRepository() {
PROFILE_CACHE = new CachedUserNameToIdResolver(new GameProfileRepository() {
@Override
public void findProfilesByNames(String[] names, ProfileLookupCallback callback) {
for (var name : names) {
try {
var profile = MojangSkinProvider.getProfile(name);
callback.onProfileLookupSucceeded(profile);
callback.onProfileLookupSucceeded(profile.name(), profile.id());
} catch (IOException e) {
callback.onProfileLookupFailed(name, e);
throw new TransparentException(e);
}
}
}
@Override
public Optional<GameProfile> findProfileByName(String name) {
public Optional<NameAndId> findProfileByName(String name) {
try {
var profile = MojangSkinProvider.getProfile(name);
return Optional.of(profile);
return Optional.of(new NameAndId(profile.id(), profile.name()));
} catch (IOException e) {
return Optional.empty();
throw new TransparentException(e);
}
}
}, SkinRestorer.getConfigDir().resolve(PROFILE_CACHE_FILENAME).toFile());
@@ -94,7 +94,7 @@ public final class MojangSkinProvider implements SkinProvider {
}
public static SkinProviderContext skinProviderContextFromProfile(GameProfile gameProfile) {
return new SkinProviderContext(MojangSkinProvider.PROVIDER_NAME, gameProfile.getName(), null);
return new SkinProviderContext(MojangSkinProvider.PROVIDER_NAME, gameProfile.name(), null);
}
@Override
@@ -117,7 +117,7 @@ public final class MojangSkinProvider implements SkinProvider {
if (cachedProfile.isEmpty())
throw new IllegalArgumentException("no profile found for " + username);
return Result.success(SKIN_CACHE.get(cachedProfile.get().getId()));
return Result.success(SKIN_CACHE.get(cachedProfile.get().id()));
} catch (UncheckedExecutionException e) {
return Result.error((Exception) e.getCause());
} catch (Exception e) {
@@ -132,7 +132,7 @@ public final class MojangSkinProvider implements SkinProvider {
return Optional.ofNullable(textures);
}
private static GameProfile getProfile(final String name) throws IOException {
private static NameAndId getProfile(final String name) throws IOException {
var request = HttpRequest.newBuilder()
.uri(MojangSkinProvider.SERVICES_SERVER_URI
.resolve("/minecraft/profile/lookup/name/")
@@ -147,7 +147,7 @@ public final class MojangSkinProvider implements SkinProvider {
if (response.statusCode() != 200)
throw new IllegalArgumentException("no profile with name " + name);
return JsonUtils.fromJson(response.body(), GameProfile.class);
return JsonUtils.fromJson(response.body(), NameAndId.class);
}
private static GameProfile getProfileWithProperties(UUID uuid) throws IOException {
@@ -165,6 +165,6 @@ public final class MojangSkinProvider implements SkinProvider {
if (response.statusCode() != 200)
throw new IllegalArgumentException("no profile with uuid " + uuid);
return JsonUtils.fromJson(response.body(), MinecraftProfilePropertiesResponse.class).toProfile();
return JsonUtils.fromJson(response.body(), MinecraftProfilePropertiesResponse.class).profile();
}
}

View File

@@ -13,6 +13,7 @@ public interface SkinProvider {
MojangSkinProvider MOJANG = new MojangSkinProvider();
ElyBySkinProvider ELY_BY = new ElyBySkinProvider();
MineskinSkinProvider MINESKIN = new MineskinSkinProvider();
CollectionSkinProvider COLLECTION = new CollectionSkinProvider();
SkinShuffleSkinProvider SKIN_SHUFFLE = new SkinShuffleSkinProvider();
Set<String> BUILTIN_PROVIDER_NAMES = ImmutableSet.of(
@@ -20,6 +21,7 @@ public interface SkinProvider {
MojangSkinProvider.PROVIDER_NAME,
ElyBySkinProvider.PROVIDER_NAME,
MineskinSkinProvider.PROVIDER_NAME,
CollectionSkinProvider.PROVIDER_NAME,
SkinShuffleSkinProvider.PROVIDER_NAME
);

View File

@@ -4,7 +4,6 @@ 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;
import com.mojang.util.UUIDTypeAdapter;
@@ -22,7 +21,6 @@ public final class JsonUtils {
.registerTypeAdapterFactory(new PostProcessingEnabler())
.registerTypeAdapter(UUID.class, new UUIDTypeAdapter())
.registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer())
.registerTypeAdapter(GameProfile.class, new GameProfile.Serializer())
.setPrettyPrinting()
.create();

View File

@@ -1,12 +1,13 @@
package net.lionarius.skinrestorer.util;
import com.google.common.collect.Iterables;
import com.google.common.collect.LinkedHashMultimap;
import com.google.gson.JsonObject;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.properties.Property;
import com.mojang.authlib.properties.PropertyMap;
import com.mojang.authlib.yggdrasil.response.MinecraftProfilePropertiesResponse;
import net.lionarius.skinrestorer.mixin.ChunkMapAccessor;
import net.lionarius.skinrestorer.mixin.TrackedEntityAccessorInvoker;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.*;
import net.minecraft.server.level.ChunkMap;
@@ -39,7 +40,7 @@ public final class PlayerUtils {
}
public static void refreshPlayer(ServerPlayer player) {
ServerLevel serverLevel = player.serverLevel();
ServerLevel serverLevel = player.level();
PlayerList playerList = serverLevel.getServer().getPlayerList();
ChunkMap chunkMap = serverLevel.getChunkSource().chunkMap;
@@ -50,14 +51,14 @@ public final class PlayerUtils {
)
));
var trackedEntity = (TrackedEntityAccessorInvoker) ((ChunkMapAccessor) chunkMap).getEntityMap().get(player.getId());
var trackedEntity = ((ChunkMapAccessor) chunkMap).getEntityMap().get(player.getId());
if (trackedEntity != null) {
var seenBy = Set.copyOf(trackedEntity.getSeenBy());
for (var observerConnection : seenBy) {
var observer = observerConnection.getPlayer();
trackedEntity.invokeRemovePlayer(observer);
var trackedObserverEntity = (TrackedEntityAccessorInvoker) ((ChunkMapAccessor) chunkMap).getEntityMap().get(observer.getId());
var trackedObserverEntity = ((ChunkMapAccessor) chunkMap).getEntityMap().get(observer.getId());
if (trackedObserverEntity != null) {
trackedObserverEntity.invokeRemovePlayer(player);
trackedObserverEntity.invokeUpdatePlayer(player);
@@ -96,15 +97,27 @@ public final class PlayerUtils {
}
}
public static Property getPlayerSkin(GameProfile profile) {
return Iterables.getFirst(profile.getProperties().get(TEXTURES_KEY), null);
public static GameProfile cloneGameProfile(GameProfile profile) {
var newProfile = new GameProfile(profile.id(), profile.name());
newProfile.properties().putAll(profile.properties());
return newProfile;
}
public static void applyRestoredSkin(GameProfile profile, Property skin) {
profile.getProperties().removeAll(TEXTURES_KEY);
public static Property getPlayerSkin(GameProfile profile) {
return Iterables.getFirst(profile.properties().get(TEXTURES_KEY), null);
}
public static GameProfile applyRestoredSkin(GameProfile profile, Property skin) {
var propertiesMap = profile.properties();
if (skin != null)
profile.getProperties().put(TEXTURES_KEY, skin);
var newProperties = LinkedHashMultimap.create(propertiesMap);
newProperties.removeAll(TEXTURES_KEY);
if (skin != null) {
newProperties.put(TEXTURES_KEY, skin);
}
return new GameProfile(profile.id(), profile.name(), new PropertyMap(newProperties));
}
public static boolean areSkinPropertiesEquals(Property x, Property y) {
@@ -128,7 +141,7 @@ public final class PlayerUtils {
public static GameProfile toProfile(MinecraftProfilePropertiesResponse response) {
final GameProfile profile = new GameProfile(response.id(), response.name());
profile.getProperties().putAll(response.properties());
profile.properties().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

@@ -0,0 +1 @@
accessWidener v2 named

View File

@@ -2,10 +2,12 @@
"required": true,
"minVersion": "0.8",
"package": "net.lionarius.skinrestorer.mixin",
"compatibilityLevel": "JAVA_8",
"compatibilityLevel": "JAVA_17",
"priority": 1100,
"refmap": "${mod_id}.refmap.json",
"mixins": [
"ChunkMapAccessor",
"PlayerAccessor",
"PlayerListMixin",
"ServerLoginPacketListenerImplMixin",
"TrackedEntityAccessorInvoker"

View File

@@ -1,5 +1,6 @@
# Fabric, see https://fabricmc.net/develop/ for new versions
fabric_loader_version=0.15.0
fabric_api_version=0.119.5+1.21.5
fabric_api_version=0.139.4+1.21.11
optional_dependencies=fabric-api
additional_modloaders=quilt

View File

@@ -32,6 +32,6 @@ public final class SkinShuffleCompatibility {
}
private static void handleSkinRefreshPacket(SkinShuffleSkinRefreshPayload payload, ServerPlayNetworking.Context context) {
net.lionarius.skinrestorer.compat.skinshuffle.SkinShuffleCompatibility.handleSkinRefresh(context.player().getServer(), context.player(), payload);
net.lionarius.skinrestorer.compat.skinshuffle.SkinShuffleCompatibility.handleSkinRefresh(SkinRestorer.getMinecraftServer(), context.player(), payload);
}
}

View File

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

View File

@@ -24,6 +24,7 @@
"${mod_id}.mixins.json",
"${mod_id}.fabric.mixins.json"
],
"accessWidener": "${mod_id}.accesswidener",
"depends": {
"fabricloader": ">=${fabric_loader_version}",
"minecraft": ">=${minecraft_version}",

View File

@@ -2,7 +2,7 @@
"required": true,
"minVersion": "0.8",
"package": "net.lionarius.skinrestorer.fabric.mixin",
"compatibilityLevel": "JAVA_8",
"compatibilityLevel": "JAVA_17",
"refmap": "${mod_id}.refmap.json",
"mixins": [
"CommandsMixin",

View File

@@ -24,7 +24,7 @@ tasks.named('jarJar') {
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
@@ -33,7 +33,7 @@ minecraft {
// 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
def at = project(':common').file('src/main/resources/META-INF/accesstransformer.cfg')
def at = project(":common").file('src/main/resources/META-INF/accesstransformer.cfg')
if (at.exists()) {
accessTransformer = at
}
@@ -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' } }
@@ -88,3 +92,7 @@ sourceSets.each {
it.output.resourcesDir = dir
it.java.destinationDirectory = dir
}
tasks.named('processResources') {
duplicatesStrategy = DuplicatesStrategy.INCLUDE
}

View File

@@ -1,5 +1,5 @@
# Forge, see https://files.minecraftforge.net/net/minecraftforge/forge/ for new versions
forge_version=55.0.0
forge_loader_version_range=[55,)
forge_version=61.0.0
forge_loader_version_range=[61,)
# Forge sometimes skips minor minecraft versions (like 1.20.5)
forge_minecraft_version=1.21.5
forge_minecraft_version=1.21.11

View File

@@ -4,7 +4,8 @@ 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.event.server.ServerStoppedEvent;
import net.minecraftforge.eventbus.api.listener.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
@Mod(SkinRestorer.MOD_ID)
@@ -27,4 +28,9 @@ public final class SkinRestorerForge {
public static void onServerStarted(ServerStartedEvent event) {
SkinRestorer.Events.onServerStarted(event.getServer());
}
@SubscribeEvent
public static void onServerStopped(ServerStoppedEvent event) {
SkinRestorer.Events.onServerStopped(event.getServer());
}
}

View File

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

View File

@@ -3,13 +3,11 @@ 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;
import net.minecraftforge.eventbus.api.SubscribeEvent;
public final class SkinShuffleGameEventHandler {
private SkinShuffleGameEventHandler() {}
@SubscribeEvent
public static void onPlayerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) {
SkinShuffleCompatibility.onPlayerJoin((ServerPlayer) event.getEntity());
}

View File

@@ -1,8 +1,8 @@
package net.lionarius.skinrestorer.forge.compat.skinshuffle;
import net.lionarius.skinrestorer.SkinRestorer;
import net.lionarius.skinrestorer.compat.skinshuffle.SkinShuffleCompatibility;
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;
@@ -10,9 +10,6 @@ import net.minecraftforge.network.Channel;
import net.minecraftforge.network.ChannelBuilder;
public class SkinShufflePacketHandler {
private SkinShufflePacketHandler() {
}
private static final Channel<CustomPacketPayload> INSTANCE = ChannelBuilder
.named(SkinRestorer.resourceLocation("skin_shuffle_compat"))
.optional()
@@ -26,6 +23,9 @@ public class SkinShufflePacketHandler {
.add(SkinShuffleSkinRefreshV2Payload.PACKET_ID, SkinShuffleSkinRefreshV2Payload.PACKET_CODEC, SkinShufflePacketHandler::handleSkinRefreshPacket)
.build();
private SkinShufflePacketHandler() {
}
protected static void initialize() {
// NO-OP
}
@@ -40,6 +40,6 @@ public class SkinShufflePacketHandler {
if (!context.isServerSide() || sender == null)
return;
SkinShuffleCompatibility.handleSkinRefresh(sender.getServer(), sender, payload);
SkinShuffleCompatibility.handleSkinRefresh(SkinRestorer.getMinecraftServer(), sender, payload);
}
}

View File

@@ -3,12 +3,12 @@ group=net.lionarius
java_version=21
# Common
minecraft_version=1.21.5
minecraft_version_list=1.21.5
minecraft_version_range=[1.21.5, 1.22)
minecraft_version=1.21.11
minecraft_version_list=1.21.11
minecraft_version_range=[1.21.11, 1.22)
mod_id=skinrestorer
mod_name=SkinRestorer
mod_version=2.3.1
mod_version=2.5.0
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.2.1-SNAPSHOT
# ParchmentMC mappings, see https://parchmentmc.org/docs/getting-started#choose-a-version for new versions
parchment_minecraft=1.21.5
parchment_version=2025.04.19
parchment_minecraft=1.21.11
parchment_version=2025.12.20
# Publishing
curseforge_id=443823

View File

@@ -12,9 +12,9 @@ neoForge {
version = neoforge_version
// Automatically enable neoforge AccessTransformers if the file exists
def at = project(':common').file('src/main/resources/META-INF/accesstransformer.cfg')
def at = project(":common").file('src/main/resources/META-INF/accesstransformer.cfg')
if (at.exists()) {
minecraft.accessTransformers.file(at)
accessTransformers.from(at.absolutePath)
}
parchment {
@@ -55,6 +55,4 @@ dependencies {
prefer mineskin_client_version
}
}
additionalRuntimeClasspath "org.mineskin:java-client:${mineskin_client_version}"
}

View File

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

View File

@@ -7,6 +7,7 @@ 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;
import net.neoforged.neoforge.event.server.ServerStoppedEvent;
@Mod(SkinRestorer.MOD_ID)
@EventBusSubscriber(modid = SkinRestorer.MOD_ID)
@@ -28,4 +29,9 @@ public final class SkinRestorerNeoForge {
public static void onServerStarted(ServerStartedEvent event) {
SkinRestorer.Events.onServerStarted(event.getServer());
}
@SubscribeEvent
public static void onServerStopped(ServerStoppedEvent event) {
SkinRestorer.Events.onServerStopped(event.getServer());
}
}

View File

@@ -1,7 +1,8 @@
package net.lionarius.skinrestorer.neoforge.compat.skinshuffle;
import net.lionarius.skinrestorer.compat.skinshuffle.SkinShuffleCompatibility;
import net.lionarius.skinrestorer.SkinRestorer;
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;
@@ -26,6 +27,6 @@ public final class SkinShuffleModEventHandler {
private static void handleSkinRefreshPacket(SkinShuffleSkinRefreshPayload payload, IPayloadContext context) {
var player = (ServerPlayer) context.player();
SkinShuffleCompatibility.handleSkinRefresh(player.getServer(), player, payload);
SkinShuffleCompatibility.handleSkinRefresh(SkinRestorer.getMinecraftServer(), player, payload);
}
}