mirror of
https://github.com/MCCTeam/Minecraft-Console-Client
synced 2026-08-15 13:04:36 +00:00
Compare commits
49 commits
20260722-4
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d50e90d860 | ||
|
|
196dc54222 | ||
|
|
a0710fd82f | ||
|
|
cfb77088b6 | ||
|
|
f1d844afbe | ||
|
|
1fd4b0244d | ||
|
|
844fa7af2e | ||
|
|
9523275eb6 | ||
|
|
8e11304bf9 | ||
|
|
34e9fd46fd | ||
|
|
15dd55d10a | ||
|
|
8f8e03b1c9 | ||
|
|
c9225aac58 | ||
|
|
7b100a3149 | ||
|
|
dbce402842 | ||
|
|
503652a760 | ||
|
|
3ae1d746fa | ||
|
|
4a68205f02 | ||
|
|
c377e52306 | ||
|
|
7fee87c98f | ||
|
|
07aa032214 | ||
|
|
6b0f1a8f77 | ||
|
|
a780312c19 | ||
|
|
19f02dfc25 | ||
|
|
dc472c3df6 | ||
|
|
90fda17365 | ||
|
|
5655e3fc89 | ||
|
|
456a548cbc | ||
|
|
92212d2b95 | ||
|
|
eea631f69e | ||
|
|
6e4bca5073 | ||
|
|
630a5fabef | ||
|
|
47bc47786a | ||
|
|
9b90b535d8 | ||
|
|
1686d00f30 | ||
|
|
23b83a45f5 | ||
|
|
97631acc55 | ||
|
|
03beb51fb7 | ||
|
|
9d1c7ac4bd | ||
|
|
668cbf7e6a | ||
|
|
bf99df7cde | ||
|
|
4c6b2b3190 | ||
|
|
fd0c99b2d3 | ||
|
|
ba134476af | ||
|
|
1dc1d06f51 | ||
|
|
78da20b4e4 | ||
|
|
a951b5b6c6 | ||
|
|
4a2837d862 | ||
|
|
85672cc0a2 |
58 changed files with 63831 additions and 338 deletions
|
|
@ -8,7 +8,7 @@
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="ModelContextProtocol" Version="1.2.0" />
|
<PackageReference Include="ModelContextProtocol" Version="1.4.1" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,7 @@
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="ModelContextProtocol" Version="1.2.0" />
|
<PackageReference Include="ModelContextProtocol" Version="1.4.1" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|
|
||||||
|
|
@ -62,6 +62,37 @@ public sealed class AutoRelogRetryPolicyTests
|
||||||
Assert.Equal(0, retriesLeft);
|
Assert.Equal(0, retriesLeft);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void CoalescedDuplicateRollsBackOnlyItsOwnReservation()
|
||||||
|
{
|
||||||
|
var policy = new AutoRelogRetryPolicy(new ManualTimeProvider());
|
||||||
|
|
||||||
|
Assert.True(policy.TryReserveAttempt(2, out int firstRetriesLeft));
|
||||||
|
Assert.True(policy.TryReserveAttempt(2, out int duplicateRetriesLeft));
|
||||||
|
policy.RollBackReservedAttempt();
|
||||||
|
|
||||||
|
Assert.Equal(1, firstRetriesLeft);
|
||||||
|
Assert.Equal(0, duplicateRetriesLeft);
|
||||||
|
Assert.Equal(1, policy.Attempts);
|
||||||
|
Assert.True(policy.TryReserveAttempt(2, out int secondFailureRetriesLeft));
|
||||||
|
Assert.Equal(0, secondFailureRetriesLeft);
|
||||||
|
Assert.False(policy.TryReserveAttempt(2, out _));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void UnlimitedDuplicateRollbackKeepsUnlimitedBudget()
|
||||||
|
{
|
||||||
|
var policy = new AutoRelogRetryPolicy(new ManualTimeProvider());
|
||||||
|
|
||||||
|
Assert.True(policy.TryReserveAttempt(-1, out _));
|
||||||
|
Assert.True(policy.TryReserveAttempt(-1, out _));
|
||||||
|
policy.RollBackReservedAttempt();
|
||||||
|
|
||||||
|
Assert.Equal(1, policy.Attempts);
|
||||||
|
Assert.True(policy.TryReserveAttempt(-1, out int retriesLeft));
|
||||||
|
Assert.Equal(-1, retriesLeft);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void StableConnectionResetsRetryBudget()
|
public void StableConnectionResetsRetryBudget()
|
||||||
{
|
{
|
||||||
|
|
|
||||||
108
MinecraftClient.Tests/BlockStatePropertiesTests.cs
Normal file
108
MinecraftClient.Tests/BlockStatePropertiesTests.cs
Normal file
|
|
@ -0,0 +1,108 @@
|
||||||
|
using MinecraftClient.Mapping;
|
||||||
|
using MinecraftClient.Mapping.BlockPalettes;
|
||||||
|
|
||||||
|
namespace MinecraftClient.Tests;
|
||||||
|
|
||||||
|
public sealed class BlockStatePropertiesTests
|
||||||
|
{
|
||||||
|
private readonly Palette262 _palette = new();
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(32162, "north", "true", "inactive")]
|
||||||
|
[InlineData(32168, "north", "false", "unlocking")]
|
||||||
|
[InlineData(32193, "east", "false", "ejecting")]
|
||||||
|
public void VaultStatesExposeAllProperties(
|
||||||
|
int stateId,
|
||||||
|
string facing,
|
||||||
|
string ominous,
|
||||||
|
string vaultState)
|
||||||
|
{
|
||||||
|
IReadOnlyDictionary<string, string> properties = _palette.GetStateProperties(stateId);
|
||||||
|
|
||||||
|
Assert.Equal(facing, properties["facing"]);
|
||||||
|
Assert.Equal(ominous, properties["ominous"]);
|
||||||
|
Assert.Equal(vaultState, properties["vault_state"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void PropertiesUseServerReportedStateStride()
|
||||||
|
{
|
||||||
|
IReadOnlyDictionary<string, string> properties = _palette.GetStateProperties(3989);
|
||||||
|
|
||||||
|
Assert.Equal("left", properties["type"]);
|
||||||
|
Assert.Equal("north", properties["facing"]);
|
||||||
|
Assert.Equal("true", properties["waterlogged"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void StateWithoutPropertiesReturnsEmptyMap()
|
||||||
|
{
|
||||||
|
IReadOnlyDictionary<string, string> properties = _palette.GetStateProperties(1);
|
||||||
|
|
||||||
|
Assert.Empty(properties);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static TheoryData<string, BlockPalette> ModernPalettes => new()
|
||||||
|
{
|
||||||
|
{ "1.13.2", new Palette113() },
|
||||||
|
{ "1.14.4", new Palette114() },
|
||||||
|
{ "1.15.2", new Palette115() },
|
||||||
|
{ "1.16.5", new Palette116() },
|
||||||
|
{ "1.17.1", new Palette117() },
|
||||||
|
{ "1.19.2", new Palette119() },
|
||||||
|
{ "1.19.3", new Palette1193() },
|
||||||
|
{ "1.19.4", new Palette1194() },
|
||||||
|
{ "1.20", new Palette120() },
|
||||||
|
{ "1.20.4", new Palette1204() },
|
||||||
|
{ "1.20.6", new Palette1206() },
|
||||||
|
{ "1.21.2", new Palette1212() },
|
||||||
|
{ "1.21.4", new Palette1214() },
|
||||||
|
{ "1.21.5", new Palette1215() },
|
||||||
|
{ "1.21.6", new Palette1216() },
|
||||||
|
{ "1.21.9", new Palette1219() },
|
||||||
|
{ "26.1", new Palette261() },
|
||||||
|
{ "26.2", new Palette262() }
|
||||||
|
};
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(ModernPalettes))]
|
||||||
|
public void EveryModernPaletteExposesOakLogAxis(string version, BlockPalette palette)
|
||||||
|
{
|
||||||
|
bool foundExpectedState = false;
|
||||||
|
|
||||||
|
for (int stateId = 0; stateId <= ushort.MaxValue; stateId++)
|
||||||
|
{
|
||||||
|
if (palette.FromId(stateId) != Material.OakLog)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
IReadOnlyDictionary<string, string> properties = palette.GetStateProperties(stateId);
|
||||||
|
if (properties.TryGetValue("axis", out string? axis) && axis == "x")
|
||||||
|
{
|
||||||
|
foundExpectedState = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.True(foundExpectedState, $"Minecraft {version} did not expose oak_log[axis=x]");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void LegacyPaletteExposesPackedMetadata()
|
||||||
|
{
|
||||||
|
BlockPalette previousPalette = Block.Palette;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Block.Palette = new Palette112();
|
||||||
|
Block block = new(17, 4);
|
||||||
|
|
||||||
|
IReadOnlyDictionary<string, string> properties = block.GetStateProperties();
|
||||||
|
|
||||||
|
Assert.Equal(276, block.StateId);
|
||||||
|
Assert.Equal("4", properties["metadata"]);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Block.Palette = previousPalette;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
14
MinecraftClient.Tests/CSharpRunnerTests.cs
Normal file
14
MinecraftClient.Tests/CSharpRunnerTests.cs
Normal file
|
|
@ -0,0 +1,14 @@
|
||||||
|
using MinecraftClient.Scripting;
|
||||||
|
|
||||||
|
namespace MinecraftClient.Tests;
|
||||||
|
|
||||||
|
public sealed class CSharpRunnerTests
|
||||||
|
{
|
||||||
|
[Theory]
|
||||||
|
[InlineData("//using MinecraftClient.CommandHandler", "using MinecraftClient.CommandHandler;")]
|
||||||
|
[InlineData("//using MinecraftClient.CommandHandler;", "using MinecraftClient.CommandHandler;")]
|
||||||
|
public void NormalizeUsingDirectiveAddsMissingSemicolon(string directive, string expected)
|
||||||
|
{
|
||||||
|
Assert.Equal(expected, CSharpRunner.NormalizeUsingDirective(directive));
|
||||||
|
}
|
||||||
|
}
|
||||||
159
MinecraftClient.Tests/ChatTypeHolderTests.cs
Normal file
159
MinecraftClient.Tests/ChatTypeHolderTests.cs
Normal file
|
|
@ -0,0 +1,159 @@
|
||||||
|
using MinecraftClient.Protocol.Handlers;
|
||||||
|
using MinecraftClient.Protocol.Message;
|
||||||
|
|
||||||
|
namespace MinecraftClient.Tests;
|
||||||
|
|
||||||
|
public sealed class ChatTypeHolderTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void ReferenceHolderUsesOneBasedWireIdIn121AndNewer()
|
||||||
|
{
|
||||||
|
var dataTypes = new DataTypes(Protocol18Handler.MC_1_21_Version);
|
||||||
|
var packetData = new Queue<byte>(DataTypes.GetVarInt(2));
|
||||||
|
|
||||||
|
int chatTypeId = ChatParser.ReadChatTypeHolder(
|
||||||
|
dataTypes,
|
||||||
|
packetData,
|
||||||
|
Protocol18Handler.MC_1_21_Version,
|
||||||
|
out var directDecoration);
|
||||||
|
|
||||||
|
Assert.Equal(1, chatTypeId);
|
||||||
|
Assert.Null(directDecoration);
|
||||||
|
Assert.Empty(packetData);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RegistryIdRemainsUnchangedBefore121()
|
||||||
|
{
|
||||||
|
var dataTypes = new DataTypes(Protocol18Handler.MC_1_20_6_Version);
|
||||||
|
var packetData = new Queue<byte>(DataTypes.GetVarInt(2));
|
||||||
|
|
||||||
|
int chatTypeId = ChatParser.ReadChatTypeHolder(
|
||||||
|
dataTypes,
|
||||||
|
packetData,
|
||||||
|
Protocol18Handler.MC_1_20_6_Version,
|
||||||
|
out var directDecoration);
|
||||||
|
|
||||||
|
Assert.Equal(2, chatTypeId);
|
||||||
|
Assert.Null(directDecoration);
|
||||||
|
Assert.Empty(packetData);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DirectHolderConsumesChatAndNarrationDecorations()
|
||||||
|
{
|
||||||
|
var dataTypes = new DataTypes(Protocol18Handler.MC_1_21_Version);
|
||||||
|
var packetBytes = new List<byte>();
|
||||||
|
packetBytes.AddRange(DataTypes.GetVarInt(0));
|
||||||
|
AddDecoration(packetBytes, dataTypes, "chat.type.text", 0, 2);
|
||||||
|
AddDecoration(packetBytes, dataTypes, "chat.type.text.narrate", 0, 2);
|
||||||
|
var packetData = new Queue<byte>(packetBytes);
|
||||||
|
|
||||||
|
int chatTypeId = ChatParser.ReadChatTypeHolder(
|
||||||
|
dataTypes,
|
||||||
|
packetData,
|
||||||
|
Protocol18Handler.MC_1_21_Version,
|
||||||
|
out var directDecoration);
|
||||||
|
|
||||||
|
Assert.Equal(-1, chatTypeId);
|
||||||
|
Assert.NotNull(directDecoration);
|
||||||
|
Assert.Equal("chat.type.text", directDecoration.TranslationKey);
|
||||||
|
Assert.Equal(
|
||||||
|
[ChatParser.ChatTypeParameter.Sender, ChatParser.ChatTypeParameter.Content],
|
||||||
|
directDecoration.Parameters);
|
||||||
|
Assert.Empty(packetData);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RegistryDecorationControlsParameterSelectionAndOrdering()
|
||||||
|
{
|
||||||
|
Dictionary<int, ChatParser.MessageType>? originalChatTypes = ChatParser.ChatId2Type;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
ChatParser.ClearChatTypeDecorations();
|
||||||
|
ChatParser.ChatId2Type = [];
|
||||||
|
var chatTypeData = new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
["chat"] = new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
["translation_key"] = "commands.message.display.outgoing",
|
||||||
|
["parameters"] = new object[] { "target", "content" }
|
||||||
|
}
|
||||||
|
};
|
||||||
|
ChatParser.ReadChatType(42, "example:custom_chat", chatTypeData);
|
||||||
|
var message = new ChatMessage(
|
||||||
|
"hello",
|
||||||
|
false,
|
||||||
|
42,
|
||||||
|
Guid.Empty,
|
||||||
|
null,
|
||||||
|
"Alice",
|
||||||
|
"Bob",
|
||||||
|
DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
|
||||||
|
null,
|
||||||
|
false);
|
||||||
|
|
||||||
|
string rendered = ChatParser.ParseSignedChat(message);
|
||||||
|
|
||||||
|
Assert.Equal("You whisper to Bob: hello", rendered);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
ChatParser.ClearChatTypeDecorations();
|
||||||
|
ChatParser.ChatId2Type = originalChatTypes;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void UnknownTranslationKeyIsUsedAsVanillaFormatPattern()
|
||||||
|
{
|
||||||
|
Dictionary<int, ChatParser.MessageType>? originalChatTypes = ChatParser.ChatId2Type;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
ChatParser.ClearChatTypeDecorations();
|
||||||
|
ChatParser.ChatId2Type = [];
|
||||||
|
var chatTypeData = new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
["chat"] = new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
["translation_key"] = "%s",
|
||||||
|
["parameters"] = new object[] { "sender", "content" }
|
||||||
|
}
|
||||||
|
};
|
||||||
|
ChatParser.ReadChatType(42, "ordinary:custom_chat", chatTypeData);
|
||||||
|
var message = new ChatMessage(
|
||||||
|
"hello",
|
||||||
|
false,
|
||||||
|
42,
|
||||||
|
Guid.Empty,
|
||||||
|
null,
|
||||||
|
"Alice » hello",
|
||||||
|
null,
|
||||||
|
DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
|
||||||
|
null,
|
||||||
|
false);
|
||||||
|
|
||||||
|
string rendered = ChatParser.ParseSignedChat(message);
|
||||||
|
|
||||||
|
Assert.Equal("Alice » hello", rendered);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
ChatParser.ClearChatTypeDecorations();
|
||||||
|
ChatParser.ChatId2Type = originalChatTypes;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void AddDecoration(
|
||||||
|
List<byte> packetBytes,
|
||||||
|
DataTypes dataTypes,
|
||||||
|
string translationKey,
|
||||||
|
params int[] parameters)
|
||||||
|
{
|
||||||
|
packetBytes.AddRange(dataTypes.GetString(translationKey));
|
||||||
|
packetBytes.AddRange(DataTypes.GetVarInt(parameters.Length));
|
||||||
|
foreach (int parameter in parameters)
|
||||||
|
packetBytes.AddRange(DataTypes.GetVarInt(parameter));
|
||||||
|
packetBytes.AddRange(dataTypes.GetNbtTag(new Dictionary<string, object>()));
|
||||||
|
}
|
||||||
|
}
|
||||||
122
MinecraftClient.Tests/McClientConnectionFailureTests.cs
Normal file
122
MinecraftClient.Tests/McClientConnectionFailureTests.cs
Normal file
|
|
@ -0,0 +1,122 @@
|
||||||
|
using MinecraftClient.Scripting;
|
||||||
|
|
||||||
|
namespace MinecraftClient.Tests;
|
||||||
|
|
||||||
|
public sealed class McClientConnectionFailureTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void LoginRejectedClaimPreventsSyntheticConnectionLostFallback()
|
||||||
|
{
|
||||||
|
var lifecycle = new ConnectionAttemptLifecycle();
|
||||||
|
|
||||||
|
Assert.True(lifecycle.TryBeginDisconnect());
|
||||||
|
Assert.True(lifecycle.IsFailureClaimed);
|
||||||
|
Assert.False(lifecycle.TryBeginDisconnect());
|
||||||
|
|
||||||
|
lifecycle.CompleteDisconnect();
|
||||||
|
|
||||||
|
Assert.True(lifecycle.IsFailureClaimed);
|
||||||
|
Assert.False(lifecycle.TryBeginDisconnect());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void UnclaimedGenericFailureCanBeClaimedExactlyOnce()
|
||||||
|
{
|
||||||
|
var lifecycle = new ConnectionAttemptLifecycle();
|
||||||
|
|
||||||
|
Assert.False(lifecycle.IsFailureClaimed);
|
||||||
|
Assert.True(lifecycle.TryBeginDisconnect());
|
||||||
|
Assert.False(lifecycle.TryBeginDisconnect());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void HeldBotsAreRestoredBeforeFailureAndReceiveOriginalMessageOnce()
|
||||||
|
{
|
||||||
|
const string rejectionMessage = "You are not white-listed on this server!";
|
||||||
|
var bot = new RecordingBot();
|
||||||
|
List<ChatBot> heldBots = [bot];
|
||||||
|
var loadedBots = new List<ChatBot>();
|
||||||
|
|
||||||
|
ConnectionAttemptLifecycle.RestoreHeldBots(heldBots, loadedBots.Add);
|
||||||
|
foreach (ChatBot loadedBot in loadedBots)
|
||||||
|
loadedBot.OnDisconnect(ChatBot.DisconnectReason.LoginRejected, rejectionMessage);
|
||||||
|
|
||||||
|
Assert.Empty(heldBots);
|
||||||
|
Assert.Single(loadedBots);
|
||||||
|
Assert.Equal(1, bot.DisconnectCount);
|
||||||
|
Assert.Equal(ChatBot.DisconnectReason.LoginRejected, bot.LastReason);
|
||||||
|
Assert.Equal(rejectionMessage, bot.LastMessage);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void OfflineRouteStaysOwnedAcrossReplacementAndSuccessfulHandoff()
|
||||||
|
{
|
||||||
|
var route = new AttemptOwnedRoute();
|
||||||
|
int activations = 0;
|
||||||
|
int deactivations = 0;
|
||||||
|
|
||||||
|
Assert.True(route.TryActivate(7, 7, () => activations++));
|
||||||
|
Assert.False(route.TryActivate(7, 7, () => activations++));
|
||||||
|
Assert.True(route.TryTransfer(7, 8));
|
||||||
|
Assert.False(route.TryDeactivate(7, () => deactivations++));
|
||||||
|
Assert.Equal(8, route.OwnerAttempt);
|
||||||
|
Assert.True(route.TryDeactivate(8, () => deactivations++));
|
||||||
|
|
||||||
|
Assert.Equal(1, activations);
|
||||||
|
Assert.Equal(1, deactivations);
|
||||||
|
Assert.Equal(-1, route.OwnerAttempt);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void InitialConnectionAttemptCanOwnOfflineRoute()
|
||||||
|
{
|
||||||
|
var route = new AttemptOwnedRoute();
|
||||||
|
int activations = 0;
|
||||||
|
|
||||||
|
Assert.True(route.TryActivate(0, 0, () => activations++));
|
||||||
|
|
||||||
|
Assert.Equal(1, activations);
|
||||||
|
Assert.Equal(0, route.OwnerAttempt);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void OlderAttemptCannotTakeAnEmptyOfflineRoute()
|
||||||
|
{
|
||||||
|
var route = new AttemptOwnedRoute();
|
||||||
|
int activations = 0;
|
||||||
|
|
||||||
|
Assert.False(route.TryActivate(4, 5, () => activations++));
|
||||||
|
|
||||||
|
Assert.Equal(0, activations);
|
||||||
|
Assert.Equal(-1, route.OwnerAttempt);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void StaleCleanupCannotClearNewerOfflineRoute()
|
||||||
|
{
|
||||||
|
var route = new AttemptOwnedRoute();
|
||||||
|
int deactivations = 0;
|
||||||
|
|
||||||
|
Assert.True(route.TryActivate(10, 10, () => { }));
|
||||||
|
Assert.True(route.TryActivate(11, 11, () => { }));
|
||||||
|
Assert.False(route.TryDeactivate(10, () => deactivations++));
|
||||||
|
|
||||||
|
Assert.Equal(11, route.OwnerAttempt);
|
||||||
|
Assert.Equal(0, deactivations);
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class RecordingBot : ChatBot
|
||||||
|
{
|
||||||
|
internal int DisconnectCount { get; private set; }
|
||||||
|
internal DisconnectReason? LastReason { get; private set; }
|
||||||
|
internal string? LastMessage { get; private set; }
|
||||||
|
|
||||||
|
public override bool OnDisconnect(DisconnectReason reason, string message)
|
||||||
|
{
|
||||||
|
DisconnectCount++;
|
||||||
|
LastReason = reason;
|
||||||
|
LastMessage = message;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -8,7 +8,7 @@
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.7.0" />
|
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.8.1" />
|
||||||
<PackageReference Include="xunit" Version="2.9.3" />
|
<PackageReference Include="xunit" Version="2.9.3" />
|
||||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
|
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
|
|
|
||||||
|
|
@ -3,59 +3,300 @@ namespace MinecraftClient.Tests;
|
||||||
public sealed class RestartCoordinatorTests
|
public sealed class RestartCoordinatorTests
|
||||||
{
|
{
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task CoalescesSameAttemptAndQueuesNewerAttempt()
|
public async Task PreparationCompletesBeforeRequestCanExecute()
|
||||||
{
|
{
|
||||||
var firstStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
var completed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
var releaseFirst = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
bool prepared = false;
|
||||||
var secondCompleted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
||||||
|
|
||||||
using var coordinator = new RestartCoordinator(
|
RestartCoordinator coordinator = null!;
|
||||||
async (request, cancellationToken) =>
|
coordinator = new RestartCoordinator(
|
||||||
|
(request, cancellationToken) =>
|
||||||
{
|
{
|
||||||
if (request.ConnectionAttempt == 10)
|
Assert.True(Volatile.Read(ref prepared));
|
||||||
{
|
Assert.True(coordinator.TryBeginCommit(request, out _));
|
||||||
firstStarted.SetResult();
|
completed.SetResult();
|
||||||
await releaseFirst.Task.WaitAsync(cancellationToken);
|
return Task.CompletedTask;
|
||||||
}
|
|
||||||
else if (request.ConnectionAttempt == 11)
|
|
||||||
{
|
|
||||||
secondCompleted.SetResult();
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
exception => throw new Xunit.Sdk.XunitException(exception.ToString()));
|
exception => throw new Xunit.Sdk.XunitException(exception.ToString()));
|
||||||
|
using var cleanup = coordinator;
|
||||||
|
|
||||||
|
Assert.True(coordinator.TrySchedule(
|
||||||
|
new RestartRequest(1, TimeSpan.Zero, true),
|
||||||
|
() =>
|
||||||
|
{
|
||||||
|
Volatile.Write(ref prepared, true);
|
||||||
|
return true;
|
||||||
|
}));
|
||||||
|
await completed.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task RejectedPreparationDoesNotPublishOrAdvanceAttempt()
|
||||||
|
{
|
||||||
|
var completed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
int executions = 0;
|
||||||
|
|
||||||
|
RestartCoordinator coordinator = null!;
|
||||||
|
coordinator = new RestartCoordinator(
|
||||||
|
(request, cancellationToken) =>
|
||||||
|
{
|
||||||
|
Interlocked.Increment(ref executions);
|
||||||
|
Assert.True(coordinator.TryBeginCommit(request, out _));
|
||||||
|
completed.SetResult();
|
||||||
|
return Task.CompletedTask;
|
||||||
|
},
|
||||||
|
exception => throw new Xunit.Sdk.XunitException(exception.ToString()));
|
||||||
|
using var cleanup = coordinator;
|
||||||
|
|
||||||
|
Assert.False(coordinator.TrySchedule(
|
||||||
|
new RestartRequest(2, TimeSpan.Zero, true),
|
||||||
|
() => false));
|
||||||
|
Assert.False(coordinator.HasScheduledRestart(2));
|
||||||
|
|
||||||
|
Assert.True(coordinator.TrySchedule(new RestartRequest(2, TimeSpan.Zero, true)));
|
||||||
|
await completed.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||||||
|
|
||||||
|
Assert.Equal(1, executions);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task FaultedSourceCleanupPreventsRestartExecution()
|
||||||
|
{
|
||||||
|
var failureReported = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
int executions = 0;
|
||||||
|
|
||||||
|
using var coordinator = new RestartCoordinator(
|
||||||
|
(_, _) =>
|
||||||
|
{
|
||||||
|
Interlocked.Increment(ref executions);
|
||||||
|
return Task.CompletedTask;
|
||||||
|
},
|
||||||
|
exception => failureReported.SetResult(exception));
|
||||||
|
|
||||||
|
var cleanupFailure = new InvalidOperationException("cleanup failed");
|
||||||
|
Assert.True(coordinator.TrySchedule(new RestartRequest(
|
||||||
|
3,
|
||||||
|
TimeSpan.Zero,
|
||||||
|
true,
|
||||||
|
SourceCleanupCompletion: Task.FromException(cleanupFailure))));
|
||||||
|
|
||||||
|
Exception reportedException = await failureReported.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||||||
|
|
||||||
|
Assert.Same(cleanupFailure, reportedException);
|
||||||
|
Assert.Equal(0, executions);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task AutomaticSameAttemptIsCoalescedWhileQueued()
|
||||||
|
{
|
||||||
|
var blockerStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
var releaseBlocker = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
var queuedCompleted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
int queuedExecutions = 0;
|
||||||
|
|
||||||
|
RestartCoordinator coordinator = null!;
|
||||||
|
coordinator = new RestartCoordinator(
|
||||||
|
async (request, cancellationToken) =>
|
||||||
|
{
|
||||||
|
if (request.ConnectionAttempt == 9)
|
||||||
|
{
|
||||||
|
blockerStarted.SetResult();
|
||||||
|
await releaseBlocker.Task.WaitAsync(cancellationToken);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Interlocked.Increment(ref queuedExecutions);
|
||||||
|
Assert.True(coordinator.TryBeginCommit(request, out _));
|
||||||
|
queuedCompleted.SetResult();
|
||||||
|
},
|
||||||
|
exception => throw new Xunit.Sdk.XunitException(exception.ToString()));
|
||||||
|
using var cleanup = coordinator;
|
||||||
|
|
||||||
|
Assert.True(coordinator.TrySchedule(new RestartRequest(9, TimeSpan.Zero, true)));
|
||||||
|
await blockerStarted.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||||||
|
|
||||||
Assert.True(coordinator.TrySchedule(new RestartRequest(10, TimeSpan.Zero, true)));
|
Assert.True(coordinator.TrySchedule(new RestartRequest(10, TimeSpan.Zero, true)));
|
||||||
await firstStarted.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
|
||||||
|
|
||||||
Assert.False(coordinator.TrySchedule(new RestartRequest(10, TimeSpan.Zero, true)));
|
Assert.False(coordinator.TrySchedule(new RestartRequest(10, TimeSpan.Zero, true)));
|
||||||
Assert.True(coordinator.TrySchedule(new RestartRequest(11, TimeSpan.Zero, true)));
|
Assert.True(coordinator.HasScheduledRestart(10));
|
||||||
Assert.True(coordinator.HasScheduledRestart(11));
|
|
||||||
|
|
||||||
releaseFirst.SetResult();
|
releaseBlocker.SetResult();
|
||||||
await secondCompleted.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
await queuedCompleted.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||||||
|
|
||||||
|
Assert.Equal(1, queuedExecutions);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task AutomaticSameAttemptIsCoalescedDuringCallback()
|
||||||
|
{
|
||||||
|
var callbackStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
var releaseCallback = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
var callbackCompleted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
int executions = 0;
|
||||||
|
|
||||||
|
RestartCoordinator coordinator = null!;
|
||||||
|
coordinator = new RestartCoordinator(
|
||||||
|
async (request, cancellationToken) =>
|
||||||
|
{
|
||||||
|
Interlocked.Increment(ref executions);
|
||||||
|
callbackStarted.SetResult();
|
||||||
|
await releaseCallback.Task.WaitAsync(cancellationToken);
|
||||||
|
Assert.True(coordinator.TryBeginCommit(request, out _));
|
||||||
|
callbackCompleted.SetResult();
|
||||||
|
},
|
||||||
|
exception => throw new Xunit.Sdk.XunitException(exception.ToString()));
|
||||||
|
using var cleanup = coordinator;
|
||||||
|
|
||||||
|
Assert.True(coordinator.TrySchedule(new RestartRequest(42, TimeSpan.Zero, true)));
|
||||||
|
await callbackStarted.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||||||
|
|
||||||
|
Assert.False(coordinator.TrySchedule(new RestartRequest(42, TimeSpan.Zero, true)));
|
||||||
|
|
||||||
|
releaseCallback.SetResult();
|
||||||
|
await callbackCompleted.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||||||
|
|
||||||
|
Assert.Equal(1, executions);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task ExplicitReplacementDuringDelayUsesLatestSnapshotWithoutAnotherExecution()
|
||||||
|
{
|
||||||
|
var callbackStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
var allowCommit = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
var callbackCompleted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
RestartRequest committedRequest = default;
|
||||||
|
int executions = 0;
|
||||||
|
|
||||||
|
RestartCoordinator coordinator = null!;
|
||||||
|
coordinator = new RestartCoordinator(
|
||||||
|
async (request, cancellationToken) =>
|
||||||
|
{
|
||||||
|
Interlocked.Increment(ref executions);
|
||||||
|
callbackStarted.SetResult();
|
||||||
|
await allowCommit.Task.WaitAsync(cancellationToken);
|
||||||
|
Assert.True(coordinator.TryBeginCommit(request, out committedRequest));
|
||||||
|
callbackCompleted.SetResult();
|
||||||
|
},
|
||||||
|
exception => throw new Xunit.Sdk.XunitException(exception.ToString()));
|
||||||
|
using var cleanup = coordinator;
|
||||||
|
|
||||||
|
Assert.True(coordinator.TrySchedule(new RestartRequest(
|
||||||
|
50,
|
||||||
|
TimeSpan.FromSeconds(10),
|
||||||
|
true,
|
||||||
|
CreateSettingsSnapshot("first"))));
|
||||||
|
await callbackStarted.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||||||
|
|
||||||
|
Assert.True(coordinator.TrySchedule(new RestartRequest(
|
||||||
|
50,
|
||||||
|
TimeSpan.Zero,
|
||||||
|
true,
|
||||||
|
CreateSettingsSnapshot("replacement"),
|
||||||
|
ReplaceUntilCommit: true)));
|
||||||
|
|
||||||
|
allowCommit.SetResult();
|
||||||
|
await callbackCompleted.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||||||
|
|
||||||
|
Assert.Equal(1, executions);
|
||||||
|
Assert.Equal("replacement", committedRequest.SettingsSnapshot?.Account.Login);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task RejectsSameAttemptReplacementAfterCommit()
|
||||||
|
{
|
||||||
|
var commitStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
var releaseCommit = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
RestartRequest committedRequest = default;
|
||||||
|
|
||||||
|
RestartCoordinator coordinator = null!;
|
||||||
|
coordinator = new RestartCoordinator(
|
||||||
|
async (request, cancellationToken) =>
|
||||||
|
{
|
||||||
|
Assert.True(coordinator.TryBeginCommit(request, out committedRequest));
|
||||||
|
commitStarted.SetResult();
|
||||||
|
await releaseCommit.Task.WaitAsync(cancellationToken);
|
||||||
|
},
|
||||||
|
exception => throw new Xunit.Sdk.XunitException(exception.ToString()));
|
||||||
|
using var cleanup = coordinator;
|
||||||
|
|
||||||
|
Assert.True(coordinator.TrySchedule(new RestartRequest(
|
||||||
|
60,
|
||||||
|
TimeSpan.Zero,
|
||||||
|
true,
|
||||||
|
CreateSettingsSnapshot("committed"))));
|
||||||
|
await commitStarted.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||||||
|
|
||||||
|
Assert.False(coordinator.TrySchedule(new RestartRequest(
|
||||||
|
60,
|
||||||
|
TimeSpan.Zero,
|
||||||
|
true,
|
||||||
|
CreateSettingsSnapshot("rejected"),
|
||||||
|
ReplaceUntilCommit: true)));
|
||||||
|
Assert.Equal("committed", committedRequest.SettingsSnapshot?.Account.Login);
|
||||||
|
|
||||||
|
releaseCommit.SetResult();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void RejectsStaleAttempt()
|
public void RejectsStaleAttempt()
|
||||||
{
|
{
|
||||||
using var coordinator = new RestartCoordinator(
|
RestartCoordinator coordinator = null!;
|
||||||
|
coordinator = new RestartCoordinator(
|
||||||
(_, _) => Task.CompletedTask,
|
(_, _) => Task.CompletedTask,
|
||||||
exception => throw new Xunit.Sdk.XunitException(exception.ToString()));
|
exception => throw new Xunit.Sdk.XunitException(exception.ToString()));
|
||||||
|
using var cleanup = coordinator;
|
||||||
|
|
||||||
Assert.True(coordinator.TrySchedule(new RestartRequest(20, TimeSpan.Zero, true)));
|
Assert.True(coordinator.TrySchedule(new RestartRequest(20, TimeSpan.Zero, true)));
|
||||||
Assert.False(coordinator.TrySchedule(new RestartRequest(19, TimeSpan.Zero, true)));
|
Assert.False(coordinator.TrySchedule(new RestartRequest(19, TimeSpan.Zero, true)));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void TerminalStopRejectsFurtherRestarts()
|
public async Task RejectsCompletedAttempt()
|
||||||
{
|
{
|
||||||
using var coordinator = new RestartCoordinator(
|
var completed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
(_, _) => Task.CompletedTask,
|
RestartCoordinator coordinator = null!;
|
||||||
|
coordinator = new RestartCoordinator(
|
||||||
|
(request, cancellationToken) =>
|
||||||
|
{
|
||||||
|
Assert.True(coordinator.TryBeginCommit(request, out _));
|
||||||
|
completed.SetResult();
|
||||||
|
return Task.CompletedTask;
|
||||||
|
},
|
||||||
exception => throw new Xunit.Sdk.XunitException(exception.ToString()));
|
exception => throw new Xunit.Sdk.XunitException(exception.ToString()));
|
||||||
|
using var cleanup = coordinator;
|
||||||
|
|
||||||
|
Assert.True(coordinator.TrySchedule(new RestartRequest(20, TimeSpan.Zero, true)));
|
||||||
|
await completed.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||||||
|
Assert.True(SpinWait.SpinUntil(() => !coordinator.HasScheduledRestart(20), TimeSpan.FromSeconds(5)));
|
||||||
|
|
||||||
|
Assert.False(coordinator.TrySchedule(new RestartRequest(20, TimeSpan.Zero, true)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task TerminalStopCancelsInFlightWorkAndRejectsFurtherRestarts()
|
||||||
|
{
|
||||||
|
var callbackStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
using var coordinator = new RestartCoordinator(
|
||||||
|
async (_, cancellationToken) =>
|
||||||
|
{
|
||||||
|
callbackStarted.SetResult();
|
||||||
|
await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken);
|
||||||
|
},
|
||||||
|
exception => throw new Xunit.Sdk.XunitException(exception.ToString()));
|
||||||
|
|
||||||
|
Assert.True(coordinator.TrySchedule(new RestartRequest(1, TimeSpan.Zero, true)));
|
||||||
|
await callbackStarted.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||||||
|
|
||||||
coordinator.Stop();
|
coordinator.Stop();
|
||||||
|
|
||||||
Assert.False(coordinator.TrySchedule(new RestartRequest(1, TimeSpan.Zero, true)));
|
Assert.False(coordinator.TrySchedule(new RestartRequest(2, TimeSpan.Zero, true)));
|
||||||
Assert.False(coordinator.HasScheduledRestart(1));
|
Assert.False(coordinator.HasScheduledRestart(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static RestartSettingsSnapshot CreateSettingsSnapshot(string account)
|
||||||
|
{
|
||||||
|
return new RestartSettingsSnapshot(
|
||||||
|
new Settings.MainConfigHelper.MainConfig.AccountInfoConfig(account, "-"),
|
||||||
|
"localhost",
|
||||||
|
25565);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -78,6 +78,7 @@ namespace MinecraftClient.ChatBots
|
||||||
}
|
}
|
||||||
|
|
||||||
private static readonly AutoRelogRetryPolicy s_retryPolicy = new(TimeProvider.System);
|
private static readonly AutoRelogRetryPolicy s_retryPolicy = new(TimeProvider.System);
|
||||||
|
private readonly long? sourceConnectionAttempt;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// This bot automatically re-join the server if kick message contains predefined string
|
/// This bot automatically re-join the server if kick message contains predefined string
|
||||||
|
|
@ -85,8 +86,13 @@ namespace MinecraftClient.ChatBots
|
||||||
/// <param name="DelayBeforeRelogMin">Minimum delay before re-joining the server (in seconds)</param>
|
/// <param name="DelayBeforeRelogMin">Minimum delay before re-joining the server (in seconds)</param>
|
||||||
/// <param name="DelayBeforeRelogMax">Maximum delay before re-joining the server (in seconds)</param>
|
/// <param name="DelayBeforeRelogMax">Maximum delay before re-joining the server (in seconds)</param>
|
||||||
/// <param name="retries">Number of retries if connection fails (-1 = infinite)</param>
|
/// <param name="retries">Number of retries if connection fails (-1 = infinite)</param>
|
||||||
public AutoRelog()
|
public AutoRelog() : this(null)
|
||||||
{
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
private AutoRelog(long? sourceConnectionAttempt)
|
||||||
|
{
|
||||||
|
this.sourceConnectionAttempt = sourceConnectionAttempt;
|
||||||
LogDebugToConsole(string.Format(Translations.bot_autoRelog_launch, Config.Retries));
|
LogDebugToConsole(string.Format(Translations.bot_autoRelog_launch, Config.Retries));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -163,21 +169,31 @@ namespace MinecraftClient.ChatBots
|
||||||
: retriesLeft.ToString();
|
: retriesLeft.ToString();
|
||||||
|
|
||||||
McClient.ReconnectionAttemptsLeft = retriesLeft;
|
McClient.ReconnectionAttemptsLeft = retriesLeft;
|
||||||
if (Program.TryRestart(TimeSpan.FromSeconds(delay), true))
|
long connectionAttempt = sourceConnectionAttempt ?? Handler.ConnectionAttempt;
|
||||||
|
if (Program.TryRestart(
|
||||||
|
connectionAttempt,
|
||||||
|
TimeSpan.FromSeconds(delay),
|
||||||
|
keepAccountAndServerSettings: true,
|
||||||
|
sourceCleanupCompletion: sourceConnectionAttempt.HasValue ? null : Handler.DisconnectCompletion))
|
||||||
{
|
{
|
||||||
LogToConsole(string.Format(Translations.bot_autoRelog_wait_with_retries, delay, retriesDisplay));
|
LogToConsole(string.Format(Translations.bot_autoRelog_wait_with_retries, delay, retriesDisplay));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
s_retryPolicy.RollBackReservedAttempt();
|
s_retryPolicy.RollBackReservedAttempt();
|
||||||
return Program.HasRestartPending;
|
return Program.HasRestartPending(connectionAttempt);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static bool OnDisconnectStatic(DisconnectReason reason, string message)
|
public static bool OnDisconnectStatic(DisconnectReason reason, string message)
|
||||||
|
{
|
||||||
|
return OnDisconnectStatic(reason, message, Program.CurrentConnectionAttempt);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static bool OnDisconnectStatic(DisconnectReason reason, string message, long sourceConnectionAttempt)
|
||||||
{
|
{
|
||||||
if (Config.Enabled)
|
if (Config.Enabled)
|
||||||
{
|
{
|
||||||
AutoRelog bot = new();
|
AutoRelog bot = new(sourceConnectionAttempt);
|
||||||
bot.Initialize();
|
bot.Initialize();
|
||||||
return bot.OnDisconnect(reason, message);
|
return bot.OnDisconnect(reason, message);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
using Brigadier.NET;
|
using System;
|
||||||
|
using Brigadier.NET;
|
||||||
using Brigadier.NET.Builder;
|
using Brigadier.NET.Builder;
|
||||||
using MinecraftClient.CommandHandler;
|
using MinecraftClient.CommandHandler;
|
||||||
using static MinecraftClient.CommandHandler.CmdResult;
|
using static MinecraftClient.CommandHandler.CmdResult;
|
||||||
|
|
@ -42,33 +43,55 @@ namespace MinecraftClient.Commands
|
||||||
|
|
||||||
private int DoConnect(CmdResult r, string server, string account)
|
private int DoConnect(CmdResult r, string server, string account)
|
||||||
{
|
{
|
||||||
|
RestartSettingsSnapshot previousSettings = Program.CaptureRestartSettings();
|
||||||
if (!string.IsNullOrWhiteSpace(account) && !Settings.Config.Main.Advanced.SetAccount(account))
|
if (!string.IsNullOrWhiteSpace(account) && !Settings.Config.Main.Advanced.SetAccount(account))
|
||||||
return r.SetAndReturn(Status.Fail, string.Format(Translations.cmd_connect_unknown, account));
|
return r.SetAndReturn(Status.Fail, string.Format(Translations.cmd_connect_unknown, account));
|
||||||
|
|
||||||
if (Settings.Config.Main.SetServerIP(new Settings.MainConfigHelper.MainConfig.ServerInfoConfig(server), true))
|
if (Settings.Config.Main.SetServerIP(new Settings.MainConfigHelper.MainConfig.ServerInfoConfig(server), true))
|
||||||
{
|
{
|
||||||
Program.Restart(keepAccountAndServerSettings: true);
|
if (Program.TryRestart(
|
||||||
return r.SetAndReturn(Status.Done);
|
Program.CurrentConnectionAttempt,
|
||||||
|
TimeSpan.Zero,
|
||||||
|
keepAccountAndServerSettings: true,
|
||||||
|
replaceUntilCommit: true))
|
||||||
|
{
|
||||||
|
return r.SetAndReturn(Status.Done);
|
||||||
|
}
|
||||||
|
|
||||||
|
Program.RestoreRestartSettings(previousSettings);
|
||||||
|
return r.SetAndReturn(Status.Fail);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
|
Program.RestoreRestartSettings(previousSettings);
|
||||||
return r.SetAndReturn(Status.Fail, string.Format(Translations.cmd_connect_invalid_ip, server));
|
return r.SetAndReturn(Status.Fail, string.Format(Translations.cmd_connect_invalid_ip, server));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static string DoConnect(string command)
|
internal static string DoConnect(string command)
|
||||||
{
|
{
|
||||||
|
RestartSettingsSnapshot previousSettings = Program.CaptureRestartSettings();
|
||||||
string[] args = GetArgs(command);
|
string[] args = GetArgs(command);
|
||||||
if (args.Length > 1 && !Settings.Config.Main.Advanced.SetAccount(args[1]))
|
if (args.Length > 1 && !Settings.Config.Main.Advanced.SetAccount(args[1]))
|
||||||
return string.Format(Translations.cmd_connect_unknown, args[1]);
|
return string.Format(Translations.cmd_connect_unknown, args[1]);
|
||||||
|
|
||||||
if (Settings.Config.Main.SetServerIP(new Settings.MainConfigHelper.MainConfig.ServerInfoConfig(args[0]), true))
|
if (Settings.Config.Main.SetServerIP(new Settings.MainConfigHelper.MainConfig.ServerInfoConfig(args[0]), true))
|
||||||
{
|
{
|
||||||
Program.Restart(keepAccountAndServerSettings: true);
|
if (Program.TryRestart(
|
||||||
return string.Empty;
|
Program.CurrentConnectionAttempt,
|
||||||
|
TimeSpan.Zero,
|
||||||
|
keepAccountAndServerSettings: true,
|
||||||
|
replaceUntilCommit: true))
|
||||||
|
{
|
||||||
|
return string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
Program.RestoreRestartSettings(previousSettings);
|
||||||
|
return Translations.general_fail;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
|
Program.RestoreRestartSettings(previousSettings);
|
||||||
return string.Format(Translations.cmd_connect_invalid_ip, args[0]);
|
return string.Format(Translations.cmd_connect_invalid_ip, args[0]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -41,18 +41,30 @@ namespace MinecraftClient.Commands
|
||||||
|
|
||||||
private int DoReconnect(CmdResult r, string account)
|
private int DoReconnect(CmdResult r, string account)
|
||||||
{
|
{
|
||||||
|
RestartSettingsSnapshot previousSettings = Program.CaptureRestartSettings();
|
||||||
if (!string.IsNullOrWhiteSpace(account))
|
if (!string.IsNullOrWhiteSpace(account))
|
||||||
{
|
{
|
||||||
account = account.Trim();
|
account = account.Trim();
|
||||||
if (!Settings.Config.Main.Advanced.SetAccount(account))
|
if (!Settings.Config.Main.Advanced.SetAccount(account))
|
||||||
return r.SetAndReturn(CmdResult.Status.Fail, string.Format(Translations.cmd_connect_unknown, account));
|
return r.SetAndReturn(CmdResult.Status.Fail, string.Format(Translations.cmd_connect_unknown, account));
|
||||||
}
|
}
|
||||||
Program.Restart(keepAccountAndServerSettings: true);
|
|
||||||
return r.SetAndReturn(CmdResult.Status.Done);
|
if (Program.TryRestart(
|
||||||
|
Program.CurrentConnectionAttempt,
|
||||||
|
TimeSpan.Zero,
|
||||||
|
keepAccountAndServerSettings: true,
|
||||||
|
replaceUntilCommit: true))
|
||||||
|
{
|
||||||
|
return r.SetAndReturn(CmdResult.Status.Done);
|
||||||
|
}
|
||||||
|
|
||||||
|
Program.RestoreRestartSettings(previousSettings);
|
||||||
|
return r.SetAndReturn(CmdResult.Status.Fail);
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static string DoReconnect(string command)
|
internal static string DoReconnect(string command)
|
||||||
{
|
{
|
||||||
|
RestartSettingsSnapshot previousSettings = Program.CaptureRestartSettings();
|
||||||
string[] args = GetArgs(command);
|
string[] args = GetArgs(command);
|
||||||
if (args.Length > 0)
|
if (args.Length > 0)
|
||||||
{
|
{
|
||||||
|
|
@ -62,8 +74,18 @@ namespace MinecraftClient.Commands
|
||||||
return string.Format(Translations.cmd_connect_unknown, account);
|
return string.Format(Translations.cmd_connect_unknown, account);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Program.Restart(keepAccountAndServerSettings: true);
|
|
||||||
return String.Empty;
|
if (Program.TryRestart(
|
||||||
|
Program.CurrentConnectionAttempt,
|
||||||
|
TimeSpan.Zero,
|
||||||
|
keepAccountAndServerSettings: true,
|
||||||
|
replaceUntilCommit: true))
|
||||||
|
{
|
||||||
|
return string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
Program.RestoreRestartSettings(previousSettings);
|
||||||
|
return Translations.general_fail;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
107
MinecraftClient/ConnectionAttemptLifecycle.cs
Normal file
107
MinecraftClient/ConnectionAttemptLifecycle.cs
Normal file
|
|
@ -0,0 +1,107 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Threading;
|
||||||
|
using MinecraftClient.Scripting;
|
||||||
|
|
||||||
|
namespace MinecraftClient
|
||||||
|
{
|
||||||
|
internal sealed class ConnectionAttemptLifecycle
|
||||||
|
{
|
||||||
|
private int disconnectState;
|
||||||
|
|
||||||
|
internal bool IsFailureClaimed => Volatile.Read(ref disconnectState) != 0;
|
||||||
|
|
||||||
|
internal bool TryBeginDisconnect()
|
||||||
|
{
|
||||||
|
return Interlocked.CompareExchange(ref disconnectState, 1, 0) == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal void CompleteDisconnect()
|
||||||
|
{
|
||||||
|
Volatile.Write(ref disconnectState, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static void RestoreHeldBots(ICollection<ChatBot> heldBots, Action<ChatBot> loadBot)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(heldBots);
|
||||||
|
ArgumentNullException.ThrowIfNull(loadBot);
|
||||||
|
|
||||||
|
foreach (ChatBot bot in heldBots)
|
||||||
|
loadBot(bot);
|
||||||
|
heldBots.Clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed class AttemptOwnedRoute
|
||||||
|
{
|
||||||
|
private const long NoOwner = -1;
|
||||||
|
private readonly Lock stateLock = new();
|
||||||
|
private long ownerAttempt = NoOwner;
|
||||||
|
|
||||||
|
internal long OwnerAttempt
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
lock (stateLock)
|
||||||
|
return ownerAttempt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal bool TryActivate(long connectionAttempt, long currentConnectionAttempt, Action activate)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(activate);
|
||||||
|
|
||||||
|
lock (stateLock)
|
||||||
|
{
|
||||||
|
if (connectionAttempt < currentConnectionAttempt || ownerAttempt >= connectionAttempt)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
ownerAttempt = connectionAttempt;
|
||||||
|
activate();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal bool TryDeactivate(long connectionAttempt, Action deactivate)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(deactivate);
|
||||||
|
|
||||||
|
lock (stateLock)
|
||||||
|
{
|
||||||
|
if (ownerAttempt != connectionAttempt)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
ownerAttempt = NoOwner;
|
||||||
|
deactivate();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal bool TryTransfer(long sourceConnectionAttempt, long targetConnectionAttempt)
|
||||||
|
{
|
||||||
|
lock (stateLock)
|
||||||
|
{
|
||||||
|
if (ownerAttempt != sourceConnectionAttempt)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
ownerAttempt = targetConnectionAttempt;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal bool TryDeactivate(Action deactivate)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(deactivate);
|
||||||
|
|
||||||
|
lock (stateLock)
|
||||||
|
{
|
||||||
|
if (ownerAttempt == NoOwner)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
ownerAttempt = NoOwner;
|
||||||
|
deactivate();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -176,6 +176,7 @@ namespace MinecraftClient
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
output.Append(str);
|
output.Append(str);
|
||||||
|
output.Append("§r");
|
||||||
Backend.WriteLineFormatted(output.ToString());
|
Backend.WriteLineFormatted(output.ToString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
using System;
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
using System.Runtime.CompilerServices;
|
using System.Runtime.CompilerServices;
|
||||||
using MinecraftClient.Mapping.BlockPalettes;
|
using MinecraftClient.Mapping.BlockPalettes;
|
||||||
using MinecraftClient.Protocol.Message;
|
using MinecraftClient.Protocol.Message;
|
||||||
|
|
@ -78,6 +79,27 @@ namespace MinecraftClient.Mapping
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Exact raw block state ID. For Minecraft 1.12 and older this contains the packed block ID and metadata.
|
||||||
|
/// </summary>
|
||||||
|
public int StateId => blockIdAndMeta;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Get the properties associated with this block's exact state ID.
|
||||||
|
/// </summary>
|
||||||
|
public IReadOnlyDictionary<string, string> GetStateProperties()
|
||||||
|
{
|
||||||
|
if (Palette.IdHasMetadata)
|
||||||
|
{
|
||||||
|
return new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["metadata"] = BlockMeta.ToString(System.Globalization.CultureInfo.InvariantCulture)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return Palette.GetStateProperties(StateId);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Material of the block
|
/// Material of the block
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
using System.Collections.Generic;
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
namespace MinecraftClient.Mapping.BlockPalettes
|
namespace MinecraftClient.Mapping.BlockPalettes
|
||||||
{
|
{
|
||||||
|
|
@ -23,6 +24,46 @@ namespace MinecraftClient.Mapping.BlockPalettes
|
||||||
return Material.Air;
|
return Material.Air;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Get block-state properties for a modern block state ID.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="stateId">Raw block state ID.</param>
|
||||||
|
/// <returns>Block-state property names and values, or an empty map when unavailable.</returns>
|
||||||
|
public IReadOnlyDictionary<string, string> GetStateProperties(int stateId)
|
||||||
|
{
|
||||||
|
BlockStateDefinition[] definitions = GetStateDefinitions();
|
||||||
|
int low = 0;
|
||||||
|
int high = definitions.Length - 1;
|
||||||
|
|
||||||
|
while (low <= high)
|
||||||
|
{
|
||||||
|
int middle = low + ((high - low) / 2);
|
||||||
|
BlockStateDefinition definition = definitions[middle];
|
||||||
|
if (stateId < definition.FirstStateId)
|
||||||
|
{
|
||||||
|
high = middle - 1;
|
||||||
|
}
|
||||||
|
else if (stateId > definition.LastStateId)
|
||||||
|
{
|
||||||
|
low = middle + 1;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
return definition.GetProperties(stateId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return BlockStateDefinition.EmptyProperties;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Get compact block-state definitions sorted by their first state ID.
|
||||||
|
/// </summary>
|
||||||
|
protected virtual BlockStateDefinition[] GetStateDefinitions()
|
||||||
|
{
|
||||||
|
return Array.Empty<BlockStateDefinition>();
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Returns TRUE if block ID uses old metadata encoding with ID and Meta inside one ushort
|
/// Returns TRUE if block ID uses old metadata encoding with ID and Meta inside one ushort
|
||||||
/// Only Palette112 should override this.
|
/// Only Palette112 should override this.
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,71 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Collections.ObjectModel;
|
||||||
|
|
||||||
|
namespace MinecraftClient.Mapping.BlockPalettes
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Compact description of the property combinations in a contiguous block-state range.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class BlockStateDefinition
|
||||||
|
{
|
||||||
|
private static readonly IReadOnlyDictionary<string, string> s_emptyProperties =
|
||||||
|
new ReadOnlyDictionary<string, string>(new Dictionary<string, string>());
|
||||||
|
|
||||||
|
private readonly BlockStatePropertyDefinition[] _properties;
|
||||||
|
public int FirstStateId { get; }
|
||||||
|
public int LastStateId { get; }
|
||||||
|
public static IReadOnlyDictionary<string, string> EmptyProperties => s_emptyProperties;
|
||||||
|
|
||||||
|
public BlockStateDefinition(int firstStateId, int stateCount, BlockStatePropertyDefinition[] properties)
|
||||||
|
{
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNegative(firstStateId);
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(stateCount);
|
||||||
|
ArgumentNullException.ThrowIfNull(properties);
|
||||||
|
|
||||||
|
FirstStateId = firstStateId;
|
||||||
|
LastStateId = checked(firstStateId + stateCount - 1);
|
||||||
|
_properties = properties;
|
||||||
|
}
|
||||||
|
|
||||||
|
public IReadOnlyDictionary<string, string> GetProperties(int stateId)
|
||||||
|
{
|
||||||
|
if (stateId < FirstStateId || stateId > LastStateId)
|
||||||
|
return EmptyProperties;
|
||||||
|
|
||||||
|
int offset = stateId - FirstStateId;
|
||||||
|
Dictionary<string, string> result = new(_properties.Length, StringComparer.Ordinal);
|
||||||
|
for (int i = 0; i < _properties.Length; i++)
|
||||||
|
{
|
||||||
|
BlockStatePropertyDefinition property = _properties[i];
|
||||||
|
int valueIndex = (offset / property.Stride) % property.Values.Length;
|
||||||
|
result[property.Name] = property.Values[valueIndex];
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Property name and its values in Minecraft's block-state iteration order.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class BlockStatePropertyDefinition
|
||||||
|
{
|
||||||
|
public string Name { get; }
|
||||||
|
public string[] Values { get; }
|
||||||
|
public int Stride { get; }
|
||||||
|
|
||||||
|
public BlockStatePropertyDefinition(string name, string[] values, int stride)
|
||||||
|
{
|
||||||
|
ArgumentException.ThrowIfNullOrEmpty(name);
|
||||||
|
ArgumentNullException.ThrowIfNull(values);
|
||||||
|
if (values.Length == 0)
|
||||||
|
throw new ArgumentException("A block-state property must define at least one value.", nameof(values));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(stride);
|
||||||
|
|
||||||
|
Name = name;
|
||||||
|
Values = values;
|
||||||
|
Stride = stride;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -231,12 +231,14 @@ namespace MinecraftClient
|
||||||
SessionToken _sessionToken;
|
SessionToken _sessionToken;
|
||||||
Tuple<Thread, CancellationTokenSource>? timeoutdetector = null;
|
Tuple<Thread, CancellationTokenSource>? timeoutdetector = null;
|
||||||
private int transferInProgress = 0;
|
private int transferInProgress = 0;
|
||||||
private int disconnectState;
|
private readonly ConnectionAttemptLifecycle connectionLifecycle = new();
|
||||||
private int disconnectOwnerThreadId;
|
private int disconnectOwnerThreadId;
|
||||||
private readonly TaskCompletionSource<bool> disconnectCompletion = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
private readonly TaskCompletionSource<bool> disconnectCompletion = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
|
||||||
public ILogger Log;
|
public ILogger Log;
|
||||||
public DialogManager Dialogs { get; }
|
public DialogManager Dialogs { get; }
|
||||||
|
internal long ConnectionAttempt { get; }
|
||||||
|
internal Task DisconnectCompletion => disconnectCompletion.Task;
|
||||||
|
|
||||||
private static IMinecraftComHandler? instance;
|
private static IMinecraftComHandler? instance;
|
||||||
public static IMinecraftComHandler? Instance => instance;
|
public static IMinecraftComHandler? Instance => instance;
|
||||||
|
|
@ -251,9 +253,22 @@ namespace MinecraftClient
|
||||||
/// <param name="protocolversion">Minecraft protocol version to use</param>
|
/// <param name="protocolversion">Minecraft protocol version to use</param>
|
||||||
/// <param name="forgeInfo">ForgeInfo item stating that Forge is enabled</param>
|
/// <param name="forgeInfo">ForgeInfo item stating that Forge is enabled</param>
|
||||||
public McClient(SessionToken session, PlayerKeyPair? playerKeyPair, string server_ip, ushort port, int protocolversion, ForgeInfo? forgeInfo)
|
public McClient(SessionToken session, PlayerKeyPair? playerKeyPair, string server_ip, ushort port, int protocolversion, ForgeInfo? forgeInfo)
|
||||||
|
: this(session, playerKeyPair, server_ip, port, protocolversion, forgeInfo, Program.CurrentConnectionAttempt)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
internal McClient(
|
||||||
|
SessionToken session,
|
||||||
|
PlayerKeyPair? playerKeyPair,
|
||||||
|
string server_ip,
|
||||||
|
ushort port,
|
||||||
|
int protocolversion,
|
||||||
|
ForgeInfo? forgeInfo,
|
||||||
|
long connectionAttempt)
|
||||||
{
|
{
|
||||||
CmdResult.currentHandler = this;
|
CmdResult.currentHandler = this;
|
||||||
instance = this;
|
instance = this;
|
||||||
|
ConnectionAttempt = connectionAttempt;
|
||||||
|
|
||||||
terrainAndMovementsEnabled = Config.Main.Advanced.TerrainAndMovements;
|
terrainAndMovementsEnabled = Config.Main.Advanced.TerrainAndMovements;
|
||||||
inventoryHandlingEnabled = Config.Main.Advanced.InventoryHandling;
|
inventoryHandlingEnabled = Config.Main.Advanced.InventoryHandling;
|
||||||
|
|
@ -311,7 +326,13 @@ namespace MinecraftClient
|
||||||
LoadCommands();
|
LoadCommands();
|
||||||
|
|
||||||
if (botsOnHold.Count == 0)
|
if (botsOnHold.Count == 0)
|
||||||
|
{
|
||||||
RegisterBots();
|
RegisterBots();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
ConnectionAttemptLifecycle.RestoreHeldBots(botsOnHold, bot => BotLoad(bot, false));
|
||||||
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
|
@ -331,10 +352,6 @@ namespace MinecraftClient
|
||||||
{
|
{
|
||||||
if (handler.Login(this.playerKeyPair, session))
|
if (handler.Login(this.playerKeyPair, session))
|
||||||
{
|
{
|
||||||
foreach (ChatBot bot in botsOnHold)
|
|
||||||
BotLoad(bot, false);
|
|
||||||
botsOnHold.Clear();
|
|
||||||
|
|
||||||
Log.Info(string.Format(Translations.mcc_joined, Config.Main.Advanced.InternalCmdChar.ToLogString()));
|
Log.Info(string.Format(Translations.mcc_joined, Config.Main.Advanced.InternalCmdChar.ToLogString()));
|
||||||
|
|
||||||
StartConsoleSession();
|
StartConsoleSession();
|
||||||
|
|
@ -368,6 +385,9 @@ namespace MinecraftClient
|
||||||
timeoutdetector = null;
|
timeoutdetector = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (connectionLifecycle.IsFailureClaimed)
|
||||||
|
return;
|
||||||
|
|
||||||
if (!InternalConfig.InteractiveMode)
|
if (!InternalConfig.InteractiveMode)
|
||||||
{
|
{
|
||||||
StopConsoleSession();
|
StopConsoleSession();
|
||||||
|
|
@ -391,14 +411,8 @@ namespace MinecraftClient
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// AutoRelog is enabled - invoke its static handler to trigger reconnection.
|
OnConnectionLost(ChatBot.DisconnectReason.ConnectionLost, Translations.mcc_disconnect_lost);
|
||||||
// Use the same "Connection has been lost" message that OnConnectionLost uses
|
return;
|
||||||
// for ConnectionLost, so it matches the default Kick_Messages.
|
|
||||||
if (AutoRelog.OnDisconnectStatic(ChatBot.DisconnectReason.ConnectionLost, Translations.mcc_disconnect_lost))
|
|
||||||
return;
|
|
||||||
|
|
||||||
StopConsoleSession();
|
|
||||||
Program.HandleFailure();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Transfer(string newHost, int newPort)
|
public void Transfer(string newHost, int newPort)
|
||||||
|
|
@ -530,6 +544,7 @@ namespace MinecraftClient
|
||||||
|
|
||||||
private void StartConsoleSession()
|
private void StartConsoleSession()
|
||||||
{
|
{
|
||||||
|
Program.EndOfflinePrompt(ConnectionAttempt);
|
||||||
ConsoleInputRouter.RouteToClient(this);
|
ConsoleInputRouter.RouteToClient(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -875,7 +890,7 @@ namespace MinecraftClient
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
restartScheduled = !exitOnFailure && Program.HasRestartPending;
|
restartScheduled = !exitOnFailure && Program.HasRestartPending(ConnectionAttempt);
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
|
|
@ -888,7 +903,7 @@ namespace MinecraftClient
|
||||||
|
|
||||||
private bool TryBeginDisconnect()
|
private bool TryBeginDisconnect()
|
||||||
{
|
{
|
||||||
if (Interlocked.CompareExchange(ref disconnectState, 1, 0) != 0)
|
if (!connectionLifecycle.TryBeginDisconnect())
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
Volatile.Write(ref disconnectOwnerThreadId, Environment.CurrentManagedThreadId);
|
Volatile.Write(ref disconnectOwnerThreadId, Environment.CurrentManagedThreadId);
|
||||||
|
|
@ -937,7 +952,7 @@ namespace MinecraftClient
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
Volatile.Write(ref disconnectState, 2);
|
connectionLifecycle.CompleteDisconnect();
|
||||||
Volatile.Write(ref disconnectOwnerThreadId, 0);
|
Volatile.Write(ref disconnectOwnerThreadId, 0);
|
||||||
disconnectCompletion.TrySetResult(true);
|
disconnectCompletion.TrySetResult(true);
|
||||||
}
|
}
|
||||||
|
|
@ -3781,6 +3796,8 @@ namespace MinecraftClient
|
||||||
{
|
{
|
||||||
UpdateKeepAlive();
|
UpdateKeepAlive();
|
||||||
|
|
||||||
|
Log.Debug(string.Format(Translations.protocol_chat_raw_message, message.content));
|
||||||
|
|
||||||
List<string> links = new();
|
List<string> links = new();
|
||||||
string messageText;
|
string messageText;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1090,6 +1090,8 @@ public sealed class MccMcpCapabilities : IMccMcpCapabilities
|
||||||
typeLabel,
|
typeLabel,
|
||||||
blockId = block.BlockId,
|
blockId = block.BlockId,
|
||||||
blockMeta = block.BlockMeta,
|
blockMeta = block.BlockMeta,
|
||||||
|
stateId = block.StateId,
|
||||||
|
properties = block.GetStateProperties(),
|
||||||
distance = Math.Sqrt(dx * dx + dy * dy + dz * dz)
|
distance = Math.Sqrt(dx * dx + dy * dy + dz * dz)
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -1139,7 +1141,7 @@ public sealed class MccMcpCapabilities : IMccMcpCapabilities
|
||||||
int cy = (int)Math.Floor(playerLocation.Y) - 1;
|
int cy = (int)Math.Floor(playerLocation.Y) - 1;
|
||||||
int cz = (int)Math.Floor(playerLocation.Z);
|
int cz = (int)Math.Floor(playerLocation.Z);
|
||||||
|
|
||||||
List<(int x, int y, int z, string material, string typeLabel, int blockId, byte blockMeta, double distance)> found = new();
|
List<(int x, int y, int z, string material, string typeLabel, int blockId, byte blockMeta, int stateId, IReadOnlyDictionary<string, string> properties, double distance)> found = new();
|
||||||
World world = client.GetWorld();
|
World world = client.GetWorld();
|
||||||
|
|
||||||
for (int y = cy - radius; y <= cy + radius && found.Count < limit; y++)
|
for (int y = cy - radius; y <= cy + radius && found.Count < limit; y++)
|
||||||
|
|
@ -1167,6 +1169,8 @@ public sealed class MccMcpCapabilities : IMccMcpCapabilities
|
||||||
block.GetTypeString(),
|
block.GetTypeString(),
|
||||||
block.BlockId,
|
block.BlockId,
|
||||||
block.BlockMeta,
|
block.BlockMeta,
|
||||||
|
block.StateId,
|
||||||
|
block.GetStateProperties(),
|
||||||
Math.Sqrt(dx * dx + dy * dy + dz * dz)));
|
Math.Sqrt(dx * dx + dy * dy + dz * dz)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1190,6 +1194,8 @@ public sealed class MccMcpCapabilities : IMccMcpCapabilities
|
||||||
entry.typeLabel,
|
entry.typeLabel,
|
||||||
entry.blockId,
|
entry.blockId,
|
||||||
entry.blockMeta,
|
entry.blockMeta,
|
||||||
|
entry.stateId,
|
||||||
|
entry.properties,
|
||||||
entry.distance
|
entry.distance
|
||||||
})
|
})
|
||||||
.ToArray()
|
.ToArray()
|
||||||
|
|
@ -1853,7 +1859,9 @@ public sealed class MccMcpCapabilities : IMccMcpCapabilities
|
||||||
z,
|
z,
|
||||||
material = block.Type.ToString(),
|
material = block.Type.ToString(),
|
||||||
blockId = block.BlockId,
|
blockId = block.BlockId,
|
||||||
blockMeta = block.BlockMeta
|
blockMeta = block.BlockMeta,
|
||||||
|
stateId = block.StateId,
|
||||||
|
properties = block.GetStateProperties()
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -3121,7 +3129,9 @@ public sealed class MccMcpCapabilities : IMccMcpCapabilities
|
||||||
material = block.Type.ToString(),
|
material = block.Type.ToString(),
|
||||||
typeLabel = block.GetTypeString(),
|
typeLabel = block.GetTypeString(),
|
||||||
blockId = block.BlockId,
|
blockId = block.BlockId,
|
||||||
blockMeta = block.BlockMeta
|
blockMeta = block.BlockMeta,
|
||||||
|
stateId = block.StateId,
|
||||||
|
properties = block.GetStateProperties()
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -38,25 +38,25 @@
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Brigadier.NET" Version="1.2.13" />
|
<PackageReference Include="Brigadier.NET" Version="1.2.13" />
|
||||||
<PackageReference Include="DiscordRichPresence" Version="1.143.0" />
|
<PackageReference Include="DiscordRichPresence" Version="1.143.0" />
|
||||||
<PackageReference Include="Consolonia" Version="11.3.12.3" />
|
<PackageReference Include="Consolonia" Version="11.3.12.6" />
|
||||||
<PackageReference Include="DnsClient" Version="1.8.0" />
|
<PackageReference Include="DnsClient" Version="1.8.0" />
|
||||||
<PackageReference Include="DSharpPlus" Version="4.5.1" />
|
<PackageReference Include="DSharpPlus" Version="4.5.2" />
|
||||||
<PackageReference Include="DynamicExpresso.Core" Version="2.19.3" />
|
<PackageReference Include="DynamicExpresso.Core" Version="2.19.3" />
|
||||||
<PackageReference Include="FuzzySharp" Version="2.0.2" />
|
<PackageReference Include="FuzzySharp" Version="2.0.2" />
|
||||||
<PackageReference Include="Magick.NET-Q16-AnyCPU" Version="14.11.1" />
|
<PackageReference Include="Magick.NET-Q16-AnyCPU" Version="14.15.0" />
|
||||||
<PackageReference Include="MessagePack" Version="3.1.4" />
|
<PackageReference Include="MessagePack" Version="3.1.8" />
|
||||||
<PackageReference Include="ModelContextProtocol" Version="1.2.0" />
|
<PackageReference Include="ModelContextProtocol" Version="1.4.1" />
|
||||||
<PackageReference Include="ModelContextProtocol.AspNetCore" Version="1.2.0" />
|
<PackageReference Include="ModelContextProtocol.AspNetCore" Version="1.4.1" />
|
||||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="5.3.0" />
|
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="5.6.0" />
|
||||||
<PackageReference Include="Microsoft.AspNet.WebApi.Client" Version="6.0.0" />
|
<PackageReference Include="Microsoft.AspNet.WebApi.Client" Version="6.0.0" />
|
||||||
<PackageReference Include="Microsoft.Windows.Compatibility" Version="10.0.5" />
|
<PackageReference Include="Microsoft.Windows.Compatibility" Version="10.0.10" />
|
||||||
<PackageReference Include="Samboy063.Tomlet" Version="6.2.0" />
|
<PackageReference Include="Samboy063.Tomlet" Version="6.2.0" />
|
||||||
<PackageReference Include="Sentry" Version="6.3.1" />
|
<PackageReference Include="Sentry" Version="6.8.0" />
|
||||||
<PackageReference Include="SingleFileExtractor.Core" Version="2.3.0" />
|
<PackageReference Include="SingleFileExtractor.Core" Version="2.3.0" />
|
||||||
<PackageReference Include="starksoft.aspen" Version="1.1.8">
|
<PackageReference Include="starksoft.aspen" Version="1.1.8">
|
||||||
<NoWarn>NU1701</NoWarn>
|
<NoWarn>NU1701</NoWarn>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
<PackageReference Include="Telegram.Bot" Version="22.9.5.3" />
|
<PackageReference Include="Telegram.Bot" Version="22.10.2.1" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Compile Remove="config\**\*.cs" />
|
<Compile Remove="config\**\*.cs" />
|
||||||
|
|
|
||||||
|
|
@ -55,9 +55,10 @@ namespace MinecraftClient
|
||||||
private static bool useMcVersionOnce = false;
|
private static bool useMcVersionOnce = false;
|
||||||
private static readonly RestartCoordinator restartCoordinator = new(ExecuteRestartAsync, ReportRestartFailure);
|
private static readonly RestartCoordinator restartCoordinator = new(ExecuteRestartAsync, ReportRestartFailure);
|
||||||
private static long connectionAttempt;
|
private static long connectionAttempt;
|
||||||
private static int offlinePromptActive;
|
private static readonly AttemptOwnedRoute offlinePromptRoute = new();
|
||||||
private static int exitOnFailurePending;
|
private static int exitOnFailurePending;
|
||||||
private static string settingsIniPath = "MinecraftClient.ini";
|
private static string settingsIniPath = "MinecraftClient.ini";
|
||||||
|
private static AuthenticationSelection? pendingAuthenticationSelection;
|
||||||
|
|
||||||
// [SENTRY]
|
// [SENTRY]
|
||||||
// Setting this string to an empty string will disable Sentry
|
// Setting this string to an empty string will disable Sentry
|
||||||
|
|
@ -565,15 +566,19 @@ namespace MinecraftClient
|
||||||
// Setup exit cleaning code
|
// Setup exit cleaning code
|
||||||
ExitCleanUp.Add(() => { DoExit(); });
|
ExitCleanUp.Add(() => { DoExit(); });
|
||||||
|
|
||||||
|
if (HasNoConfiguredLoginDetails())
|
||||||
|
{
|
||||||
|
if (!PromptForAuthenticationSelection())
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
//Asking the user to type in missing data such as Username and Password
|
//Asking the user to type in missing data such as Username and Password
|
||||||
bool useBrowser = Config.Main.General.AccountType == LoginType.microsoft && Config.Main.General.Method == LoginMethod.browser;
|
bool useBrowser = Config.Main.General.AccountType == LoginType.microsoft && Config.Main.General.Method == LoginMethod.browser;
|
||||||
bool useDeviceCode = Config.Main.General.AccountType == LoginType.microsoft && Config.Main.General.Method == LoginMethod.mcc;
|
bool useDeviceCode = Config.Main.General.AccountType == LoginType.microsoft && Config.Main.General.Method == LoginMethod.mcc;
|
||||||
bool skipPassword = useBrowser || useDeviceCode;
|
bool skipPassword = useBrowser || useDeviceCode;
|
||||||
if (string.IsNullOrWhiteSpace(InternalConfig.Account.Login) && !useBrowser)
|
if (string.IsNullOrWhiteSpace(InternalConfig.Account.Login) && !skipPassword)
|
||||||
{
|
{
|
||||||
ConsoleIO.WriteLine(ConsoleIO.BasicIO ? Translations.mcc_login_basic_io : Translations.mcc_login);
|
if (!RequestLogin())
|
||||||
InternalConfig.Account.Login = ConsoleIO.ReadLine().Trim();
|
|
||||||
if (string.IsNullOrWhiteSpace(InternalConfig.Account.Login))
|
|
||||||
{
|
{
|
||||||
HandleFailure(Translations.error_login_blocked, false, ChatBot.DisconnectReason.LoginRejected);
|
HandleFailure(Translations.error_login_blocked, false, ChatBot.DisconnectReason.LoginRejected);
|
||||||
return;
|
return;
|
||||||
|
|
@ -603,12 +608,153 @@ namespace MinecraftClient
|
||||||
InternalConfig.Account.Password = password;
|
InternalConfig.Account.Password = password;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static bool HasNoConfiguredLoginDetails()
|
||||||
|
=> string.IsNullOrWhiteSpace(InternalConfig.Account.Login)
|
||||||
|
&& string.IsNullOrWhiteSpace(InternalConfig.Account.Password);
|
||||||
|
|
||||||
|
private static bool PromptForAuthenticationSelection()
|
||||||
|
{
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
ConsoleIO.WriteLine(Translations.mcc_auth_method_prompt);
|
||||||
|
string selection = ConsoleIO.ReadLine().Trim();
|
||||||
|
|
||||||
|
switch (selection.ToLowerInvariant())
|
||||||
|
{
|
||||||
|
case "1":
|
||||||
|
case "offline":
|
||||||
|
BeginAuthenticationSelection(LoginType.mojang, LoginMethod.mcc);
|
||||||
|
if (!RequestLogin())
|
||||||
|
{
|
||||||
|
DiscardAuthenticationSelection();
|
||||||
|
HandleFailure(Translations.error_login_blocked, false, ChatBot.DisconnectReason.LoginRejected);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
InternalConfig.Account.Password = "-";
|
||||||
|
return true;
|
||||||
|
|
||||||
|
case "2":
|
||||||
|
case "online":
|
||||||
|
case "microsoft":
|
||||||
|
BeginAuthenticationSelection(LoginType.microsoft, LoginMethod.mcc);
|
||||||
|
return true;
|
||||||
|
|
||||||
|
case "3":
|
||||||
|
case "yggdrasil":
|
||||||
|
BeginAuthenticationSelection(LoginType.yggdrasil, LoginMethod.mcc);
|
||||||
|
if (!RequestLogin() || !RequestRequiredPassword())
|
||||||
|
{
|
||||||
|
DiscardAuthenticationSelection();
|
||||||
|
HandleFailure(Translations.error_login_blocked, false, ChatBot.DisconnectReason.LoginRejected);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!RequestAuthlibServer())
|
||||||
|
{
|
||||||
|
DiscardAuthenticationSelection();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
|
||||||
|
default:
|
||||||
|
ConsoleIO.WriteLine(Translations.mcc_auth_method_invalid);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void BeginAuthenticationSelection(LoginType accountType, LoginMethod method)
|
||||||
|
{
|
||||||
|
pendingAuthenticationSelection ??= new AuthenticationSelection(
|
||||||
|
Config.Main.General.AccountType,
|
||||||
|
Config.Main.General.Method,
|
||||||
|
Config.Main.General.AuthServerUrl);
|
||||||
|
|
||||||
|
Config.Main.General.AccountType = accountType;
|
||||||
|
Config.Main.General.Method = method;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool RequestLogin()
|
||||||
|
{
|
||||||
|
ConsoleIO.WriteLine(ConsoleIO.BasicIO ? Translations.mcc_login_basic_io : Translations.mcc_login);
|
||||||
|
InternalConfig.Account.Login = ConsoleIO.ReadLine().Trim();
|
||||||
|
return !string.IsNullOrWhiteSpace(InternalConfig.Account.Login);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool RequestRequiredPassword()
|
||||||
|
{
|
||||||
|
ConsoleIO.WriteLine(ConsoleIO.BasicIO ? string.Format(Translations.mcc_password_basic_io, InternalConfig.Account.Login) + "\n" : Translations.mcc_password_hidden);
|
||||||
|
string? password = ConsoleIO.BasicIO ? Console.ReadLine() : ConsoleIO.ReadPassword();
|
||||||
|
if (string.IsNullOrWhiteSpace(password))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
InternalConfig.Account.Password = password;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool RequestAuthlibServer()
|
||||||
|
{
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
ConsoleIO.WriteLine(Translations.mcc_yggdrasil_url);
|
||||||
|
string authServerUrl = ConsoleIO.ReadLine().Trim();
|
||||||
|
if (!Config.Main.General.TrySetAuthServerUrl(authServerUrl)
|
||||||
|
|| !Config.Main.General.TryGetAuthServerUri(out Uri? authServerUri))
|
||||||
|
{
|
||||||
|
ConsoleIO.WriteLine(Translations.mcc_yggdrasil_invalid_url);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (ProtocolHandler.ValidateAuthlibServer(authServerUri))
|
||||||
|
{
|
||||||
|
case ProtocolHandler.AuthlibServerValidationResult.Valid:
|
||||||
|
return true;
|
||||||
|
case ProtocolHandler.AuthlibServerValidationResult.Unreachable:
|
||||||
|
ConsoleIO.WriteLine(Translations.mcc_yggdrasil_server_unreachable);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
ConsoleIO.WriteLine(Translations.mcc_yggdrasil_server_invalid);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void PersistAuthenticationSelection(SessionToken session)
|
||||||
|
{
|
||||||
|
if (pendingAuthenticationSelection is null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(InternalConfig.Account.Login))
|
||||||
|
InternalConfig.Account.Login = session.PlayerName;
|
||||||
|
|
||||||
|
Config.Main.General.Account = InternalConfig.Account;
|
||||||
|
WriteBackSettings();
|
||||||
|
pendingAuthenticationSelection = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void DiscardAuthenticationSelection()
|
||||||
|
{
|
||||||
|
if (pendingAuthenticationSelection is not AuthenticationSelection selection)
|
||||||
|
return;
|
||||||
|
|
||||||
|
Config.Main.General.AccountType = selection.AccountType;
|
||||||
|
Config.Main.General.Method = selection.Method;
|
||||||
|
Config.Main.General.AuthServerUrl = selection.AuthServerUrl;
|
||||||
|
pendingAuthenticationSelection = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed record AuthenticationSelection(LoginType AccountType, LoginMethod Method, string AuthServerUrl);
|
||||||
|
|
||||||
|
internal static long CurrentConnectionAttempt => Volatile.Read(ref connectionAttempt);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Start a new Client
|
/// Start a new Client
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private static void InitializeClient()
|
private static void InitializeClient()
|
||||||
{
|
{
|
||||||
Interlocked.Increment(ref connectionAttempt);
|
long attempt = Interlocked.Increment(ref connectionAttempt);
|
||||||
|
|
||||||
// Ensure that we use the provided Minecraft version if we can't connect automatically.
|
// Ensure that we use the provided Minecraft version if we can't connect automatically.
|
||||||
//
|
//
|
||||||
|
|
@ -628,7 +774,7 @@ namespace MinecraftClient
|
||||||
ConsoleIO.WriteLineFormatted("§8" + Translations.mcc_offline, acceptnewlines: true);
|
ConsoleIO.WriteLineFormatted("§8" + Translations.mcc_offline, acceptnewlines: true);
|
||||||
result = ProtocolHandler.LoginResult.Success;
|
result = ProtocolHandler.LoginResult.Success;
|
||||||
session.PlayerID = "0";
|
session.PlayerID = "0";
|
||||||
session.PlayerName = InternalConfig.Username;
|
session.PlayerName = InternalConfig.Account.Login;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
|
|
@ -664,17 +810,26 @@ namespace MinecraftClient
|
||||||
|
|
||||||
if (result != ProtocolHandler.LoginResult.Success)
|
if (result != ProtocolHandler.LoginResult.Success)
|
||||||
{
|
{
|
||||||
ConsoleIO.WriteLine(string.Format(Translations.mcc_connecting, Config.Main.General.AccountType == LoginType.mojang ? "Minecraft.net" : (Config.Main.General.AccountType == LoginType.microsoft ? "Microsoft" : Config.Main.General.AuthServer.Host)));
|
ConsoleIO.WriteLine(string.Format(Translations.mcc_connecting, Config.Main.General.AccountType == LoginType.mojang ? "Minecraft.net" : (Config.Main.General.AccountType == LoginType.microsoft ? "Microsoft" : Config.Main.General.AuthServerUrl)));
|
||||||
result = ProtocolHandler.GetLogin(InternalConfig.Account.Login, InternalConfig.Account.Password, Config.Main.General.AccountType, out session);
|
result = ProtocolHandler.GetLogin(InternalConfig.Account.Login, InternalConfig.Account.Password, Config.Main.General.AccountType, out session);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (result == ProtocolHandler.LoginResult.Success && Config.Main.Advanced.SessionCache != CacheType.none)
|
if (result == ProtocolHandler.LoginResult.Success)
|
||||||
SessionCache.Store(loginLower, session);
|
{
|
||||||
|
PersistAuthenticationSelection(session);
|
||||||
|
loginLower = ToLowerIfNeed(InternalConfig.Account.Login);
|
||||||
|
|
||||||
|
if (Config.Main.Advanced.SessionCache != CacheType.none)
|
||||||
|
SessionCache.Store(loginLower, session);
|
||||||
|
}
|
||||||
|
|
||||||
if (result == ProtocolHandler.LoginResult.Success)
|
if (result == ProtocolHandler.LoginResult.Success)
|
||||||
session.SessionPreCheckTask = Task.Factory.StartNew(() => session.SessionPreCheck(Config.Main.General.AccountType));
|
session.SessionPreCheckTask = Task.Factory.StartNew(() => session.SessionPreCheck(Config.Main.General.AccountType));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (result == ProtocolHandler.LoginResult.Success)
|
||||||
|
PersistAuthenticationSelection(session);
|
||||||
|
|
||||||
if (result == ProtocolHandler.LoginResult.Success)
|
if (result == ProtocolHandler.LoginResult.Success)
|
||||||
{
|
{
|
||||||
InternalConfig.Username = session.PlayerName;
|
InternalConfig.Username = session.PlayerName;
|
||||||
|
|
@ -831,7 +986,7 @@ namespace MinecraftClient
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
//Start the main TCP client
|
//Start the main TCP client
|
||||||
client = new McClient(session, playerKeyPair, InternalConfig.ServerIP, InternalConfig.ServerPort, protocolversion, forgeInfo);
|
client = new McClient(session, playerKeyPair, InternalConfig.ServerIP, InternalConfig.ServerPort, protocolversion, forgeInfo, attempt);
|
||||||
|
|
||||||
//Update console title
|
//Update console title
|
||||||
if (OperatingSystem.IsWindows() && !string.IsNullOrWhiteSpace(Config.Main.Advanced.ConsoleTitle))
|
if (OperatingSystem.IsWindows() && !string.IsNullOrWhiteSpace(Config.Main.Advanced.ConsoleTitle))
|
||||||
|
|
@ -859,6 +1014,7 @@ namespace MinecraftClient
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
|
DiscardAuthenticationSelection();
|
||||||
string failureMessage = Translations.error_login;
|
string failureMessage = Translations.error_login;
|
||||||
string failureReason = result switch
|
string failureReason = result switch
|
||||||
{
|
{
|
||||||
|
|
@ -908,7 +1064,22 @@ namespace MinecraftClient
|
||||||
TryRestart(TimeSpan.FromSeconds(Math.Max(0, delaySeconds)), keepAccountAndServerSettings);
|
TryRestart(TimeSpan.FromSeconds(Math.Max(0, delaySeconds)), keepAccountAndServerSettings);
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static bool HasRestartPending => restartCoordinator.HasScheduledRestart(Volatile.Read(ref connectionAttempt));
|
internal static bool HasRestartPending(long sourceConnectionAttempt)
|
||||||
|
{
|
||||||
|
return restartCoordinator.HasScheduledRestart(sourceConnectionAttempt);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static RestartSettingsSnapshot CaptureRestartSettings()
|
||||||
|
{
|
||||||
|
return new RestartSettingsSnapshot(InternalConfig.Account, InternalConfig.ServerIP, InternalConfig.ServerPort);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static void RestoreRestartSettings(RestartSettingsSnapshot settingsSnapshot)
|
||||||
|
{
|
||||||
|
InternalConfig.Account = settingsSnapshot.Account;
|
||||||
|
InternalConfig.ServerIP = settingsSnapshot.ServerIP;
|
||||||
|
InternalConfig.ServerPort = settingsSnapshot.ServerPort;
|
||||||
|
}
|
||||||
|
|
||||||
internal static bool TryRestart(int delaySeconds = 0, bool keepAccountAndServerSettings = false)
|
internal static bool TryRestart(int delaySeconds = 0, bool keepAccountAndServerSettings = false)
|
||||||
{
|
{
|
||||||
|
|
@ -916,21 +1087,47 @@ namespace MinecraftClient
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static bool TryRestart(TimeSpan delay, bool keepAccountAndServerSettings = false)
|
internal static bool TryRestart(TimeSpan delay, bool keepAccountAndServerSettings = false)
|
||||||
|
{
|
||||||
|
return TryRestart(CurrentConnectionAttempt, delay, keepAccountAndServerSettings);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static bool TryRestart(
|
||||||
|
long sourceConnectionAttempt,
|
||||||
|
TimeSpan delay,
|
||||||
|
bool keepAccountAndServerSettings = false,
|
||||||
|
bool replaceUntilCommit = false,
|
||||||
|
Task? sourceCleanupCompletion = null)
|
||||||
{
|
{
|
||||||
if (Volatile.Read(ref exitOnFailurePending) != 0)
|
if (Volatile.Read(ref exitOnFailurePending) != 0)
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
|
if (sourceConnectionAttempt != CurrentConnectionAttempt)
|
||||||
|
return false;
|
||||||
|
|
||||||
if (delay < TimeSpan.Zero)
|
if (delay < TimeSpan.Zero)
|
||||||
delay = TimeSpan.Zero;
|
delay = TimeSpan.Zero;
|
||||||
|
|
||||||
return restartCoordinator.TrySchedule(new RestartRequest(
|
RestartSettingsSnapshot? settingsSnapshot = keepAccountAndServerSettings
|
||||||
Volatile.Read(ref connectionAttempt),
|
? CaptureRestartSettings()
|
||||||
delay,
|
: null;
|
||||||
keepAccountAndServerSettings));
|
|
||||||
|
bool scheduled = restartCoordinator.TrySchedule(
|
||||||
|
new RestartRequest(
|
||||||
|
sourceConnectionAttempt,
|
||||||
|
delay,
|
||||||
|
keepAccountAndServerSettings,
|
||||||
|
settingsSnapshot,
|
||||||
|
replaceUntilCommit,
|
||||||
|
sourceCleanupCompletion),
|
||||||
|
() => BeginOfflinePrompt(sourceConnectionAttempt));
|
||||||
|
return scheduled;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static async Task ExecuteRestartAsync(RestartRequest request, CancellationToken cancellationToken)
|
private static async Task ExecuteRestartAsync(RestartRequest request, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
|
if (request.ConnectionAttempt != CurrentConnectionAttempt)
|
||||||
|
return;
|
||||||
|
|
||||||
McClient? disconnectedClient = client;
|
McClient? disconnectedClient = client;
|
||||||
if (disconnectedClient is not null)
|
if (disconnectedClient is not null)
|
||||||
{
|
{
|
||||||
|
|
@ -939,7 +1136,6 @@ namespace MinecraftClient
|
||||||
client = null;
|
client = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
EndOfflinePrompt();
|
|
||||||
ConsoleIO.Reset();
|
ConsoleIO.Reset();
|
||||||
|
|
||||||
if (request.Delay > TimeSpan.Zero)
|
if (request.Delay > TimeSpan.Zero)
|
||||||
|
|
@ -949,8 +1145,22 @@ namespace MinecraftClient
|
||||||
}
|
}
|
||||||
|
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
if (request.ConnectionAttempt != CurrentConnectionAttempt
|
||||||
|
|| !restartCoordinator.TryBeginCommit(request, out RestartRequest latestRequest)
|
||||||
|
|| latestRequest.ConnectionAttempt != CurrentConnectionAttempt)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
ConsoleIO.WriteLine(Translations.mcc_restart);
|
ConsoleIO.WriteLine(Translations.mcc_restart);
|
||||||
ReloadSettings(request.KeepAccountAndServerSettings);
|
ReloadSettings(latestRequest.KeepAccountAndServerSettings);
|
||||||
|
if (latestRequest.SettingsSnapshot is RestartSettingsSnapshot settingsSnapshot)
|
||||||
|
{
|
||||||
|
InternalConfig.Account = settingsSnapshot.Account;
|
||||||
|
InternalConfig.ServerIP = settingsSnapshot.ServerIP;
|
||||||
|
InternalConfig.ServerPort = settingsSnapshot.ServerPort;
|
||||||
|
}
|
||||||
|
TransferOfflinePrompt(latestRequest.ConnectionAttempt, latestRequest.ConnectionAttempt + 1);
|
||||||
InitializeClient();
|
InitializeClient();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1032,7 +1242,7 @@ namespace MinecraftClient
|
||||||
if (!string.IsNullOrEmpty(errorMessage) && disconnectReason.HasValue)
|
if (!string.IsNullOrEmpty(errorMessage) && disconnectReason.HasValue)
|
||||||
{
|
{
|
||||||
autoRelogHandled = true;
|
autoRelogHandled = true;
|
||||||
if (ChatBots.AutoRelog.OnDisconnectStatic(disconnectReason.Value, errorMessage))
|
if (ChatBots.AutoRelog.OnDisconnectStatic(disconnectReason.Value, errorMessage, CurrentConnectionAttempt))
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1052,35 +1262,58 @@ namespace MinecraftClient
|
||||||
|
|
||||||
if (!autoRelogHandled && disconnectReason.HasValue)
|
if (!autoRelogHandled && disconnectReason.HasValue)
|
||||||
{
|
{
|
||||||
if (ChatBots.AutoRelog.OnDisconnectStatic(disconnectReason.Value, errorMessage!))
|
if (ChatBots.AutoRelog.OnDisconnectStatic(disconnectReason.Value, errorMessage!, CurrentConnectionAttempt))
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
BeginOfflinePrompt();
|
BeginOfflinePrompt(CurrentConnectionAttempt);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void BeginOfflinePrompt()
|
private static bool BeginOfflinePrompt(long connectionAttempt)
|
||||||
{
|
{
|
||||||
if (Interlocked.CompareExchange(ref offlinePromptActive, 1, 0) != 0)
|
long currentConnectionAttempt = CurrentConnectionAttempt;
|
||||||
return;
|
if (connectionAttempt != currentConnectionAttempt)
|
||||||
|
return false;
|
||||||
|
|
||||||
ConsoleInputRouter.RouteOffline(HandleOfflineCommand);
|
if (offlinePromptRoute.TryActivate(connectionAttempt, currentConnectionAttempt, () =>
|
||||||
ConsoleIO.WriteLine(string.Empty);
|
{
|
||||||
ConsoleIO.WriteLineFormatted(string.Format(Translations.mcc_disconnected, Config.Main.Advanced.InternalCmdChar.ToLogString()));
|
ConsoleInputRouter.RouteOffline(HandleOfflineCommand);
|
||||||
if (ConsoleIO.Backend is Tui.TuiConsoleBackend)
|
ConsoleIO.WriteLine(string.Empty);
|
||||||
ConsoleIO.WriteLineFormatted(string.Format(Translations.mcc_use_quit_to_exit, Config.Main.Advanced.InternalCmdChar.ToLogString()));
|
ConsoleIO.WriteLineFormatted(string.Format(Translations.mcc_disconnected, Config.Main.Advanced.InternalCmdChar.ToLogString()));
|
||||||
else
|
if (ConsoleIO.Backend is Tui.TuiConsoleBackend)
|
||||||
ConsoleIO.WriteLineFormatted(Translations.mcc_press_exit, acceptnewlines: true);
|
ConsoleIO.WriteLineFormatted(string.Format(Translations.mcc_use_quit_to_exit, Config.Main.Advanced.InternalCmdChar.ToLogString()));
|
||||||
|
else
|
||||||
|
ConsoleIO.WriteLineFormatted(Translations.mcc_press_exit, acceptnewlines: true);
|
||||||
|
}))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return offlinePromptRoute.OwnerAttempt == connectionAttempt;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void EndOfflinePrompt()
|
private static void EndOfflinePrompt()
|
||||||
{
|
{
|
||||||
if (Interlocked.Exchange(ref offlinePromptActive, 0) == 0)
|
offlinePromptRoute.TryDeactivate(() =>
|
||||||
return;
|
{
|
||||||
|
ConsoleInputRouter.ClearOfflineRoute(HandleOfflineCommand);
|
||||||
|
ConsoleIO.Reset();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
ConsoleInputRouter.ClearOfflineRoute(HandleOfflineCommand);
|
internal static void EndOfflinePrompt(long connectionAttempt)
|
||||||
ConsoleIO.Reset();
|
{
|
||||||
|
offlinePromptRoute.TryDeactivate(connectionAttempt, () =>
|
||||||
|
{
|
||||||
|
ConsoleInputRouter.ClearOfflineRoute(HandleOfflineCommand);
|
||||||
|
ConsoleIO.Reset();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TransferOfflinePrompt(long sourceConnectionAttempt, long targetConnectionAttempt)
|
||||||
|
{
|
||||||
|
offlinePromptRoute.TryTransfer(sourceConnectionAttempt, targetConnectionAttempt);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void HandleOfflineCommand(string input)
|
private static void HandleOfflineCommand(string input)
|
||||||
|
|
@ -1104,19 +1337,13 @@ namespace MinecraftClient
|
||||||
{
|
{
|
||||||
message = Commands.Reco.DoReconnect(Config.AppVar.ExpandVars(command));
|
message = Commands.Reco.DoReconnect(Config.AppVar.ExpandVars(command));
|
||||||
if (message.Length == 0)
|
if (message.Length == 0)
|
||||||
{
|
|
||||||
EndOfflinePrompt();
|
|
||||||
return;
|
return;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
else if (command.StartsWith("connect", StringComparison.Ordinal))
|
else if (command.StartsWith("connect", StringComparison.Ordinal))
|
||||||
{
|
{
|
||||||
message = Commands.Connect.DoConnect(Config.AppVar.ExpandVars(command));
|
message = Commands.Connect.DoConnect(Config.AppVar.ExpandVars(command));
|
||||||
if (message.Length == 0)
|
if (message.Length == 0)
|
||||||
{
|
|
||||||
EndOfflinePrompt();
|
|
||||||
return;
|
return;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
else if (command.StartsWith("exit", StringComparison.Ordinal)
|
else if (command.StartsWith("exit", StringComparison.Ordinal)
|
||||||
|| command.StartsWith("quit", StringComparison.Ordinal))
|
|| command.StartsWith("quit", StringComparison.Ordinal))
|
||||||
|
|
|
||||||
|
|
@ -287,6 +287,7 @@ namespace MinecraftClient.Protocol.Handlers
|
||||||
},
|
},
|
||||||
_ => ChatParser.ChatId2Type
|
_ => ChatParser.ChatId2Type
|
||||||
};
|
};
|
||||||
|
ChatParser.ClearChatTypeDecorations();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|
@ -304,7 +305,10 @@ namespace MinecraftClient.Protocol.Handlers
|
||||||
{
|
{
|
||||||
Stopwatch stopWatch = Stopwatch.StartNew();
|
Stopwatch stopWatch = Stopwatch.StartNew();
|
||||||
long nextUpdateDue = 0;
|
long nextUpdateDue = 0;
|
||||||
while (!packetQueue.IsAddingCompleted)
|
// Continue until the reader has finished and every queued packet has been handled.
|
||||||
|
// A server can close immediately after a Disconnect packet, completing the queue
|
||||||
|
// while that final packet is still waiting to be processed.
|
||||||
|
while (!packetQueue.IsCompleted)
|
||||||
{
|
{
|
||||||
cancelToken.ThrowIfCancellationRequested();
|
cancelToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
|
|
@ -573,7 +577,6 @@ namespace MinecraftClient.Protocol.Handlers
|
||||||
var isEnchantment = registryId == "minecraft:enchantment";
|
var isEnchantment = registryId == "minecraft:enchantment";
|
||||||
var isDialog = registryId == "minecraft:dialog";
|
var isDialog = registryId == "minecraft:dialog";
|
||||||
|
|
||||||
var availableChats = isChat ? new Dictionary<int, string>() : null;
|
|
||||||
var dimensionIdMap = isDimension ? new Dictionary<int, string>() : null;
|
var dimensionIdMap = isDimension ? new Dictionary<int, string>() : null;
|
||||||
var attributeIdMap = isAttribute ? new Dictionary<int, string>() : null;
|
var attributeIdMap = isAttribute ? new Dictionary<int, string>() : null;
|
||||||
var enchantmentIdMap = isEnchantment ? new Dictionary<int, string>() : null;
|
var enchantmentIdMap = isEnchantment ? new Dictionary<int, string>() : null;
|
||||||
|
|
@ -588,7 +591,7 @@ namespace MinecraftClient.Protocol.Handlers
|
||||||
nbtData = dataTypes.ReadNextNbt(packetData);
|
nbtData = dataTypes.ReadNextNbt(packetData);
|
||||||
|
|
||||||
if (isChat)
|
if (isChat)
|
||||||
availableChats!.Add(i, entryId);
|
ChatParser.ReadChatType(i, entryId, nbtData);
|
||||||
else if (isDimension)
|
else if (isDimension)
|
||||||
{
|
{
|
||||||
dimensionIdMap!.Add(i, entryId);
|
dimensionIdMap!.Add(i, entryId);
|
||||||
|
|
@ -608,9 +611,7 @@ namespace MinecraftClient.Protocol.Handlers
|
||||||
handler.OnDialogRegistryData(i, entryId, dialogNbtParser.Parse(nbtData));
|
handler.OnDialogRegistryData(i, entryId, dialogNbtParser.Parse(nbtData));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isChat)
|
if (isDimension)
|
||||||
ChatParser.ReadChatType(availableChats!);
|
|
||||||
else if (isDimension)
|
|
||||||
{
|
{
|
||||||
World.SetDimensionIdMap(dimensionIdMap!);
|
World.SetDimensionIdMap(dimensionIdMap!);
|
||||||
if (!handler.GetTerrainEnabled() || !World.HasAnyDimension())
|
if (!handler.GetTerrainEnabled() || !World.HasAnyDimension())
|
||||||
|
|
@ -1229,7 +1230,8 @@ namespace MinecraftClient.Protocol.Handlers
|
||||||
|
|
||||||
// Network Target
|
// Network Target
|
||||||
// net.minecraft.network.message.MessageType.Serialized#write
|
// net.minecraft.network.message.MessageType.Serialized#write
|
||||||
var chatTypeId = dataTypes.ReadNextVarInt(packetData);
|
var chatTypeId = ChatParser.ReadChatTypeHolder(
|
||||||
|
dataTypes, packetData, protocolVersion, out var directChatTypeDecoration);
|
||||||
var chatName = dataTypes.ReadNextChat(packetData);
|
var chatName = dataTypes.ReadNextChat(packetData);
|
||||||
var targetName = dataTypes.ReadNextBool(packetData)
|
var targetName = dataTypes.ReadNextBool(packetData)
|
||||||
? dataTypes.ReadNextChat(packetData)
|
? dataTypes.ReadNextChat(packetData)
|
||||||
|
|
@ -1278,7 +1280,10 @@ namespace MinecraftClient.Protocol.Handlers
|
||||||
}
|
}
|
||||||
|
|
||||||
ChatMessage chat = new(message, false, chatTypeId, senderUuid, unsignedChatContent,
|
ChatMessage chat = new(message, false, chatTypeId, senderUuid, unsignedChatContent,
|
||||||
senderDisplayName, senderTeamName, timestamp, messageSignature, verifyResult);
|
senderDisplayName, senderTeamName, timestamp, messageSignature, verifyResult)
|
||||||
|
{
|
||||||
|
chatTypeDecoration = directChatTypeDecoration
|
||||||
|
};
|
||||||
lock (MessageSigningLock)
|
lock (MessageSigningLock)
|
||||||
Acknowledge(chat);
|
Acknowledge(chat);
|
||||||
handler.OnTextReceived(chat);
|
handler.OnTextReceived(chat);
|
||||||
|
|
@ -1342,14 +1347,17 @@ namespace MinecraftClient.Protocol.Handlers
|
||||||
break;
|
break;
|
||||||
case PacketTypesIn.ProfilelessChatMessage:
|
case PacketTypesIn.ProfilelessChatMessage:
|
||||||
var message_ = dataTypes.ReadNextChat(packetData);
|
var message_ = dataTypes.ReadNextChat(packetData);
|
||||||
var messageType_ = dataTypes.ReadNextVarInt(packetData);
|
var messageType_ = ChatParser.ReadChatTypeHolder(
|
||||||
|
dataTypes, packetData, protocolVersion, out var directProfilelessChatTypeDecoration);
|
||||||
var messageName = dataTypes.ReadNextChat(packetData);
|
var messageName = dataTypes.ReadNextChat(packetData);
|
||||||
var targetName_ = dataTypes.ReadNextBool(packetData)
|
var targetName_ = dataTypes.ReadNextBool(packetData)
|
||||||
? dataTypes.ReadNextChat(packetData)
|
? dataTypes.ReadNextChat(packetData)
|
||||||
: null;
|
: null;
|
||||||
ChatMessage profilelessChat = new(message_, targetName_ ?? messageName, false, messageType_,
|
ChatMessage profilelessChat = new(message_, messageName, false, messageType_,
|
||||||
Guid.Empty, true);
|
Guid.Empty, true);
|
||||||
profilelessChat.isSenderJson = false;
|
profilelessChat.isSenderJson = false;
|
||||||
|
profilelessChat.teamName = targetName_;
|
||||||
|
profilelessChat.chatTypeDecoration = directProfilelessChatTypeDecoration;
|
||||||
handler.OnTextReceived(profilelessChat);
|
handler.OnTextReceived(profilelessChat);
|
||||||
break;
|
break;
|
||||||
case PacketTypesIn.CombatEvent:
|
case PacketTypesIn.CombatEvent:
|
||||||
|
|
@ -5713,6 +5721,13 @@ namespace MinecraftClient.Protocol.Handlers
|
||||||
{
|
{
|
||||||
List<byte> fields = new();
|
List<byte> fields = new();
|
||||||
fields.AddRange(DataTypes.GetVarInt(EntityID));
|
fields.AddRange(DataTypes.GetVarInt(EntityID));
|
||||||
|
|
||||||
|
if (protocolVersion >= MC_26_1_Version && type == (int)InteractType.Attack)
|
||||||
|
{
|
||||||
|
SendPacket(PacketTypesOut.Attack, fields);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
fields.AddRange(DataTypes.GetVarInt(type));
|
fields.AddRange(DataTypes.GetVarInt(type));
|
||||||
|
|
||||||
// Is player Sneaking (Only 1.16 and above)
|
// Is player Sneaking (Only 1.16 and above)
|
||||||
|
|
|
||||||
|
|
@ -35,6 +35,8 @@ namespace MinecraftClient.Protocol.Message
|
||||||
|
|
||||||
public bool? isSignatureLegal;
|
public bool? isSignatureLegal;
|
||||||
|
|
||||||
|
internal ChatParser.ChatTypeDecoration? chatTypeDecoration;
|
||||||
|
|
||||||
public ChatMessage(string content, bool isJson, int chatType, Guid senderUUID, string? unsignedContent, string displayName, string? teamName, long timestamp, byte[]? signature, bool isSignatureLegal)
|
public ChatMessage(string content, bool isJson, int chatType, Guid senderUUID, string? unsignedContent, string displayName, string? teamName, long timestamp, byte[]? signature, bool isSignatureLegal)
|
||||||
{
|
{
|
||||||
isSignedChat = true;
|
isSignedChat = true;
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,7 @@ using System.Text;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Text.RegularExpressions;
|
using System.Text.RegularExpressions;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
using MinecraftClient.Protocol.Handlers;
|
||||||
using Tomlet;
|
using Tomlet;
|
||||||
using Tomlet.Models;
|
using Tomlet.Models;
|
||||||
using static MinecraftClient.Settings;
|
using static MinecraftClient.Settings;
|
||||||
|
|
@ -36,33 +37,49 @@ namespace MinecraftClient.Protocol.Message
|
||||||
|
|
||||||
public static Dictionary<int, MessageType>? ChatId2Type;
|
public static Dictionary<int, MessageType>? ChatId2Type;
|
||||||
|
|
||||||
|
internal enum ChatTypeParameter
|
||||||
|
{
|
||||||
|
Sender,
|
||||||
|
Target,
|
||||||
|
Content
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed record ChatTypeDecoration(string TranslationKey, ChatTypeParameter[] Parameters);
|
||||||
|
|
||||||
|
private static readonly Dictionary<int, ChatTypeDecoration> ChatId2Decoration = new();
|
||||||
|
|
||||||
|
internal static void ClearChatTypeDecorations()
|
||||||
|
{
|
||||||
|
ChatId2Decoration.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
// Used to store Chat Types in 1.20.6+
|
// Used to store Chat Types in 1.20.6+
|
||||||
public static void ReadChatType(Dictionary<int, string> data)
|
public static void ReadChatType(int chatId, string chatName, Dictionary<string, object>? chatTypeData)
|
||||||
{
|
{
|
||||||
var chatTypeDictionary = ChatId2Type ?? new Dictionary<int, MessageType>();
|
var chatTypeDictionary = ChatId2Type ?? new Dictionary<int, MessageType>();
|
||||||
|
|
||||||
foreach (var (chatId, chatName) in data)
|
chatTypeDictionary[chatId] = chatName switch
|
||||||
{
|
{
|
||||||
chatTypeDictionary[chatId] = chatName switch
|
"minecraft:chat" => MessageType.CHAT,
|
||||||
{
|
"minecraft:emote_command" => MessageType.EMOTE_COMMAND,
|
||||||
"minecraft:chat" => MessageType.CHAT,
|
"minecraft:msg_command_incoming" => MessageType.MSG_COMMAND_INCOMING,
|
||||||
"minecraft:emote_command" => MessageType.EMOTE_COMMAND,
|
"minecraft:msg_command_outgoing" => MessageType.MSG_COMMAND_OUTGOING,
|
||||||
"minecraft:msg_command_incoming" => MessageType.MSG_COMMAND_INCOMING,
|
"minecraft:say_command" => MessageType.SAY_COMMAND,
|
||||||
"minecraft:msg_command_outgoing" => MessageType.MSG_COMMAND_OUTGOING,
|
"minecraft:team_msg_command_incoming" => MessageType.TEAM_MSG_COMMAND_INCOMING,
|
||||||
"minecraft:say_command" => MessageType.SAY_COMMAND,
|
"minecraft:team_msg_command_outgoing" => MessageType.TEAM_MSG_COMMAND_OUTGOING,
|
||||||
"minecraft:team_msg_command_incoming" => MessageType.TEAM_MSG_COMMAND_INCOMING,
|
_ => MessageType.CHAT,
|
||||||
"minecraft:team_msg_command_outgoing" => MessageType.TEAM_MSG_COMMAND_OUTGOING,
|
};
|
||||||
_ => MessageType.CHAT,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
ChatId2Type = chatTypeDictionary;
|
ChatId2Type = chatTypeDictionary;
|
||||||
|
|
||||||
|
if (TryReadChatTypeDecoration(chatTypeData, out var decoration))
|
||||||
|
ChatId2Decoration[chatId] = decoration;
|
||||||
|
else
|
||||||
|
ChatId2Decoration.Remove(chatId);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void ReadChatType(Dictionary<string, object> registryCodec)
|
public static void ReadChatType(Dictionary<string, object> registryCodec)
|
||||||
{
|
{
|
||||||
Dictionary<int, MessageType> chatTypeDictionary = ChatId2Type ?? new();
|
|
||||||
|
|
||||||
// Check if the chat type registry is in the correct format
|
// Check if the chat type registry is in the correct format
|
||||||
if (!registryCodec.ContainsKey("minecraft:chat_type"))
|
if (!registryCodec.ContainsKey("minecraft:chat_type"))
|
||||||
{
|
{
|
||||||
|
|
@ -84,25 +101,80 @@ namespace MinecraftClient.Protocol.Message
|
||||||
}
|
}
|
||||||
|
|
||||||
var chatTypeListNbt = (object[])(((Dictionary<string, object>)registryCodec["minecraft:chat_type"])["value"]);
|
var chatTypeListNbt = (object[])(((Dictionary<string, object>)registryCodec["minecraft:chat_type"])["value"]);
|
||||||
foreach (var (chatName, chatId) in from Dictionary<string, object> chatTypeNbt in chatTypeListNbt
|
foreach (Dictionary<string, object> chatTypeNbt in chatTypeListNbt)
|
||||||
let chatName = (string)chatTypeNbt["name"]
|
|
||||||
let chatId = (int)chatTypeNbt["id"]
|
|
||||||
select (chatName, chatId))
|
|
||||||
{
|
{
|
||||||
chatTypeDictionary[chatId] = chatName switch
|
string chatName = (string)chatTypeNbt["name"];
|
||||||
|
int chatId = (int)chatTypeNbt["id"];
|
||||||
|
var chatTypeData = chatTypeNbt.TryGetValue("element", out var element)
|
||||||
|
? element as Dictionary<string, object>
|
||||||
|
: null;
|
||||||
|
ReadChatType(chatId, chatName, chatTypeData);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static int ReadChatTypeHolder(
|
||||||
|
DataTypes dataTypes,
|
||||||
|
Queue<byte> packetData,
|
||||||
|
int protocolVersion,
|
||||||
|
out ChatTypeDecoration? directDecoration)
|
||||||
|
{
|
||||||
|
int encodedId = dataTypes.ReadNextVarInt(packetData);
|
||||||
|
directDecoration = null;
|
||||||
|
|
||||||
|
if (protocolVersion < Protocol18Handler.MC_1_21_Version)
|
||||||
|
return encodedId;
|
||||||
|
|
||||||
|
if (encodedId > 0)
|
||||||
|
return encodedId - 1;
|
||||||
|
|
||||||
|
directDecoration = ReadNetworkChatTypeDecoration(dataTypes, packetData);
|
||||||
|
_ = ReadNetworkChatTypeDecoration(dataTypes, packetData); // Narration decoration
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ChatTypeDecoration ReadNetworkChatTypeDecoration(
|
||||||
|
DataTypes dataTypes,
|
||||||
|
Queue<byte> packetData)
|
||||||
|
{
|
||||||
|
string translationKey = dataTypes.ReadNextString(packetData);
|
||||||
|
int parameterCount = dataTypes.ReadNextVarInt(packetData);
|
||||||
|
var parameters = new ChatTypeParameter[parameterCount];
|
||||||
|
|
||||||
|
for (int i = 0; i < parameterCount; i++)
|
||||||
|
parameters[i] = (ChatTypeParameter)dataTypes.ReadNextVarInt(packetData);
|
||||||
|
|
||||||
|
_ = dataTypes.ReadNextNbtTag(packetData); // Style
|
||||||
|
return new ChatTypeDecoration(translationKey, parameters);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryReadChatTypeDecoration(
|
||||||
|
Dictionary<string, object>? chatTypeData,
|
||||||
|
[NotNullWhen(true)] out ChatTypeDecoration? decoration)
|
||||||
|
{
|
||||||
|
decoration = null;
|
||||||
|
if (chatTypeData is null
|
||||||
|
|| !chatTypeData.TryGetValue("chat", out var chat)
|
||||||
|
|| chat is not Dictionary<string, object> chatDecoration
|
||||||
|
|| !chatDecoration.TryGetValue("translation_key", out var translationKey)
|
||||||
|
|| translationKey is not string translationKeyText
|
||||||
|
|| !chatDecoration.TryGetValue("parameters", out var parameters)
|
||||||
|
|| parameters is not object[] parameterList)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
var parsedParameters = new ChatTypeParameter[parameterList.Length];
|
||||||
|
for (int i = 0; i < parameterList.Length; i++)
|
||||||
|
{
|
||||||
|
parsedParameters[i] = parameterList[i] switch
|
||||||
{
|
{
|
||||||
"minecraft:chat" => MessageType.CHAT,
|
"sender" => ChatTypeParameter.Sender,
|
||||||
"minecraft:emote_command" => MessageType.EMOTE_COMMAND,
|
"target" => ChatTypeParameter.Target,
|
||||||
"minecraft:msg_command_incoming" => MessageType.MSG_COMMAND_INCOMING,
|
"content" => ChatTypeParameter.Content,
|
||||||
"minecraft:msg_command_outgoing" => MessageType.MSG_COMMAND_OUTGOING,
|
_ => ChatTypeParameter.Sender
|
||||||
"minecraft:say_command" => MessageType.SAY_COMMAND,
|
|
||||||
"minecraft:team_msg_command_incoming" => MessageType.TEAM_MSG_COMMAND_INCOMING,
|
|
||||||
"minecraft:team_msg_command_outgoing" => MessageType.TEAM_MSG_COMMAND_OUTGOING,
|
|
||||||
_ => MessageType.CHAT,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
ChatId2Type = chatTypeDictionary;
|
decoration = new ChatTypeDecoration(translationKeyText, parsedParameters);
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|
@ -147,6 +219,26 @@ namespace MinecraftClient.Protocol.Message
|
||||||
string text;
|
string text;
|
||||||
List<string> usingData = new();
|
List<string> usingData = new();
|
||||||
|
|
||||||
|
ChatTypeDecoration? decoration = message.chatTypeDecoration;
|
||||||
|
if (decoration is null)
|
||||||
|
ChatId2Decoration.TryGetValue(message.chatTypeId, out decoration);
|
||||||
|
|
||||||
|
if (decoration is not null)
|
||||||
|
{
|
||||||
|
foreach (var parameter in decoration.Parameters)
|
||||||
|
{
|
||||||
|
usingData.Add(parameter switch
|
||||||
|
{
|
||||||
|
ChatTypeParameter.Sender => sender,
|
||||||
|
ChatTypeParameter.Target => message.teamName ?? string.Empty,
|
||||||
|
ChatTypeParameter.Content => content,
|
||||||
|
_ => string.Empty
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return TranslateString(decoration.TranslationKey, usingData);
|
||||||
|
}
|
||||||
|
|
||||||
MessageType chatType;
|
MessageType chatType;
|
||||||
if (message.chatTypeId == -1)
|
if (message.chatTypeId == -1)
|
||||||
chatType = MessageType.RAW_MSG;
|
chatType = MessageType.RAW_MSG;
|
||||||
|
|
@ -557,48 +649,47 @@ namespace MinecraftClient.Protocol.Message
|
||||||
RulesInitialized = true;
|
RulesInitialized = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (TryGetTranslationRule(rulename, out string? rule))
|
if (!TryGetTranslationRule(rulename, out string? rule))
|
||||||
{
|
rule = rulename;
|
||||||
int using_idx = 0;
|
|
||||||
StringBuilder result = new();
|
|
||||||
for (int i = 0; i < rule.Length; i++)
|
|
||||||
{
|
|
||||||
if (rule[i] == '%' && i + 1 < rule.Length)
|
|
||||||
{
|
|
||||||
//Using string or int with %s or %d
|
|
||||||
if (rule[i + 1] == 's' || rule[i + 1] == 'd')
|
|
||||||
{
|
|
||||||
if (using_data.Count > using_idx)
|
|
||||||
{
|
|
||||||
result.Append(using_data[using_idx]);
|
|
||||||
using_idx++;
|
|
||||||
i += 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//Using specified string or int with %1$s, %2$s...
|
int using_idx = 0;
|
||||||
else if (char.IsDigit(rule[i + 1])
|
StringBuilder result = new();
|
||||||
&& i + 3 < rule.Length && rule[i + 2] == '$'
|
for (int i = 0; i < rule.Length; i++)
|
||||||
&& (rule[i + 3] == 's' || rule[i + 3] == 'd'))
|
{
|
||||||
|
if (rule[i] == '%' && i + 1 < rule.Length)
|
||||||
|
{
|
||||||
|
//Using string or int with %s or %d
|
||||||
|
if (rule[i + 1] == 's' || rule[i + 1] == 'd')
|
||||||
|
{
|
||||||
|
if (using_data.Count > using_idx)
|
||||||
{
|
{
|
||||||
int specified_idx = rule[i + 1] - '1';
|
result.Append(using_data[using_idx]);
|
||||||
if (using_data.Count > specified_idx)
|
using_idx++;
|
||||||
{
|
i += 1;
|
||||||
result.Append(using_data[specified_idx]);
|
continue;
|
||||||
using_idx++;
|
|
||||||
i += 3;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
result.Append(rule[i]);
|
//Using specified string or int with %1$s, %2$s...
|
||||||
|
else if (char.IsDigit(rule[i + 1])
|
||||||
|
&& i + 3 < rule.Length && rule[i + 2] == '$'
|
||||||
|
&& (rule[i + 3] == 's' || rule[i + 3] == 'd'))
|
||||||
|
{
|
||||||
|
int specified_idx = rule[i + 1] - '1';
|
||||||
|
if (using_data.Count > specified_idx)
|
||||||
|
{
|
||||||
|
result.Append(using_data[specified_idx]);
|
||||||
|
using_idx++;
|
||||||
|
i += 3;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return result.ToString();
|
result.Append(rule[i]);
|
||||||
}
|
}
|
||||||
else return "[" + rulename + "] " + string.Join(" ", using_data);
|
|
||||||
|
return result.ToString();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static bool TryGetTranslationRule(string rulename, [NotNullWhen(true)] out string? result)
|
private static bool TryGetTranslationRule(string rulename, [NotNullWhen(true)] out string? result)
|
||||||
|
|
|
||||||
|
|
@ -153,7 +153,7 @@ namespace MinecraftClient.Protocol
|
||||||
// Extract email from JWT id_token
|
// Extract email from JWT id_token
|
||||||
string payload = JwtPayloadDecode.GetPayload(jsonData["id_token"]!.GetStringValue());
|
string payload = JwtPayloadDecode.GetPayload(jsonData["id_token"]!.GetStringValue());
|
||||||
var jsonPayload = Json.ParseJson(payload);
|
var jsonPayload = Json.ParseJson(payload);
|
||||||
string email = jsonPayload!["email"]!.GetStringValue();
|
string email = jsonPayload?["email"]?.GetStringValue() ?? string.Empty;
|
||||||
|
|
||||||
return new LoginResponse()
|
return new LoginResponse()
|
||||||
{
|
{
|
||||||
|
|
@ -195,7 +195,7 @@ namespace MinecraftClient.Protocol
|
||||||
// Extract email from JWT
|
// Extract email from JWT
|
||||||
string payload = JwtPayloadDecode.GetPayload(jsonData["id_token"]!.GetStringValue());
|
string payload = JwtPayloadDecode.GetPayload(jsonData["id_token"]!.GetStringValue());
|
||||||
var jsonPayload = Json.ParseJson(payload);
|
var jsonPayload = Json.ParseJson(payload);
|
||||||
string email = jsonPayload!["email"]!.GetStringValue();
|
string email = jsonPayload?["email"]?.GetStringValue() ?? string.Empty;
|
||||||
return new LoginResponse()
|
return new LoginResponse()
|
||||||
{
|
{
|
||||||
Email = email,
|
Email = email,
|
||||||
|
|
|
||||||
|
|
@ -26,9 +26,10 @@ namespace MinecraftClient.Protocol.ProfileKey
|
||||||
ProxiedWebRequest.Response? response = null;
|
ProxiedWebRequest.Response? response = null;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var authServer = Settings.Config.Main.General.AuthServer;
|
if (!Settings.Config.Main.General.TryGetAuthServerUri(out Uri? authServerUri))
|
||||||
var request = new ProxiedWebRequest(
|
return false;
|
||||||
(authServer.UseHttps ? "https" : "http") + "://" + authServer.Host + ":" + authServer.Port + authServer.AuthlibInjectorAPIPath)
|
|
||||||
|
var request = new ProxiedWebRequest(authServerUri.AbsoluteUri)
|
||||||
{
|
{
|
||||||
Accept = "application/json"
|
Accept = "application/json"
|
||||||
};
|
};
|
||||||
|
|
@ -66,9 +67,10 @@ namespace MinecraftClient.Protocol.ProfileKey
|
||||||
string certificatesURL = "https://api.minecraftservices.com/player/certificates";
|
string certificatesURL = "https://api.minecraftservices.com/player/certificates";
|
||||||
if (isYggdrasil)
|
if (isYggdrasil)
|
||||||
{
|
{
|
||||||
var authServer = Settings.Config.Main.General.AuthServer;
|
if (!Settings.Config.Main.General.TryGetAuthServerUri(out Uri? authServerUri))
|
||||||
certificatesURL = (authServer.UseHttps ? "https" : "http") + "://" + authServer.Host + ":" + authServer.Port +
|
return null;
|
||||||
authServer.AuthlibInjectorAPIPath + "/minecraftservices/player/certificates";
|
|
||||||
|
certificatesURL = new Uri(authServerUri, "minecraftservices/player/certificates").AbsoluteUri;
|
||||||
}
|
}
|
||||||
|
|
||||||
ProxiedWebRequest.Response? response = null;
|
ProxiedWebRequest.Response? response = null;
|
||||||
|
|
|
||||||
|
|
@ -27,6 +27,13 @@ namespace MinecraftClient.Protocol
|
||||||
/// </remarks>
|
/// </remarks>
|
||||||
public static class ProtocolHandler
|
public static class ProtocolHandler
|
||||||
{
|
{
|
||||||
|
public enum AuthlibServerValidationResult
|
||||||
|
{
|
||||||
|
Valid,
|
||||||
|
Unreachable,
|
||||||
|
InvalidResponse
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Perform a DNS lookup for a Minecraft Service using the specified domain name
|
/// Perform a DNS lookup for a Minecraft Service using the specified domain name
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|
@ -134,6 +141,37 @@ namespace MinecraftClient.Protocol
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies that an authlib-injector URL is reachable and returns its metadata document.
|
||||||
|
/// </summary>
|
||||||
|
public static AuthlibServerValidationResult ValidateAuthlibServer(Uri authServerUri)
|
||||||
|
{
|
||||||
|
string result = string.Empty;
|
||||||
|
int statusCode;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
statusCode = DoHTTPSGet(authServerUri, ref result);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return AuthlibServerValidationResult.Unreachable;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (statusCode != 200)
|
||||||
|
return AuthlibServerValidationResult.InvalidResponse;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return Json.ParseJson(result)?["meta"]?["implementationName"]?.GetStringValue() is { Length: > 0 }
|
||||||
|
? AuthlibServerValidationResult.Valid
|
||||||
|
: AuthlibServerValidationResult.InvalidResponse;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return AuthlibServerValidationResult.InvalidResponse;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Get a protocol handler for the specified Minecraft version
|
/// Get a protocol handler for the specified Minecraft version
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|
@ -714,9 +752,10 @@ namespace MinecraftClient.Protocol
|
||||||
string json_request = "{\"agent\": { \"name\": \"Minecraft\", \"version\": 1 }, \"username\": \"" +
|
string json_request = "{\"agent\": { \"name\": \"Minecraft\", \"version\": 1 }, \"username\": \"" +
|
||||||
JsonEncode(user) + "\", \"password\": \"" + JsonEncode(pass) +
|
JsonEncode(user) + "\", \"password\": \"" + JsonEncode(pass) +
|
||||||
"\", \"clientToken\": \"" + JsonEncode(session.ClientID) + "\" }";
|
"\", \"clientToken\": \"" + JsonEncode(session.ClientID) + "\" }";
|
||||||
int code = DoHTTPSPost(Config.Main.General.AuthServer.Host, Config.Main.General.AuthServer.Port,
|
if (!Config.Main.General.TryGetAuthServerUri(out Uri? authServerUri))
|
||||||
Config.Main.General.AuthServer.AuthlibInjectorAPIPath + "/authserver/authenticate", json_request,
|
return LoginResult.OtherError;
|
||||||
Config.Main.General.AuthServer.UseHttps, ref result);
|
|
||||||
|
int code = DoHTTPSPost(authServerUri, "authserver/authenticate", json_request, ref result);
|
||||||
if (code == 200)
|
if (code == 200)
|
||||||
{
|
{
|
||||||
if (result.Contains("availableProfiles\":[]}"))
|
if (result.Contains("availableProfiles\":[]}"))
|
||||||
|
|
@ -922,7 +961,8 @@ namespace MinecraftClient.Protocol
|
||||||
session.PlayerID = profile.UUID;
|
session.PlayerID = profile.UUID;
|
||||||
session.ID = accessToken;
|
session.ID = accessToken;
|
||||||
session.RefreshToken = msaResponse.RefreshToken;
|
session.RefreshToken = msaResponse.RefreshToken;
|
||||||
InternalConfig.Account.Login = msaResponse.Email;
|
if (!string.IsNullOrWhiteSpace(msaResponse.Email))
|
||||||
|
InternalConfig.Account.Login = msaResponse.Email;
|
||||||
return LoginResult.Success;
|
return LoginResult.Success;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
|
|
@ -1037,9 +1077,10 @@ namespace MinecraftClient.Protocol
|
||||||
"\", \"clientToken\": \"" + JsonEncode(currentsession.ClientID) +
|
"\", \"clientToken\": \"" + JsonEncode(currentsession.ClientID) +
|
||||||
"\", \"selectedProfile\": { \"id\": \"" + JsonEncode(currentsession.PlayerID) +
|
"\", \"selectedProfile\": { \"id\": \"" + JsonEncode(currentsession.PlayerID) +
|
||||||
"\", \"name\": \"" + JsonEncode(currentsession.PlayerName) + "\" } }";
|
"\", \"name\": \"" + JsonEncode(currentsession.PlayerName) + "\" } }";
|
||||||
int code = DoHTTPSPost(Config.Main.General.AuthServer.Host, Config.Main.General.AuthServer.Port,
|
if (!Config.Main.General.TryGetAuthServerUri(out Uri? authServerUri))
|
||||||
Config.Main.General.AuthServer.AuthlibInjectorAPIPath + "/authserver/refresh", json_request,
|
return LoginResult.OtherError;
|
||||||
Config.Main.General.AuthServer.UseHttps, ref result);
|
|
||||||
|
int code = DoHTTPSPost(authServerUri, "authserver/refresh", json_request, ref result);
|
||||||
if (code == 200)
|
if (code == 200)
|
||||||
{
|
{
|
||||||
if (result is null)
|
if (result is null)
|
||||||
|
|
@ -1093,16 +1134,18 @@ namespace MinecraftClient.Protocol
|
||||||
string result = "";
|
string result = "";
|
||||||
string json_request = "{\"accessToken\":\"" + accesstoken + "\",\"selectedProfile\":\"" + uuid +
|
string json_request = "{\"accessToken\":\"" + accesstoken + "\",\"selectedProfile\":\"" + uuid +
|
||||||
"\",\"serverId\":\"" + serverhash + "\"}";
|
"\",\"serverId\":\"" + serverhash + "\"}";
|
||||||
string host = type == LoginType.yggdrasil
|
int code;
|
||||||
? Config.Main.General.AuthServer.Host
|
if (type == LoginType.yggdrasil)
|
||||||
: "sessionserver.mojang.com";
|
{
|
||||||
int port = type == LoginType.yggdrasil ? Config.Main.General.AuthServer.Port : 443;
|
if (!Config.Main.General.TryGetAuthServerUri(out Uri? authServerUri))
|
||||||
string endpoint = type == LoginType.yggdrasil
|
return false;
|
||||||
? Config.Main.General.AuthServer.AuthlibInjectorAPIPath + "/sessionserver/session/minecraft/join"
|
|
||||||
: "/session/minecraft/join";
|
|
||||||
|
|
||||||
bool useHttps = type == LoginType.yggdrasil ? Config.Main.General.AuthServer.UseHttps : true;
|
code = DoHTTPSPost(authServerUri, "sessionserver/session/minecraft/join", json_request, ref result);
|
||||||
int code = DoHTTPSPost(host, port, endpoint, json_request, useHttps, ref result);
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
code = DoHTTPSPost("sessionserver.mojang.com", 443, "/session/minecraft/join", json_request, ref result);
|
||||||
|
}
|
||||||
return (code >= 200 && code < 300);
|
return (code >= 200 && code < 300);
|
||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
|
|
@ -1241,6 +1284,16 @@ namespace MinecraftClient.Protocol
|
||||||
return DoHTTPSRequest(HttpMethod.Get, host, port, path, headers, null, useHttps: true, ref result);
|
return DoHTTPSRequest(HttpMethod.Get, host, port, path, headers, null, useHttps: true, ref result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static int DoHTTPSGet(Uri requestUri, ref string result)
|
||||||
|
{
|
||||||
|
Dictionary<string, string> headers = new()
|
||||||
|
{
|
||||||
|
{ "User-Agent", "MCC/" + Program.Version }
|
||||||
|
};
|
||||||
|
return DoHTTPSRequest(HttpMethod.Get, requestUri.Host, requestUri.Port, requestUri.PathAndQuery, headers,
|
||||||
|
null, requestUri.Scheme == Uri.UriSchemeHttps, ref result);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Make a POST request to the specified endpoint of the Mojang API
|
/// Make a POST request to the specified endpoint of the Mojang API
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|
@ -1253,6 +1306,13 @@ namespace MinecraftClient.Protocol
|
||||||
private static int DoHTTPSPost(string host, int port, string path, string body, ref string result)
|
private static int DoHTTPSPost(string host, int port, string path, string body, ref string result)
|
||||||
=> DoHTTPSPost(host, port, path, body, useHttps: true, ref result);
|
=> DoHTTPSPost(host, port, path, body, useHttps: true, ref result);
|
||||||
|
|
||||||
|
private static int DoHTTPSPost(Uri baseUri, string relativePath, string body, ref string result)
|
||||||
|
{
|
||||||
|
Uri requestUri = new(baseUri, relativePath);
|
||||||
|
return DoHTTPSPost(requestUri.Host, requestUri.Port, requestUri.PathAndQuery, body,
|
||||||
|
requestUri.Scheme == Uri.UriSchemeHttps, ref result);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Make a POST request to the specified endpoint of the Mojang API
|
/// Make a POST request to the specified endpoint of the Mojang API
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|
@ -1392,4 +1452,4 @@ namespace MinecraftClient.Protocol
|
||||||
return dateTime;
|
return dateTime;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2011,6 +2011,15 @@ namespace MinecraftClient {
|
||||||
return ResourceManager.GetString("Main.General.AuthlibServer", resourceCulture);
|
return ResourceManager.GetString("Main.General.AuthlibServer", resourceCulture);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Looks up a localized string similar to Authlib-injector URL to use for Yggdrasil accounts. It must use http or https and include any required path..
|
||||||
|
/// </summary>
|
||||||
|
internal static string Main_General_AuthServerUrl {
|
||||||
|
get {
|
||||||
|
return ResourceManager.GetString("Main.General.AuthServerUrl", resourceCulture);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Looks up a localized string similar to Yggdrasil authlib multi-user selection..
|
/// Looks up a localized string similar to Yggdrasil authlib multi-user selection..
|
||||||
|
|
|
||||||
|
|
@ -983,6 +983,9 @@ Note: This does NOT require a Bot Token, only an Application ID. Discord must be
|
||||||
<data name="Main.General.AuthlibServer" xml:space="preserve">
|
<data name="Main.General.AuthlibServer" xml:space="preserve">
|
||||||
<value>authlib-injector authentication server to use for Yggdrasil accounts</value>
|
<value>authlib-injector authentication server to use for Yggdrasil accounts</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="Main.General.AuthServerUrl" xml:space="preserve">
|
||||||
|
<value>Authlib-injector URL to use for Yggdrasil accounts. It must use http or https and include any required path.</value>
|
||||||
|
</data>
|
||||||
<data name="AuthlibServer.Host" xml:space="preserve">
|
<data name="AuthlibServer.Host" xml:space="preserve">
|
||||||
<value>Domain name or IP address</value>
|
<value>Domain name or IP address</value>
|
||||||
</data>
|
</data>
|
||||||
|
|
|
||||||
|
|
@ -5998,6 +5998,24 @@ namespace MinecraftClient {
|
||||||
return ResourceManager.GetString("mcc.connecting", resourceCulture);
|
return ResourceManager.GetString("mcc.connecting", resourceCulture);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Looks up a localized string similar to Select a login method: [1] Offline, [2] Online (Microsoft), [3] Yggdrasil.
|
||||||
|
/// </summary>
|
||||||
|
internal static string mcc_auth_method_prompt {
|
||||||
|
get {
|
||||||
|
return ResourceManager.GetString("mcc.auth_method_prompt", resourceCulture);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Looks up a localized string similar to Please choose 1, 2, or 3..
|
||||||
|
/// </summary>
|
||||||
|
internal static string mcc_auth_method_invalid {
|
||||||
|
get {
|
||||||
|
return ResourceManager.GetString("mcc.auth_method_invalid", resourceCulture);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Looks up a localized string similar to Tip: try TUI mode for a cleaner interface, mouse-friendly container actions, and a nicer layout. Run {0}feature tui§8 to switch [Console.General] ConsoleMode to "tui" for the next restart..
|
/// Looks up a localized string similar to Tip: try TUI mode for a cleaner interface, mouse-friendly container actions, and a nicer layout. Run {0}feature tui§8 to switch [Console.General] ConsoleMode to "tui" for the next restart..
|
||||||
|
|
@ -6271,6 +6289,114 @@ namespace MinecraftClient {
|
||||||
return ResourceManager.GetString("mcc.password_hidden", resourceCulture);
|
return ResourceManager.GetString("mcc.password_hidden", resourceCulture);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Looks up a localized string similar to Authlib server host:.
|
||||||
|
/// </summary>
|
||||||
|
internal static string mcc_yggdrasil_host {
|
||||||
|
get {
|
||||||
|
return ResourceManager.GetString("mcc.yggdrasil_host", resourceCulture);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Looks up a localized string similar to Authlib server port [{0}]:.
|
||||||
|
/// </summary>
|
||||||
|
internal static string mcc_yggdrasil_port {
|
||||||
|
get {
|
||||||
|
return ResourceManager.GetString("mcc.yggdrasil_port", resourceCulture);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Looks up a localized string similar to Authlib-Injector API path [{0}]:.
|
||||||
|
/// </summary>
|
||||||
|
internal static string mcc_yggdrasil_api_path {
|
||||||
|
get {
|
||||||
|
return ResourceManager.GetString("mcc.yggdrasil_api_path", resourceCulture);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Looks up a localized string similar to Use HTTPS? [Y/n].
|
||||||
|
/// </summary>
|
||||||
|
internal static string mcc_yggdrasil_use_https {
|
||||||
|
get {
|
||||||
|
return ResourceManager.GetString("mcc.yggdrasil_use_https", resourceCulture);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Looks up a localized string similar to The authlib server host cannot be empty..
|
||||||
|
/// </summary>
|
||||||
|
internal static string mcc_yggdrasil_invalid_host {
|
||||||
|
get {
|
||||||
|
return ResourceManager.GetString("mcc.yggdrasil_invalid_host", resourceCulture);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Looks up a localized string similar to The authlib server port must be between 1 and 65535..
|
||||||
|
/// </summary>
|
||||||
|
internal static string mcc_yggdrasil_invalid_port {
|
||||||
|
get {
|
||||||
|
return ResourceManager.GetString("mcc.yggdrasil_invalid_port", resourceCulture);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Looks up a localized string similar to Please answer yes or no..
|
||||||
|
/// </summary>
|
||||||
|
internal static string mcc_yggdrasil_invalid_yes_no {
|
||||||
|
get {
|
||||||
|
return ResourceManager.GetString("mcc.yggdrasil_invalid_yes_no", resourceCulture);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Looks up a localized string similar to Authlib-injector URL:.
|
||||||
|
/// </summary>
|
||||||
|
internal static string mcc_yggdrasil_url {
|
||||||
|
get {
|
||||||
|
return ResourceManager.GetString("mcc.yggdrasil_url", resourceCulture);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Looks up a localized string similar to The authlib-injector URL must be an absolute HTTP or HTTPS URL..
|
||||||
|
/// </summary>
|
||||||
|
internal static string mcc_yggdrasil_invalid_url {
|
||||||
|
get {
|
||||||
|
return ResourceManager.GetString("mcc.yggdrasil_invalid_url", resourceCulture);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Looks up a localized string similar to Could not reach the authlib-injector server. Check the URL and try again..
|
||||||
|
/// </summary>
|
||||||
|
internal static string mcc_yggdrasil_server_unreachable {
|
||||||
|
get {
|
||||||
|
return ResourceManager.GetString("mcc.yggdrasil_server_unreachable", resourceCulture);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Looks up a localized string similar to The server did not return valid authlib-injector metadata. Check the URL and try again..
|
||||||
|
/// </summary>
|
||||||
|
internal static string mcc_yggdrasil_server_invalid {
|
||||||
|
get {
|
||||||
|
return ResourceManager.GetString("mcc.yggdrasil_server_invalid", resourceCulture);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Looks up a localized string similar to The configured authlib-injector URL must be an absolute HTTP or HTTPS URL..
|
||||||
|
/// </summary>
|
||||||
|
internal static string config_auth_server_url_invalid {
|
||||||
|
get {
|
||||||
|
return ResourceManager.GetString("config.auth_server_url_invalid", resourceCulture);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Looks up a localized string similar to You are dead. Type '{0}respawn' to respawn..
|
/// Looks up a localized string similar to You are dead. Type '{0}respawn' to respawn..
|
||||||
|
|
@ -8170,5 +8296,9 @@ namespace MinecraftClient {
|
||||||
get { return ResourceManager.GetString("dialog.render.help_hint", resourceCulture); }
|
get { return ResourceManager.GetString("dialog.render.help_hint", resourceCulture); }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal static string protocol_chat_raw_message {
|
||||||
|
get { return ResourceManager.GetString("protocol.chat.raw_message", resourceCulture); }
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2004,6 +2004,27 @@ You can use "/chunk status {0:0.0} {1:0.0} {2:0.0}" to check the chunk loading s
|
||||||
<data name="mcc.connecting" xml:space="preserve">
|
<data name="mcc.connecting" xml:space="preserve">
|
||||||
<value>Connecting to {0}...</value>
|
<value>Connecting to {0}...</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="mcc.auth_method_prompt" xml:space="preserve">
|
||||||
|
<value>Select a login method: [1] Offline, [2] Online (Microsoft), [3] Yggdrasil</value>
|
||||||
|
</data>
|
||||||
|
<data name="mcc.auth_method_invalid" xml:space="preserve">
|
||||||
|
<value>Please choose 1, 2, or 3.</value>
|
||||||
|
</data>
|
||||||
|
<data name="mcc.yggdrasil_url" xml:space="preserve">
|
||||||
|
<value>Authlib-injector URL:</value>
|
||||||
|
</data>
|
||||||
|
<data name="mcc.yggdrasil_invalid_url" xml:space="preserve">
|
||||||
|
<value>The authlib-injector URL must be an absolute HTTP or HTTPS URL.</value>
|
||||||
|
</data>
|
||||||
|
<data name="mcc.yggdrasil_server_unreachable" xml:space="preserve">
|
||||||
|
<value>Could not reach the authlib-injector server. Check the URL and try again.</value>
|
||||||
|
</data>
|
||||||
|
<data name="mcc.yggdrasil_server_invalid" xml:space="preserve">
|
||||||
|
<value>The server did not return valid authlib-injector metadata. Check the URL and try again.</value>
|
||||||
|
</data>
|
||||||
|
<data name="config.auth_server_url_invalid" xml:space="preserve">
|
||||||
|
<value>The configured authlib-injector URL must be an absolute HTTP or HTTPS URL.</value>
|
||||||
|
</data>
|
||||||
<data name="mcc.console_mode_tui_recommendation" xml:space="preserve">
|
<data name="mcc.console_mode_tui_recommendation" xml:space="preserve">
|
||||||
<value>Tip: try TUI mode for a cleaner interface, mouse-friendly inventory actions, and a nicer layout. Run {0}tryout tui§8 to switch [Console.General] ConsoleMode to "tui" for the next restart.</value>
|
<value>Tip: try TUI mode for a cleaner interface, mouse-friendly inventory actions, and a nicer layout. Run {0}tryout tui§8 to switch [Console.General] ConsoleMode to "tui" for the next restart.</value>
|
||||||
</data>
|
</data>
|
||||||
|
|
@ -2097,6 +2118,27 @@ Type '{0}quit' to leave the server.</value>
|
||||||
<data name="mcc.password_hidden" xml:space="preserve">
|
<data name="mcc.password_hidden" xml:space="preserve">
|
||||||
<value>Password(invisible): </value>
|
<value>Password(invisible): </value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="mcc.yggdrasil_host" xml:space="preserve">
|
||||||
|
<value>Authlib server host:</value>
|
||||||
|
</data>
|
||||||
|
<data name="mcc.yggdrasil_port" xml:space="preserve">
|
||||||
|
<value>Authlib server port [{0}]:</value>
|
||||||
|
</data>
|
||||||
|
<data name="mcc.yggdrasil_api_path" xml:space="preserve">
|
||||||
|
<value>Authlib-Injector API path [{0}]:</value>
|
||||||
|
</data>
|
||||||
|
<data name="mcc.yggdrasil_use_https" xml:space="preserve">
|
||||||
|
<value>Use HTTPS? [Y/n]</value>
|
||||||
|
</data>
|
||||||
|
<data name="mcc.yggdrasil_invalid_host" xml:space="preserve">
|
||||||
|
<value>The authlib server host cannot be empty.</value>
|
||||||
|
</data>
|
||||||
|
<data name="mcc.yggdrasil_invalid_port" xml:space="preserve">
|
||||||
|
<value>The authlib server port must be between 1 and 65535.</value>
|
||||||
|
</data>
|
||||||
|
<data name="mcc.yggdrasil_invalid_yes_no" xml:space="preserve">
|
||||||
|
<value>Please answer yes or no.</value>
|
||||||
|
</data>
|
||||||
<data name="mcc.player_dead" xml:space="preserve">
|
<data name="mcc.player_dead" xml:space="preserve">
|
||||||
<value>You are dead. Type '{0}respawn' to respawn.</value>
|
<value>You are dead. Type '{0}respawn' to respawn.</value>
|
||||||
</data>
|
</data>
|
||||||
|
|
@ -3085,4 +3127,7 @@ see item details.</value>
|
||||||
<data name="dialog.render.help_hint" xml:space="preserve">
|
<data name="dialog.render.help_hint" xml:space="preserve">
|
||||||
<value>Use /dialog help for a list of commands.</value>
|
<value>Use /dialog help for a list of commands.</value>
|
||||||
</data>
|
</data>
|
||||||
|
<data name="protocol.chat.raw_message" xml:space="preserve">
|
||||||
|
<value>Raw server chat message: {0}</value>
|
||||||
|
</data>
|
||||||
</root>
|
</root>
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,27 @@ namespace MinecraftClient
|
||||||
internal readonly record struct RestartRequest(
|
internal readonly record struct RestartRequest(
|
||||||
long ConnectionAttempt,
|
long ConnectionAttempt,
|
||||||
TimeSpan Delay,
|
TimeSpan Delay,
|
||||||
bool KeepAccountAndServerSettings);
|
bool KeepAccountAndServerSettings,
|
||||||
|
RestartSettingsSnapshot? SettingsSnapshot = null,
|
||||||
|
bool ReplaceUntilCommit = false,
|
||||||
|
Task? SourceCleanupCompletion = null,
|
||||||
|
long RequestId = 0);
|
||||||
|
|
||||||
|
internal readonly record struct RestartSettingsSnapshot(
|
||||||
|
Settings.MainConfigHelper.MainConfig.AccountInfoConfig Account,
|
||||||
|
string ServerIP,
|
||||||
|
ushort ServerPort);
|
||||||
|
|
||||||
|
internal enum RestartRequestState
|
||||||
|
{
|
||||||
|
Replaceable,
|
||||||
|
Committing,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal readonly record struct PendingRestart(
|
||||||
|
long RequestId,
|
||||||
|
RestartRequest Request,
|
||||||
|
RestartRequestState State);
|
||||||
|
|
||||||
internal sealed class RestartCoordinator : IDisposable
|
internal sealed class RestartCoordinator : IDisposable
|
||||||
{
|
{
|
||||||
|
|
@ -19,8 +39,9 @@ namespace MinecraftClient
|
||||||
private readonly Func<RestartRequest, CancellationToken, Task> restart;
|
private readonly Func<RestartRequest, CancellationToken, Task> restart;
|
||||||
private readonly Action<Exception> reportFailure;
|
private readonly Action<Exception> reportFailure;
|
||||||
private readonly Task worker;
|
private readonly Task worker;
|
||||||
private readonly HashSet<long> pendingAttempts = [];
|
private readonly Dictionary<long, PendingRestart> pendingAttempts = [];
|
||||||
private long highestScheduledAttempt = -1;
|
private long highestScheduledAttempt = -1;
|
||||||
|
private long nextRequestId;
|
||||||
private bool stopped;
|
private bool stopped;
|
||||||
|
|
||||||
internal RestartCoordinator(
|
internal RestartCoordinator(
|
||||||
|
|
@ -44,26 +65,85 @@ namespace MinecraftClient
|
||||||
internal bool HasScheduledRestart(long connectionAttempt)
|
internal bool HasScheduledRestart(long connectionAttempt)
|
||||||
{
|
{
|
||||||
lock (stateLock)
|
lock (stateLock)
|
||||||
return !stopped && pendingAttempts.Contains(connectionAttempt);
|
return !stopped && pendingAttempts.ContainsKey(connectionAttempt);
|
||||||
}
|
}
|
||||||
|
|
||||||
internal bool TrySchedule(RestartRequest request)
|
internal bool TrySchedule(RestartRequest request, Func<bool>? beforePublish = null)
|
||||||
{
|
{
|
||||||
lock (stateLock)
|
lock (stateLock)
|
||||||
{
|
{
|
||||||
if (stopped || request.ConnectionAttempt <= highestScheduledAttempt)
|
if (stopped)
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
highestScheduledAttempt = request.ConnectionAttempt;
|
if (pendingAttempts.TryGetValue(request.ConnectionAttempt, out PendingRestart pendingRequest))
|
||||||
pendingAttempts.Add(request.ConnectionAttempt);
|
{
|
||||||
if (requests.Writer.TryWrite(request))
|
if (pendingRequest.State != RestartRequestState.Replaceable || !request.ReplaceUntilCommit)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
request = request with
|
||||||
|
{
|
||||||
|
RequestId = pendingRequest.RequestId,
|
||||||
|
SourceCleanupCompletion = pendingRequest.Request.SourceCleanupCompletion,
|
||||||
|
};
|
||||||
|
pendingAttempts[request.ConnectionAttempt] = pendingRequest with { Request = request };
|
||||||
return true;
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.ConnectionAttempt <= highestScheduledAttempt)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
request = request with { RequestId = ++nextRequestId };
|
||||||
|
pendingAttempts[request.ConnectionAttempt] = new PendingRestart(
|
||||||
|
request.RequestId,
|
||||||
|
request,
|
||||||
|
RestartRequestState.Replaceable);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (beforePublish is not null && !beforePublish())
|
||||||
|
{
|
||||||
|
pendingAttempts.Remove(request.ConnectionAttempt);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (requests.Writer.TryWrite(request))
|
||||||
|
{
|
||||||
|
highestScheduledAttempt = Math.Max(highestScheduledAttempt, request.ConnectionAttempt);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
pendingAttempts.Remove(request.ConnectionAttempt);
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
|
||||||
pendingAttempts.Remove(request.ConnectionAttempt);
|
pendingAttempts.Remove(request.ConnectionAttempt);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal bool TryBeginCommit(RestartRequest scheduledRequest, out RestartRequest latestRequest)
|
||||||
|
{
|
||||||
|
lock (stateLock)
|
||||||
|
{
|
||||||
|
if (stopped
|
||||||
|
|| !pendingAttempts.TryGetValue(scheduledRequest.ConnectionAttempt, out PendingRestart pendingRequest)
|
||||||
|
|| pendingRequest.RequestId != scheduledRequest.RequestId
|
||||||
|
|| pendingRequest.State != RestartRequestState.Replaceable)
|
||||||
|
{
|
||||||
|
latestRequest = default;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
latestRequest = pendingRequest.Request;
|
||||||
|
pendingAttempts[scheduledRequest.ConnectionAttempt] = pendingRequest with
|
||||||
|
{
|
||||||
|
State = RestartRequestState.Committing,
|
||||||
|
};
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
internal void Stop()
|
internal void Stop()
|
||||||
{
|
{
|
||||||
lock (stateLock)
|
lock (stateLock)
|
||||||
|
|
@ -84,8 +164,18 @@ namespace MinecraftClient
|
||||||
{
|
{
|
||||||
await foreach (RestartRequest request in requests.Reader.ReadAllAsync(shutdown.Token).ConfigureAwait(false))
|
await foreach (RestartRequest request in requests.Reader.ReadAllAsync(shutdown.Token).ConfigureAwait(false))
|
||||||
{
|
{
|
||||||
|
lock (stateLock)
|
||||||
|
{
|
||||||
|
if (!pendingAttempts.TryGetValue(request.ConnectionAttempt, out PendingRestart pendingRequest)
|
||||||
|
|| pendingRequest.RequestId != request.RequestId)
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
if (request.SourceCleanupCompletion is Task sourceCleanupCompletion)
|
||||||
|
await sourceCleanupCompletion.WaitAsync(shutdown.Token).ConfigureAwait(false);
|
||||||
|
|
||||||
await restart(request, shutdown.Token).ConfigureAwait(false);
|
await restart(request, shutdown.Token).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
catch (OperationCanceledException) when (shutdown.IsCancellationRequested)
|
catch (OperationCanceledException) when (shutdown.IsCancellationRequested)
|
||||||
|
|
@ -99,7 +189,11 @@ namespace MinecraftClient
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
lock (stateLock)
|
lock (stateLock)
|
||||||
pendingAttempts.Remove(request.ConnectionAttempt);
|
{
|
||||||
|
if (pendingAttempts.TryGetValue(request.ConnectionAttempt, out PendingRestart pendingRequest)
|
||||||
|
&& pendingRequest.RequestId == request.RequestId)
|
||||||
|
pendingAttempts.Remove(request.ConnectionAttempt);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -60,7 +60,7 @@ namespace MinecraftClient.Scripting
|
||||||
string line = lines[i];
|
string line = lines[i];
|
||||||
if (line.StartsWith("//using"))
|
if (line.StartsWith("//using"))
|
||||||
{
|
{
|
||||||
libs.Add(line.Replace("//", "").Trim());
|
libs.Add(NormalizeUsingDirective(line));
|
||||||
}
|
}
|
||||||
else if (line.StartsWith("//dll"))
|
else if (line.StartsWith("//dll"))
|
||||||
{
|
{
|
||||||
|
|
@ -125,6 +125,12 @@ namespace MinecraftClient.Scripting
|
||||||
else return null;
|
else return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal static string NormalizeUsingDirective(string line)
|
||||||
|
{
|
||||||
|
string directive = line[2..].Trim();
|
||||||
|
return directive.EndsWith(';') ? directive : $"{directive};";
|
||||||
|
}
|
||||||
|
|
||||||
private static string BuildScriptCode(string scriptName, IEnumerable<ScriptSourceLine> script, IEnumerable<ScriptSourceLine> extensions, IEnumerable<string> libs, bool hasImplicitReturn)
|
private static string BuildScriptCode(string scriptName, IEnumerable<ScriptSourceLine> script, IEnumerable<ScriptSourceLine> extensions, IEnumerable<string> libs, bool hasImplicitReturn)
|
||||||
{
|
{
|
||||||
StringBuilder codeBuilder = new();
|
StringBuilder codeBuilder = new();
|
||||||
|
|
|
||||||
|
|
@ -26,6 +26,8 @@ public sealed class MccBlockStateSnapshot
|
||||||
public required string TypeLabel { get; init; }
|
public required string TypeLabel { get; init; }
|
||||||
public required int BlockId { get; init; }
|
public required int BlockId { get; init; }
|
||||||
public required int BlockMeta { get; init; }
|
public required int BlockMeta { get; init; }
|
||||||
|
public required int StateId { get; init; }
|
||||||
|
public required IReadOnlyDictionary<string, string> Properties { get; init; }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|
@ -143,7 +145,9 @@ public static class MccGameCommon
|
||||||
Material = block.Type.ToString(),
|
Material = block.Type.ToString(),
|
||||||
TypeLabel = block.GetTypeString(),
|
TypeLabel = block.GetTypeString(),
|
||||||
BlockId = block.BlockId,
|
BlockId = block.BlockId,
|
||||||
BlockMeta = block.BlockMeta
|
BlockMeta = block.BlockMeta,
|
||||||
|
StateId = block.StateId,
|
||||||
|
Properties = block.GetStateProperties()
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -209,6 +209,7 @@ namespace MinecraftClient
|
||||||
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
|
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
|
||||||
string tomlString = TomletMain.TomlStringFrom(Config);
|
string tomlString = TomletMain.TomlStringFrom(Config);
|
||||||
Thread.CurrentThread.CurrentCulture = Program.ActualCulture;
|
Thread.CurrentThread.CurrentCulture = Program.ActualCulture;
|
||||||
|
tomlString = RemoveLegacyAuthServerSection(tomlString);
|
||||||
|
|
||||||
string[] tomlList = tomlString.Split('\n');
|
string[] tomlList = tomlString.Split('\n');
|
||||||
StringBuilder newConfig = new();
|
StringBuilder newConfig = new();
|
||||||
|
|
@ -272,6 +273,19 @@ namespace MinecraftClient
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static string RemoveLegacyAuthServerSection(string tomlString)
|
||||||
|
{
|
||||||
|
const string legacySection = "[Main.General.AuthServer]";
|
||||||
|
int sectionStart = tomlString.IndexOf(legacySection, StringComparison.Ordinal);
|
||||||
|
if (sectionStart < 0)
|
||||||
|
return tomlString;
|
||||||
|
|
||||||
|
int nextSection = tomlString.IndexOf("\n[", sectionStart + legacySection.Length, StringComparison.Ordinal);
|
||||||
|
return nextSection < 0
|
||||||
|
? tomlString[..sectionStart]
|
||||||
|
: tomlString.Remove(sectionStart, nextSection - sectionStart + 1);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Load settings from the command line
|
/// Load settings from the command line
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|
@ -656,6 +670,8 @@ namespace MinecraftClient
|
||||||
|
|
||||||
General.Account.Login ??= string.Empty;
|
General.Account.Login ??= string.Empty;
|
||||||
General.Account.Password ??= string.Empty;
|
General.Account.Password ??= string.Empty;
|
||||||
|
if (!General.MigrateLegacyAuthServer())
|
||||||
|
ConsoleIO.WriteLogLine(Translations.config_auth_server_url_invalid);
|
||||||
if (!InternalConfig.KeepAccountSettings)
|
if (!InternalConfig.KeepAccountSettings)
|
||||||
{
|
{
|
||||||
if (Advanced.AccountList.TryGetValue(General.Account.Login, out AccountInfoConfig account))
|
if (Advanced.AccountList.TryGetValue(General.Account.Login, out AccountInfoConfig account))
|
||||||
|
|
@ -753,12 +769,72 @@ namespace MinecraftClient
|
||||||
|
|
||||||
[TomlInlineComment("$Main.General.method$")]
|
[TomlInlineComment("$Main.General.method$")]
|
||||||
public LoginMethod Method = LoginMethod.mcc;
|
public LoginMethod Method = LoginMethod.mcc;
|
||||||
|
|
||||||
|
[TomlInlineComment("$Main.General.AuthServerUrl$")]
|
||||||
|
public string AuthServerUrl = string.Empty;
|
||||||
|
|
||||||
|
// Retained only to deserialize pre-URL configs. WriteToFile() removes this legacy section.
|
||||||
[TomlInlineComment("$Main.General.AuthlibServer$")]
|
[TomlInlineComment("$Main.General.AuthlibServer$")]
|
||||||
public AuthlibServer AuthServer = new();
|
public AuthlibServer AuthServer = new();
|
||||||
|
|
||||||
[TomlInlineComment("$Main.General.AuthlibUser$")]
|
[TomlInlineComment("$Main.General.AuthlibUser$")]
|
||||||
public string AuthUser = "";
|
public string AuthUser = "";
|
||||||
|
|
||||||
|
public bool MigrateLegacyAuthServer()
|
||||||
|
{
|
||||||
|
AuthServerUrl ??= string.Empty;
|
||||||
|
if (TrySetAuthServerUrl(AuthServerUrl))
|
||||||
|
return true;
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(AuthServerUrl))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(AuthServer.Host))
|
||||||
|
{
|
||||||
|
string path = AuthServer.AuthlibInjectorAPIPath ?? string.Empty;
|
||||||
|
if (!path.StartsWith('/'))
|
||||||
|
path = '/' + path;
|
||||||
|
|
||||||
|
string legacyUrl = $"{(AuthServer.UseHttps ? "https" : "http")}://{AuthServer.Host}:{AuthServer.Port}{path}";
|
||||||
|
return TrySetAuthServerUrl(legacyUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TrySetAuthServerUrl(string url)
|
||||||
|
{
|
||||||
|
if (!TryGetNormalizedAuthServerUri(url, out Uri? authServerUri))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
AuthServerUrl = authServerUri.AbsoluteUri;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryGetAuthServerUri([NotNullWhen(true)] out Uri? authServerUri)
|
||||||
|
=> TryGetNormalizedAuthServerUri(AuthServerUrl, out authServerUri);
|
||||||
|
|
||||||
|
private static bool TryGetNormalizedAuthServerUri(string? url, [NotNullWhen(true)] out Uri? authServerUri)
|
||||||
|
{
|
||||||
|
authServerUri = null;
|
||||||
|
if (!Uri.TryCreate(url?.Trim(), UriKind.Absolute, out Uri? parsedUri)
|
||||||
|
|| (!parsedUri.Scheme.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase)
|
||||||
|
&& !parsedUri.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase))
|
||||||
|
|| string.IsNullOrWhiteSpace(parsedUri.Host)
|
||||||
|
|| !string.IsNullOrEmpty(parsedUri.UserInfo)
|
||||||
|
|| !string.IsNullOrEmpty(parsedUri.Query)
|
||||||
|
|| !string.IsNullOrEmpty(parsedUri.Fragment))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var builder = new UriBuilder(parsedUri)
|
||||||
|
{
|
||||||
|
Path = parsedUri.AbsolutePath.TrimEnd('/') + "/"
|
||||||
|
};
|
||||||
|
authServerUri = builder.Uri;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
public enum LoginType { mojang, microsoft, yggdrasil };
|
public enum LoginType { mojang, microsoft, yggdrasil };
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1322,6 +1322,8 @@ redirectFrom:
|
||||||
|
|
||||||
A lost TCP connection always triggers Auto Relog when the bot is enabled. `Kick_Messages` only filters server kick and login rejection messages. Logging out with an MCC command never triggers Auto Relog.
|
A lost TCP connection always triggers Auto Relog when the bot is enabled. `Kick_Messages` only filters server kick and login rejection messages. Logging out with an MCC command never triggers Auto Relog.
|
||||||
|
|
||||||
|
One logical disconnect or login rejection consumes one retry. `Ignore_Kick_Message` controls filtering, but it does not create additional restart decisions for the same failure.
|
||||||
|
|
||||||
- **Settings:**
|
- **Settings:**
|
||||||
|
|
||||||
**Section:** **`ChatBot.AutoRelog`**
|
**Section:** **`ChatBot.AutoRelog`**
|
||||||
|
|
@ -1349,6 +1351,8 @@ redirectFrom:
|
||||||
|
|
||||||
If `min` and `max` are equal, every attempt uses that delay. Otherwise, MCC picks a random value in the range. Values are seconds and may include a fractional part, such as `0.5` or `37.0`.
|
If `min` and `max` are equal, every attempt uses that delay. Otherwise, MCC picks a random value in the range. Values are seconds and may include a fractional part, such as `0.5` or `37.0`.
|
||||||
|
|
||||||
|
For multi-process deployments, use a nonzero range such as `{ min = 3.0, max = 10.0 }` so clients do not reconnect in lockstep during maintenance. Equal values remain supported when a fixed interval is required.
|
||||||
|
|
||||||
- **Format:** `{ min = <seconds (double)>, max = <seconds (double)> }`
|
- **Format:** `{ min = <seconds (double)>, max = <seconds (double)> }`
|
||||||
|
|
||||||
- **Type:** `inline table`
|
- **Type:** `inline table`
|
||||||
|
|
|
||||||
|
|
@ -138,6 +138,16 @@ Coordinate = { x = 145, y = 64, z = 2045 }
|
||||||
AccountType = "microsoft"
|
AccountType = "microsoft"
|
||||||
```
|
```
|
||||||
|
|
||||||
|
#### Interactive login
|
||||||
|
|
||||||
|
If both `Account.Login` and `Account.Password` are empty when MCC starts, it asks which account type to use instead of assuming Microsoft login.
|
||||||
|
|
||||||
|
- Choose Offline to enter an in-game username. MCC saves the account as an offline account.
|
||||||
|
- Choose Online (Microsoft) to continue with the device-code sign-in. MCC shows the code and link, then opens the sign-in page in your browser.
|
||||||
|
- Choose Yggdrasil to enter the username, password, and authlib-injector URL for the account server. MCC checks the URL before it continues. If the address is malformed, unreachable, or does not return authlib-injector metadata, MCC explains the problem and asks for another URL.
|
||||||
|
|
||||||
|
After a successful login, MCC saves the account details and selected account type in the configuration file. Later starts use those saved details and do not show this prompt. To choose a different method, edit or clear the account settings in the configuration file.
|
||||||
|
|
||||||
#### `Method`
|
#### `Method`
|
||||||
|
|
||||||
- **Description:**
|
- **Description:**
|
||||||
|
|
@ -154,52 +164,32 @@ Coordinate = { x = 145, y = 64, z = 2045 }
|
||||||
Method = "mcc"
|
Method = "mcc"
|
||||||
```
|
```
|
||||||
|
|
||||||
#### `AuthServer`
|
#### `AuthServerUrl`
|
||||||
|
|
||||||
- **Description:**
|
- **Description:**
|
||||||
|
|
||||||
This subsection is used when `AccountType` is set to `yggdrasil`. It points MCC at the authlib/Yggdrasil server used for login, session checks, and profile key requests.
|
Use this setting with `AccountType = "yggdrasil"`. It is the complete base URL of the authlib-injector or Yggdrasil service MCC uses for login, session checks, and profile key requests.
|
||||||
|
|
||||||
MCC now writes this as a dedicated TOML subsection instead of an inline table:
|
The URL must start with `http://` or `https://` and include any path used by the service. For example, an authlib-injector server may use `/authlib-injector/` as its base path.
|
||||||
|
|
||||||
```toml
|
An existing multi-field Yggdrasil configuration is converted to this URL automatically. When MCC writes the configuration after migration, it removes the previous Yggdrasil section.
|
||||||
[Main.General.AuthServer]
|
|
||||||
```
|
|
||||||
|
|
||||||
`Host` accepts either a plain host name or a `host:port` pair. If you include the port there, MCC updates `Port` to match.
|
- **Type:** `string`
|
||||||
|
|
||||||
`AuthlibInjectorAPIPath` defaults to `/api/yggdrasil`. Change it if your authlib-injector server uses a different prefix, such as `/authlib-injector`.
|
- **Default:** `""`
|
||||||
|
|
||||||
`UseHttps` defaults to `true`. Set it to `false` if your local or development auth server only exposes plain HTTP.
|
|
||||||
|
|
||||||
- **Type:** `section`
|
|
||||||
|
|
||||||
- **Default:**
|
|
||||||
|
|
||||||
```toml
|
|
||||||
[Main.General.AuthServer]
|
|
||||||
Port = 443
|
|
||||||
AuthlibInjectorAPIPath = "/api/yggdrasil"
|
|
||||||
UseHttps = true
|
|
||||||
Host = ""
|
|
||||||
```
|
|
||||||
|
|
||||||
- **Example:**
|
- **Example:**
|
||||||
|
|
||||||
```
|
```toml
|
||||||
[Main.General.AuthServer]
|
Account = { Login = "player@example.com", Password = "password" }
|
||||||
Host = "auth.example.com"
|
AccountType = "yggdrasil"
|
||||||
Port = 443
|
AuthServerUrl = "https://auth.example.com/api/yggdrasil/"
|
||||||
AuthlibInjectorAPIPath = "/api/yggdrasil"
|
|
||||||
UseHttps = true
|
|
||||||
```
|
```
|
||||||
|
|
||||||
```
|
```toml
|
||||||
[Main.General.AuthServer]
|
Account = { Login = "player", Password = "password" }
|
||||||
Host = "127.0.0.1"
|
AccountType = "yggdrasil"
|
||||||
Port = 25585
|
AuthServerUrl = "http://127.0.0.1:25585/authlib-injector/"
|
||||||
AuthlibInjectorAPIPath = "/authlib-injector"
|
|
||||||
UseHttps = false
|
|
||||||
```
|
```
|
||||||
|
|
||||||
#### `AuthUser`
|
#### `AuthUser`
|
||||||
|
|
|
||||||
|
|
@ -20,7 +20,7 @@
|
||||||
"@vuepress/plugin-search": "2.0.0-rc.125",
|
"@vuepress/plugin-search": "2.0.0-rc.125",
|
||||||
"@vuepress/plugin-shiki": "2.0.0-rc.125",
|
"@vuepress/plugin-shiki": "2.0.0-rc.125",
|
||||||
"@vuepress/theme-default": "2.0.0-rc.125",
|
"@vuepress/theme-default": "2.0.0-rc.125",
|
||||||
"mermaid": "11.15.0",
|
"mermaid": "11.16.1",
|
||||||
"sass-embedded": "1.98.0",
|
"sass-embedded": "1.98.0",
|
||||||
"sass-loader": "16.0.7",
|
"sass-loader": "16.0.7",
|
||||||
"vuepress": "2.0.0-rc.26"
|
"vuepress": "2.0.0-rc.26"
|
||||||
|
|
|
||||||
140
docs/yarn.lock
140
docs/yarn.lock
|
|
@ -56,7 +56,7 @@
|
||||||
"@babel/helper-string-parser" "^7.27.1"
|
"@babel/helper-string-parser" "^7.27.1"
|
||||||
"@babel/helper-validator-identifier" "^7.28.5"
|
"@babel/helper-validator-identifier" "^7.28.5"
|
||||||
|
|
||||||
"@braintree/sanitize-url@^7.1.1":
|
"@braintree/sanitize-url@^7.1.2":
|
||||||
version "7.1.2"
|
version "7.1.2"
|
||||||
resolved "https://registry.yarnpkg.com/@braintree/sanitize-url/-/sanitize-url-7.1.2.tgz#ca2035b0fefe956a8676ff0c69af73e605fcd81f"
|
resolved "https://registry.yarnpkg.com/@braintree/sanitize-url/-/sanitize-url-7.1.2.tgz#ca2035b0fefe956a8676ff0c69af73e605fcd81f"
|
||||||
integrity sha512-jigsZK+sMF/cuiB7sERuo9V7N9jx+dhmHHnQyDSVdpZwVutaBu7WvNYqMDLSgFgfB30n452TP3vjDAvFC973mA==
|
integrity sha512-jigsZK+sMF/cuiB7sERuo9V7N9jx+dhmHHnQyDSVdpZwVutaBu7WvNYqMDLSgFgfB30n452TP3vjDAvFC973mA==
|
||||||
|
|
@ -66,7 +66,7 @@
|
||||||
resolved "https://registry.yarnpkg.com/@bufbuild/protobuf/-/protobuf-2.11.0.tgz#3ec3985c9074b23aea337957225fe15a0e845f8e"
|
resolved "https://registry.yarnpkg.com/@bufbuild/protobuf/-/protobuf-2.11.0.tgz#3ec3985c9074b23aea337957225fe15a0e845f8e"
|
||||||
integrity sha512-sBXGT13cpmPR5BMgHE6UEEfEaShh5Ror6rfN3yEK5si7QVrtZg8LEPQb0VVhiLRUslD2yLnXtnRzG035J/mZXQ==
|
integrity sha512-sBXGT13cpmPR5BMgHE6UEEfEaShh5Ror6rfN3yEK5si7QVrtZg8LEPQb0VVhiLRUslD2yLnXtnRzG035J/mZXQ==
|
||||||
|
|
||||||
"@chevrotain/types@~11.1.1":
|
"@chevrotain/types@~11.1.2":
|
||||||
version "11.1.2"
|
version "11.1.2"
|
||||||
resolved "https://registry.yarnpkg.com/@chevrotain/types/-/types-11.1.2.tgz#e83a1a2704f0c5e49e7592b214031a0f4a34d7e5"
|
resolved "https://registry.yarnpkg.com/@chevrotain/types/-/types-11.1.2.tgz#e83a1a2704f0c5e49e7592b214031a0f4a34d7e5"
|
||||||
integrity sha512-U+HFai5+zmJCkK86QsaJtoITlboZHBqrVketcO2ROv865xfCMSFpELQoz1GkX5GzME8pTa+3kbKrZHQtI0gdbw==
|
integrity sha512-U+HFai5+zmJCkK86QsaJtoITlboZHBqrVketcO2ROv865xfCMSFpELQoz1GkX5GzME8pTa+3kbKrZHQtI0gdbw==
|
||||||
|
|
@ -739,12 +739,12 @@
|
||||||
"@mdit/helper" "0.23.1"
|
"@mdit/helper" "0.23.1"
|
||||||
"@types/markdown-it" "^14.1.2"
|
"@types/markdown-it" "^14.1.2"
|
||||||
|
|
||||||
"@mermaid-js/parser@^1.1.1":
|
"@mermaid-js/parser@^1.2.0":
|
||||||
version "1.1.1"
|
version "1.2.0"
|
||||||
resolved "https://registry.yarnpkg.com/@mermaid-js/parser/-/parser-1.1.1.tgz#30f3ab68d816912e43f245a72a0d4081bf69d966"
|
resolved "https://registry.yarnpkg.com/@mermaid-js/parser/-/parser-1.2.0.tgz#266d728c54d2d4034d270f8b31d790e26296a5fa"
|
||||||
integrity sha512-VuHdsYMK1bT6X2JbcAaWAhugTRvRBRyuZgd+c22swUeI9g/ntaxF7CY7dYarhZovofCbUNO0G7JesfmNtjYOCw==
|
integrity sha512-oYPyv8A4As1yH5Bx+04iQEQxXuIQDe0GKCNSRgao6z8AM9jixXIfP0vsppRLvGf+nKIOb9/LdpWA4YuJiVvESA==
|
||||||
dependencies:
|
dependencies:
|
||||||
"@chevrotain/types" "~11.1.1"
|
"@chevrotain/types" "~11.1.2"
|
||||||
|
|
||||||
"@noble/hashes@1.4.0":
|
"@noble/hashes@1.4.0":
|
||||||
version "1.4.0"
|
version "1.4.0"
|
||||||
|
|
@ -3246,10 +3246,10 @@ cytoscape-fcose@^2.2.0:
|
||||||
dependencies:
|
dependencies:
|
||||||
cose-base "^2.2.0"
|
cose-base "^2.2.0"
|
||||||
|
|
||||||
cytoscape@^3.33.1:
|
cytoscape@^3.33.3:
|
||||||
version "3.33.1"
|
version "3.34.0"
|
||||||
resolved "https://registry.yarnpkg.com/cytoscape/-/cytoscape-3.33.1.tgz#449e05d104b760af2912ab76482d24c01cdd4c97"
|
resolved "https://registry.yarnpkg.com/cytoscape/-/cytoscape-3.34.0.tgz#5fbe2eb1cf76b070a8ecd5647c35f65aa097c9c6"
|
||||||
integrity sha512-iJc4TwyANnOGR1OmWhsS9ayRS3s+XQ185FmuHObThD+5AeJCakAAbWv8KimMTt08xCCLNgneQwFp+JRJOr9qGQ==
|
integrity sha512-62rNSrioXw93uliKFBwjukeQyeWwH2PqDrTac31r2P6464u3AUvTk0xS4LVvT251g7IgkFunrI48ZEZGjywSOg==
|
||||||
|
|
||||||
"d3-array@1 - 2":
|
"d3-array@1 - 2":
|
||||||
version "2.12.1"
|
version "2.12.1"
|
||||||
|
|
@ -3530,10 +3530,10 @@ dagre-d3-es@7.0.14:
|
||||||
d3 "^7.9.0"
|
d3 "^7.9.0"
|
||||||
lodash-es "^4.17.21"
|
lodash-es "^4.17.21"
|
||||||
|
|
||||||
dayjs@^1.11.19:
|
dayjs@^1.11.20:
|
||||||
version "1.11.20"
|
version "1.11.21"
|
||||||
resolved "https://registry.yarnpkg.com/dayjs/-/dayjs-1.11.20.tgz#88d919fd639dc991415da5f4cb6f1b6650811938"
|
resolved "https://registry.yarnpkg.com/dayjs/-/dayjs-1.11.21.tgz#57f87562e62de76f3c704bd2b8d522fc33068eb2"
|
||||||
integrity sha512-YbwwqR/uYpeoP4pu043q+LTDLFBLApUP6VxRihdfNTqu4ubqMlGDLd6ErXhEgsyvY0K6nCs7nggYumAN+9uEuQ==
|
integrity sha512-98IT+HOahAisibz/yjKbzuOBwYcjJ7BCLPzARyHiyEBmRz4fatF+KPJszEHXsGYjUG234aH/cOjW1wwTbKUZlA==
|
||||||
|
|
||||||
debug@2.6.9, debug@^2.2.0, debug@^2.3.3:
|
debug@2.6.9, debug@^2.2.0, debug@^2.3.3:
|
||||||
version "2.6.9"
|
version "2.6.9"
|
||||||
|
|
@ -3701,10 +3701,10 @@ domhandler@^5.0.2, domhandler@^5.0.3:
|
||||||
dependencies:
|
dependencies:
|
||||||
domelementtype "^2.3.0"
|
domelementtype "^2.3.0"
|
||||||
|
|
||||||
dompurify@^3.3.1:
|
dompurify@^3.3.3:
|
||||||
version "3.4.11"
|
version "3.4.13"
|
||||||
resolved "https://registry.yarnpkg.com/dompurify/-/dompurify-3.4.11.tgz#29c8ba496475f279ef4015784068452fb14a0680"
|
resolved "https://registry.yarnpkg.com/dompurify/-/dompurify-3.4.13.tgz#fc28949d59f92d62e28a3a764bcbeee35897a1be"
|
||||||
integrity sha512-zhlUV12GsaRzMsf9q5M254YhA4+VuF0fG+QFqu6aYpoGlKtz+w8//jBcGVYBgQkR5GHjUomejY84AV+/uPbWdw==
|
integrity sha512-2vmYIoqjze2d+kakP8S/nS5shfsl587kzwEjcGlTdiksUVgFHnFCsLYDVj/JNqJVOQZGSYBTmuycv0PodwmnMQ==
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
"@types/trusted-types" "^2.0.7"
|
"@types/trusted-types" "^2.0.7"
|
||||||
|
|
||||||
|
|
@ -4077,9 +4077,9 @@ fast-deep-equal@^3.1.1, fast-deep-equal@^3.1.3:
|
||||||
integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==
|
integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==
|
||||||
|
|
||||||
fast-uri@^3.0.1:
|
fast-uri@^3.0.1:
|
||||||
version "3.1.2"
|
version "3.1.5"
|
||||||
resolved "https://registry.yarnpkg.com/fast-uri/-/fast-uri-3.1.2.tgz#8af3d4fc9d3e71b11572cc2673b514a7d1a8c8ec"
|
resolved "https://registry.yarnpkg.com/fast-uri/-/fast-uri-3.1.5.tgz#610f37419a030270430cecd68d74e3d4d96725d0"
|
||||||
integrity sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==
|
integrity sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw==
|
||||||
|
|
||||||
faye-websocket@^0.11.3:
|
faye-websocket@^0.11.3:
|
||||||
version "0.11.4"
|
version "0.11.4"
|
||||||
|
|
@ -4603,9 +4603,9 @@ icss-utils@^5.0.0, icss-utils@^5.1.0:
|
||||||
integrity sha512-soFhflCVWLfRNOPU3iv5Z9VUdT44xFRbzjLsEzSr5AQmgqPMTHdU3PMT1Cf1ssx8fLNJDA1juftYl+PUcv3MqA==
|
integrity sha512-soFhflCVWLfRNOPU3iv5Z9VUdT44xFRbzjLsEzSr5AQmgqPMTHdU3PMT1Cf1ssx8fLNJDA1juftYl+PUcv3MqA==
|
||||||
|
|
||||||
immutable@^5.1.5:
|
immutable@^5.1.5:
|
||||||
version "5.1.5"
|
version "5.1.9"
|
||||||
resolved "https://registry.yarnpkg.com/immutable/-/immutable-5.1.5.tgz#93ee4db5c2a9ab42a4a783069f3c5d8847d40165"
|
resolved "https://registry.yarnpkg.com/immutable/-/immutable-5.1.9.tgz#ac23c3a01992ab665e14ac9ffff298f28cd74a0c"
|
||||||
integrity sha512-t7xcm2siw+hlUM68I+UEOK+z84RzmN59as9DZ7P1l0994DKUWV7UXBMQZVxaoMSRQ+PBZbHCOoBt7a2wxOMt+A==
|
integrity sha512-m8nVez3rwrgmWxtLMt1ZYXB2Lv7OKYn/disyxAlSDYAlKSlFoPPfIAmAM/M5xqL4m4C/wAPw7S2/CNaUii1Hxg==
|
||||||
|
|
||||||
import-fresh@^3.3.0:
|
import-fresh@^3.3.0:
|
||||||
version "3.3.1"
|
version "3.3.1"
|
||||||
|
|
@ -4908,10 +4908,10 @@ jsonfile@^6.0.1:
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
graceful-fs "^4.1.6"
|
graceful-fs "^4.1.6"
|
||||||
|
|
||||||
katex@^0.16.25:
|
katex@^0.16.45:
|
||||||
version "0.16.40"
|
version "0.16.47"
|
||||||
resolved "https://registry.yarnpkg.com/katex/-/katex-0.16.40.tgz#87c94e4149f8fa7c22ff95bae1dc687355a38d63"
|
resolved "https://registry.yarnpkg.com/katex/-/katex-0.16.47.tgz#0a13a42c2deb4f74e61f162d440b9165a548030f"
|
||||||
integrity sha512-1DJcK/L05k1Y9Gf7wMcyuqFOL6BiY3vY0CFcAM/LPRN04NALxcl6u7lOWNsp3f/bCHWxigzQl6FbR95XJ4R84Q==
|
integrity sha512-Eeo8Ys1doU1z+x8AZsPpQu+p/QcZBI5PeOo7QGQdy2x2m0MU/hYagBbGOmXwr5KVbEfVuWv9LpnQWeehogurjg==
|
||||||
dependencies:
|
dependencies:
|
||||||
commander "^8.3.0"
|
commander "^8.3.0"
|
||||||
|
|
||||||
|
|
@ -4944,7 +4944,7 @@ kind-of@^6.0.0, kind-of@^6.0.2:
|
||||||
resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.3.tgz#07c05034a6c349fa06e24fa35aa76db4580ce4dd"
|
resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.3.tgz#07c05034a6c349fa06e24fa35aa76db4580ce4dd"
|
||||||
integrity sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==
|
integrity sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==
|
||||||
|
|
||||||
launch-editor@^2.6.1:
|
launch-editor@^2.14.1:
|
||||||
version "2.14.1"
|
version "2.14.1"
|
||||||
resolved "https://registry.yarnpkg.com/launch-editor/-/launch-editor-2.14.1.tgz#f7e0da3f58aaea03fea01074d840b5f739ed7ddc"
|
resolved "https://registry.yarnpkg.com/launch-editor/-/launch-editor-2.14.1.tgz#f7e0da3f58aaea03fea01074d840b5f739ed7ddc"
|
||||||
integrity sha512-QWBrQsMpH7gPr965dsKD/3cKWiNoTjpATQf++Xq63N6sKRGMwlVXz41O1IZTMfZQgBctD/K5Zt06+/I6pP6+HA==
|
integrity sha512-QWBrQsMpH7gPr965dsKD/3cKWiNoTjpATQf++Xq63N6sKRGMwlVXz41O1IZTMfZQgBctD/K5Zt06+/I6pP6+HA==
|
||||||
|
|
@ -5047,9 +5047,9 @@ lines-and-columns@^1.1.6:
|
||||||
integrity sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==
|
integrity sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==
|
||||||
|
|
||||||
linkify-it@^5.0.1:
|
linkify-it@^5.0.1:
|
||||||
version "5.0.1"
|
version "5.0.2"
|
||||||
resolved "https://registry.yarnpkg.com/linkify-it/-/linkify-it-5.0.1.tgz#10c4cecbb5c6828eabf81d3c801adc4a542dfb55"
|
resolved "https://registry.yarnpkg.com/linkify-it/-/linkify-it-5.0.2.tgz#d3be0a693af3da9df3883f1e346a0e97461a8c19"
|
||||||
integrity sha512-wVoTjP4Q6R0NW5hiZkVJaFZPWgtXfoGF+6LucL3/FtiNjmcHhYjEr5f1Kqjirc1nBW07J/ZuRFumqr2oqccEWg==
|
integrity sha512-ONTm2jCMAVZjgQa/Fy1kScXsuOoF5NPTsoFBdE1KVIZ2vAh/r9+Bqo+0jINCBYnavTPQZz38QzFTme79ENoN3Q==
|
||||||
dependencies:
|
dependencies:
|
||||||
uc.micro "^2.0.0"
|
uc.micro "^2.0.0"
|
||||||
|
|
||||||
|
|
@ -5068,9 +5068,9 @@ loader-utils@^2.0.4:
|
||||||
json5 "^2.1.2"
|
json5 "^2.1.2"
|
||||||
|
|
||||||
lodash-es@^4.17.21:
|
lodash-es@^4.17.21:
|
||||||
version "4.17.23"
|
version "4.18.1"
|
||||||
resolved "https://registry.yarnpkg.com/lodash-es/-/lodash-es-4.17.23.tgz#58c4360fd1b5d33afc6c0bbd3d1149349b1138e0"
|
resolved "https://registry.yarnpkg.com/lodash-es/-/lodash-es-4.18.1.tgz#b962eeb80d9d983a900bf342961fb7418ca10b1d"
|
||||||
integrity sha512-kVI48u3PZr38HdYz98UmfPnXl2DXrpdctLrFLCd3kOx1xUkOmpFPx7gCWWM5MPkL/fD8zb+Ph0QzjGFs4+hHWg==
|
integrity sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==
|
||||||
|
|
||||||
lodash.memoize@^4.1.2:
|
lodash.memoize@^4.1.2:
|
||||||
version "4.1.2"
|
version "4.1.2"
|
||||||
|
|
@ -5223,26 +5223,26 @@ merge-stream@^2.0.0:
|
||||||
resolved "https://registry.yarnpkg.com/merge-stream/-/merge-stream-2.0.0.tgz#52823629a14dd00c9770fb6ad47dc6310f2c1f60"
|
resolved "https://registry.yarnpkg.com/merge-stream/-/merge-stream-2.0.0.tgz#52823629a14dd00c9770fb6ad47dc6310f2c1f60"
|
||||||
integrity sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==
|
integrity sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==
|
||||||
|
|
||||||
mermaid@11.15.0:
|
mermaid@11.16.1:
|
||||||
version "11.15.0"
|
version "11.16.1"
|
||||||
resolved "https://registry.yarnpkg.com/mermaid/-/mermaid-11.15.0.tgz#b485c13ea5e1e74f3328c4bb00427bda87fa1c1e"
|
resolved "https://registry.yarnpkg.com/mermaid/-/mermaid-11.16.1.tgz#57ae2342f6c45b967113b04c9258430bdd057ee8"
|
||||||
integrity sha512-pTMbcf3rWdtLiYGpmoTjHEpeY8seiy6sR+9nD7LOs8KfUbHE4lOUAprTRqRAcWSQ6MQpdX+YEsxShtGsINtPtw==
|
integrity sha512-TQsq6u22fAn3rek5VOubrhKPo1g5hwC3FXUN9hiyupTckcYiGuuKGkNQrKYwGJkXUxZdojwRG46gsSCFZMDp4g==
|
||||||
dependencies:
|
dependencies:
|
||||||
"@braintree/sanitize-url" "^7.1.1"
|
"@braintree/sanitize-url" "^7.1.2"
|
||||||
"@iconify/utils" "^3.0.2"
|
"@iconify/utils" "^3.0.2"
|
||||||
"@mermaid-js/parser" "^1.1.1"
|
"@mermaid-js/parser" "^1.2.0"
|
||||||
"@types/d3" "^7.4.3"
|
"@types/d3" "^7.4.3"
|
||||||
"@upsetjs/venn.js" "^2.0.0"
|
"@upsetjs/venn.js" "^2.0.0"
|
||||||
cytoscape "^3.33.1"
|
cytoscape "^3.33.3"
|
||||||
cytoscape-cose-bilkent "^4.1.0"
|
cytoscape-cose-bilkent "^4.1.0"
|
||||||
cytoscape-fcose "^2.2.0"
|
cytoscape-fcose "^2.2.0"
|
||||||
d3 "^7.9.0"
|
d3 "^7.9.0"
|
||||||
d3-sankey "^0.12.3"
|
d3-sankey "^0.12.3"
|
||||||
dagre-d3-es "7.0.14"
|
dagre-d3-es "7.0.14"
|
||||||
dayjs "^1.11.19"
|
dayjs "^1.11.20"
|
||||||
dompurify "^3.3.1"
|
dompurify "^3.3.3"
|
||||||
es-toolkit "^1.45.1"
|
es-toolkit "^1.45.1"
|
||||||
katex "^0.16.25"
|
katex "^0.16.45"
|
||||||
khroma "^2.1.0"
|
khroma "^2.1.0"
|
||||||
marked "^16.3.0"
|
marked "^16.3.0"
|
||||||
roughjs "^4.6.6"
|
roughjs "^4.6.6"
|
||||||
|
|
@ -5407,10 +5407,10 @@ multicast-dns@^7.2.5:
|
||||||
dns-packet "^5.2.2"
|
dns-packet "^5.2.2"
|
||||||
thunky "^1.0.2"
|
thunky "^1.0.2"
|
||||||
|
|
||||||
nanoid@^3.3.11:
|
nanoid@^3.3.16:
|
||||||
version "3.3.11"
|
version "3.3.16"
|
||||||
resolved "https://registry.yarnpkg.com/nanoid/-/nanoid-3.3.11.tgz#4f4f112cefbe303202f2199838128936266d185b"
|
resolved "https://registry.yarnpkg.com/nanoid/-/nanoid-3.3.16.tgz#a04d8ec4b1f10009d2d533947aefe4293737816c"
|
||||||
integrity sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==
|
integrity sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==
|
||||||
|
|
||||||
nanoid@^5.1.6:
|
nanoid@^5.1.6:
|
||||||
version "5.1.7"
|
version "5.1.7"
|
||||||
|
|
@ -5986,11 +5986,11 @@ postcss-value-parser@^4.1.0, postcss-value-parser@^4.2.0:
|
||||||
integrity sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==
|
integrity sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==
|
||||||
|
|
||||||
postcss@^8.4.40, postcss@^8.5.6, postcss@^8.5.8:
|
postcss@^8.4.40, postcss@^8.5.6, postcss@^8.5.8:
|
||||||
version "8.5.14"
|
version "8.5.23"
|
||||||
resolved "https://registry.yarnpkg.com/postcss/-/postcss-8.5.14.tgz#a66c2d7808fadf69ebb5b84a03f8bafd76c4919c"
|
resolved "https://registry.yarnpkg.com/postcss/-/postcss-8.5.23.tgz#3493550116f478487298301d2c2e8dc5a56e6594"
|
||||||
integrity sha512-SoSL4+OSEtR99LHFZQiJLkT59C5B1amGO1NzTwj7TT1qCUgUO6hxOvzkOYxD+vMrXBM3XJIKzokoERdqQq/Zmg==
|
integrity sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg==
|
||||||
dependencies:
|
dependencies:
|
||||||
nanoid "^3.3.11"
|
nanoid "^3.3.16"
|
||||||
picocolors "^1.1.1"
|
picocolors "^1.1.1"
|
||||||
source-map-js "^1.2.1"
|
source-map-js "^1.2.1"
|
||||||
|
|
||||||
|
|
@ -6631,9 +6631,9 @@ shallow-clone@^3.0.0:
|
||||||
kind-of "^6.0.2"
|
kind-of "^6.0.2"
|
||||||
|
|
||||||
shell-quote@^1.8.4:
|
shell-quote@^1.8.4:
|
||||||
version "1.8.4"
|
version "1.10.0"
|
||||||
resolved "https://registry.yarnpkg.com/shell-quote/-/shell-quote-1.8.4.tgz#2edd9a4dcefc96649e2e2cb12f637b1f1d92a190"
|
resolved "https://registry.yarnpkg.com/shell-quote/-/shell-quote-1.10.0.tgz#482033e192e4f5c07151521ffa03400ec71b1b0f"
|
||||||
integrity sha512-VsC6n6vz1ihYYyZZwX7YZSF5l5x36ca17OC+a69h94YqB7X6XLwf+5MOgynYir2SLFUbl8gIYvBo8K8RoNQ6bQ==
|
integrity sha512-w1aiOKwKuRgtwAReIIj89puqg+I7GvX4IbLrvmhXbzQsj1+Zwi4VO3+fa6ZF91TWSjIxoEkKnMeHcLEODK5ZXA==
|
||||||
|
|
||||||
shiki@^4.0.1:
|
shiki@^4.0.1:
|
||||||
version "4.0.2"
|
version "4.0.2"
|
||||||
|
|
@ -6949,9 +6949,9 @@ supports-color@^8.0.0, supports-color@^8.1.1:
|
||||||
has-flag "^4.0.0"
|
has-flag "^4.0.0"
|
||||||
|
|
||||||
svgo@^4.0.1:
|
svgo@^4.0.1:
|
||||||
version "4.0.1"
|
version "4.0.2"
|
||||||
resolved "https://registry.yarnpkg.com/svgo/-/svgo-4.0.1.tgz#c82dacd04ee9f1d55cd4e0b7f9a214c86670e3ee"
|
resolved "https://registry.yarnpkg.com/svgo/-/svgo-4.0.2.tgz#a62246f0a9d671c0314d04f3cc15f78b1bd0667f"
|
||||||
integrity sha512-XDpWUOPC6FEibaLzjfe0ucaV0YrOjYotGJO1WpF0Zd+n6ZGEQUsSugaoLq9QkEZtAfQIxT42UChcssDVPP3+/w==
|
integrity sha512-ekx94z1rRc5LDi6oSUaeRnYhd0UOJxdtQCL2rF8xpWxD3TPAsISWOrxezqGovqS38GRZOdpDfvQe3ts6F7nsng==
|
||||||
dependencies:
|
dependencies:
|
||||||
commander "^11.1.0"
|
commander "^11.1.0"
|
||||||
css-select "^5.1.0"
|
css-select "^5.1.0"
|
||||||
|
|
@ -7146,9 +7146,9 @@ undici-types@~7.16.0:
|
||||||
integrity sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==
|
integrity sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==
|
||||||
|
|
||||||
undici@^7.19.0:
|
undici@^7.19.0:
|
||||||
version "7.28.0"
|
version "7.29.0"
|
||||||
resolved "https://registry.yarnpkg.com/undici/-/undici-7.28.0.tgz#97d64564198b285bc281f0e8e29597e3d11fe7ec"
|
resolved "https://registry.yarnpkg.com/undici/-/undici-7.29.0.tgz#ae0f6f62e06e057a9cbb7b2b5fde2bb74f791b8f"
|
||||||
integrity sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==
|
integrity sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==
|
||||||
|
|
||||||
unified@^11.0.0, unified@^11.0.5:
|
unified@^11.0.0, unified@^11.0.5:
|
||||||
version "11.0.5"
|
version "11.0.5"
|
||||||
|
|
@ -7405,9 +7405,9 @@ webpack-dev-middleware@^7.4.2:
|
||||||
schema-utils "^4.0.0"
|
schema-utils "^4.0.0"
|
||||||
|
|
||||||
webpack-dev-server@^5.2.2:
|
webpack-dev-server@^5.2.2:
|
||||||
version "5.2.5"
|
version "5.2.6"
|
||||||
resolved "https://registry.yarnpkg.com/webpack-dev-server/-/webpack-dev-server-5.2.5.tgz#648fceaac6a5736b0935e5c1e55d6aa1d0626119"
|
resolved "https://registry.yarnpkg.com/webpack-dev-server/-/webpack-dev-server-5.2.6.tgz#3a5d41233cbb7504f814d19e59a59173fb8ae23d"
|
||||||
integrity sha512-4wZtCquSuv9CKX8oybo+mqxtxZqWz47uM1Ch94lxowBztOhWCbhqvRbfC/mODOwxgV2brY+JGZpHq58/SuVFYg==
|
integrity sha512-HNLRmamRvVavZQ+avceZifmv8hmdUjg43t6MI4SqJDwFdW7RPQwH5vzGhDRZSX59SgfbeHhLnq3g+uooWo7pVw==
|
||||||
dependencies:
|
dependencies:
|
||||||
"@types/bonjour" "^3.5.13"
|
"@types/bonjour" "^3.5.13"
|
||||||
"@types/connect-history-api-fallback" "^1.5.4"
|
"@types/connect-history-api-fallback" "^1.5.4"
|
||||||
|
|
@ -7427,7 +7427,7 @@ webpack-dev-server@^5.2.2:
|
||||||
graceful-fs "^4.2.6"
|
graceful-fs "^4.2.6"
|
||||||
http-proxy-middleware "^2.0.9"
|
http-proxy-middleware "^2.0.9"
|
||||||
ipaddr.js "^2.1.0"
|
ipaddr.js "^2.1.0"
|
||||||
launch-editor "^2.6.1"
|
launch-editor "^2.14.1"
|
||||||
open "^10.0.3"
|
open "^10.0.3"
|
||||||
p-retry "^6.2.0"
|
p-retry "^6.2.0"
|
||||||
schema-utils "^4.2.0"
|
schema-utils "^4.2.0"
|
||||||
|
|
@ -7531,9 +7531,9 @@ wildcard@^2.0.1:
|
||||||
integrity sha512-CC1bOL87PIWSBhDcTrdeLo6eGT7mCFtrg0uIJtqJUFyK+eJnzl8A1niH56uu7KMa5XFrtiV+AQuHO3n7DsHnLQ==
|
integrity sha512-CC1bOL87PIWSBhDcTrdeLo6eGT7mCFtrg0uIJtqJUFyK+eJnzl8A1niH56uu7KMa5XFrtiV+AQuHO3n7DsHnLQ==
|
||||||
|
|
||||||
ws@^8.18.0:
|
ws@^8.18.0:
|
||||||
version "8.20.0"
|
version "8.21.1"
|
||||||
resolved "https://registry.yarnpkg.com/ws/-/ws-8.20.0.tgz#4cd9532358eba60bc863aad1623dfb045a4d4af8"
|
resolved "https://registry.yarnpkg.com/ws/-/ws-8.21.1.tgz#045650cd4b1207809e7547146223c3814a9af586"
|
||||||
integrity sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==
|
integrity sha512-+0NTnW77fFN/DjQi6k/Sq/Yvk4Sgajw7urW8V+asjXnRgDs9gyGkdb7EzgfhA4goXsRIZKE28fzIXBHEzhuiWw==
|
||||||
|
|
||||||
wsl-utils@^0.1.0:
|
wsl-utils@^0.1.0:
|
||||||
version "0.1.0"
|
version "0.1.0"
|
||||||
|
|
|
||||||
|
|
@ -14,25 +14,42 @@ Example:
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
import math
|
||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
|
from collections.abc import Sequence
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
OUTPUT_DIR = (Path(__file__).resolve().parent.parent /
|
OUTPUT_DIR = (Path(__file__).resolve().parent.parent /
|
||||||
"MinecraftClient" / "Mapping" / "BlockPalettes")
|
"MinecraftClient" / "Mapping" / "BlockPalettes")
|
||||||
MATERIAL_CS = OUTPUT_DIR.parent / "Material.cs"
|
MATERIAL_CS = OUTPUT_DIR.parent / "Material.cs"
|
||||||
|
|
||||||
|
# Minecraft renamed these registry keys after the corresponding MCC Material
|
||||||
|
# names had already stabilized. Keep historical reports mapped to the current
|
||||||
|
# enum names instead of generating references to members that do not exist.
|
||||||
|
MATERIAL_NAME_ALIASES = {
|
||||||
|
"Grass": "ShortGrass",
|
||||||
|
"GrassPath": "DirtPath",
|
||||||
|
"Sign": "OakSign",
|
||||||
|
"WallSign": "OakWallSign",
|
||||||
|
}
|
||||||
|
|
||||||
|
OUTPUT_FILE_ALIASES = {
|
||||||
|
"120": "BlockPalette120.cs",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def mc_name_to_csharp(mc_name: str) -> str:
|
def mc_name_to_csharp(mc_name: str) -> str:
|
||||||
"""Convert minecraft:snake_case to PascalCase C# enum name."""
|
"""Convert minecraft:snake_case to PascalCase C# enum name."""
|
||||||
name = mc_name.removeprefix("minecraft:")
|
name = mc_name.removeprefix("minecraft:")
|
||||||
return "".join(word.capitalize() for word in name.split("_"))
|
csharp_name = "".join(word.capitalize() for word in name.split("_"))
|
||||||
|
return MATERIAL_NAME_ALIASES.get(csharp_name, csharp_name)
|
||||||
|
|
||||||
|
|
||||||
def load_known_materials() -> set[str]:
|
def load_known_materials() -> set[str]:
|
||||||
known = set()
|
known = set()
|
||||||
if MATERIAL_CS.exists():
|
if MATERIAL_CS.exists():
|
||||||
with open(MATERIAL_CS) as f:
|
with MATERIAL_CS.open(encoding="utf-8-sig") as f:
|
||||||
for line in f:
|
for line in f:
|
||||||
m = re.match(r'\s+(\w+),?\s*$', line)
|
m = re.match(r'\s+(\w+),?\s*$', line)
|
||||||
if m:
|
if m:
|
||||||
|
|
@ -40,6 +57,122 @@ def load_known_materials() -> set[str]:
|
||||||
return known
|
return known
|
||||||
|
|
||||||
|
|
||||||
|
def get_state_property_definitions(
|
||||||
|
block_key: str,
|
||||||
|
states: list[dict],
|
||||||
|
properties: dict[str, list[str]],
|
||||||
|
) -> list[tuple[str, list[str], int]]:
|
||||||
|
"""Build and verify the compact stride schema against every reported state."""
|
||||||
|
if not properties:
|
||||||
|
return []
|
||||||
|
|
||||||
|
ordered_states = sorted(states, key=lambda state: state["id"])
|
||||||
|
first_state_id = ordered_states[0]["id"]
|
||||||
|
expected_ids = list(range(first_state_id, first_state_id + len(ordered_states)))
|
||||||
|
actual_ids = [state["id"] for state in ordered_states]
|
||||||
|
if actual_ids != expected_ids:
|
||||||
|
raise ValueError(f"{block_key} has non-contiguous state IDs")
|
||||||
|
|
||||||
|
expected_count = math.prod(len(values) for values in properties.values())
|
||||||
|
if expected_count != len(ordered_states):
|
||||||
|
raise ValueError(
|
||||||
|
f"{block_key} has {len(ordered_states)} states but its properties describe {expected_count} combinations"
|
||||||
|
)
|
||||||
|
|
||||||
|
definitions = []
|
||||||
|
for name, values in properties.items():
|
||||||
|
stride = next(
|
||||||
|
(
|
||||||
|
candidate
|
||||||
|
for candidate in range(1, len(ordered_states) + 1)
|
||||||
|
if all(
|
||||||
|
state.get("properties", {}).get(name)
|
||||||
|
== values[(offset // candidate) % len(values)]
|
||||||
|
for offset, state in enumerate(ordered_states)
|
||||||
|
)
|
||||||
|
),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
if stride is None:
|
||||||
|
raise ValueError(f"{block_key} property {name} has no regular state stride")
|
||||||
|
definitions.append((name, values, stride))
|
||||||
|
|
||||||
|
return definitions
|
||||||
|
|
||||||
|
|
||||||
|
def csharp_string(value: str) -> str:
|
||||||
|
"""Encode a Python string as a compatible C# string literal."""
|
||||||
|
return json.dumps(value, ensure_ascii=False)
|
||||||
|
|
||||||
|
|
||||||
|
def render_state_definitions(
|
||||||
|
block_ranges: Sequence[tuple[int, int, str, list[tuple[str, list[str], int]]]],
|
||||||
|
) -> tuple[list[str], int]:
|
||||||
|
"""Render the generated state-property section and return its definition count."""
|
||||||
|
lines = [
|
||||||
|
" // <auto-generated block-state-properties>",
|
||||||
|
" private static readonly BlockStateDefinition[] stateDefinitions =",
|
||||||
|
" [",
|
||||||
|
]
|
||||||
|
property_definition_count = 0
|
||||||
|
for min_s, max_s, _, properties in block_ranges:
|
||||||
|
if not properties:
|
||||||
|
continue
|
||||||
|
|
||||||
|
property_definition_count += 1
|
||||||
|
lines.append(f" new({min_s}, {max_s - min_s + 1},")
|
||||||
|
lines.append(" [")
|
||||||
|
for index, (name, values, stride) in enumerate(properties):
|
||||||
|
encoded_values = ", ".join(csharp_string(value) for value in values)
|
||||||
|
suffix = "," if index < len(properties) - 1 else ""
|
||||||
|
lines.append(f" new({csharp_string(name)}, [{encoded_values}], {stride}){suffix}")
|
||||||
|
lines.append(" ]),")
|
||||||
|
|
||||||
|
lines += [
|
||||||
|
" ];",
|
||||||
|
" // </auto-generated block-state-properties>",
|
||||||
|
]
|
||||||
|
return lines, property_definition_count
|
||||||
|
|
||||||
|
|
||||||
|
def update_existing_palette(output_path: Path, state_lines: list[str]) -> bool:
|
||||||
|
"""Replace only generated state metadata while preserving established material mappings."""
|
||||||
|
if not output_path.exists():
|
||||||
|
return False
|
||||||
|
|
||||||
|
source = output_path.read_text(encoding="utf-8")
|
||||||
|
dictionary_method = " protected override Dictionary<int, Material> GetDict()"
|
||||||
|
dictionary_index = source.find(dictionary_method)
|
||||||
|
if dictionary_index < 0:
|
||||||
|
raise ValueError(f"{output_path} does not contain the expected GetDict method")
|
||||||
|
|
||||||
|
generated_start = source.find(" // <auto-generated block-state-properties>")
|
||||||
|
legacy_start = source.find(" private static readonly BlockStateDefinition[] stateDefinitions =")
|
||||||
|
section_start = generated_start if generated_start >= 0 else legacy_start
|
||||||
|
if section_start < 0:
|
||||||
|
section_start = dictionary_index
|
||||||
|
|
||||||
|
prefix = source[:section_start].rstrip()
|
||||||
|
suffix = source[dictionary_index:]
|
||||||
|
state_override = """ protected override BlockStateDefinition[] GetStateDefinitions()
|
||||||
|
{
|
||||||
|
return stateDefinitions;
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
suffix = suffix.replace("\n" + state_override, "", 1)
|
||||||
|
|
||||||
|
class_end = suffix.rfind("\n }\n}")
|
||||||
|
if class_end < 0:
|
||||||
|
raise ValueError(f"{output_path} does not contain the expected class terminator")
|
||||||
|
suffix = suffix[:class_end].rstrip() + "\n\n" + state_override.rstrip() + suffix[class_end:]
|
||||||
|
|
||||||
|
output_path.write_text(
|
||||||
|
prefix + "\n\n" + "\n".join(state_lines) + "\n\n" + suffix,
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
if len(sys.argv) != 3:
|
if len(sys.argv) != 3:
|
||||||
print(__doc__)
|
print(__doc__)
|
||||||
|
|
@ -52,17 +185,18 @@ def main():
|
||||||
print(f"Error: {blocks_json} not found")
|
print(f"Error: {blocks_json} not found")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
with open(blocks_json) as f:
|
with blocks_json.open(encoding="utf-8") as f:
|
||||||
data = json.load(f)
|
data = json.load(f)
|
||||||
|
|
||||||
# Build (min_state, max_state, cs_name) for each block, sorted by min_state
|
# Build block ranges and compact state-property definitions, sorted by min state.
|
||||||
block_ranges = []
|
block_ranges = []
|
||||||
for block_key, block_info in data.items():
|
for block_key, block_info in data.items():
|
||||||
cs_name = mc_name_to_csharp(block_key)
|
cs_name = mc_name_to_csharp(block_key)
|
||||||
states = block_info.get("states", [])
|
states = block_info.get("states", [])
|
||||||
state_ids = [s["id"] for s in states]
|
state_ids = [s["id"] for s in states]
|
||||||
if state_ids:
|
if state_ids:
|
||||||
block_ranges.append((min(state_ids), max(state_ids), cs_name))
|
properties = get_state_property_definitions(block_key, states, block_info.get("properties", {}))
|
||||||
|
block_ranges.append((min(state_ids), max(state_ids), cs_name, properties))
|
||||||
|
|
||||||
block_ranges.sort(key=lambda x: x[0])
|
block_ranges.sort(key=lambda x: x[0])
|
||||||
print(f"Loaded {len(block_ranges)} blocks from {blocks_json}")
|
print(f"Loaded {len(block_ranges)} blocks from {blocks_json}")
|
||||||
|
|
@ -71,7 +205,7 @@ def main():
|
||||||
print(f"State ID range: 0 - {max_state}")
|
print(f"State ID range: 0 - {max_state}")
|
||||||
|
|
||||||
known_materials = load_known_materials()
|
known_materials = load_known_materials()
|
||||||
missing = [cs for _, _, cs in block_ranges if known_materials and cs not in known_materials]
|
missing = [cs for _, _, cs, _ in block_ranges if known_materials and cs not in known_materials]
|
||||||
if missing:
|
if missing:
|
||||||
print(f"\nWARNING: {len(missing)} blocks not found in Material.cs enum:")
|
print(f"\nWARNING: {len(missing)} blocks not found in Material.cs enum:")
|
||||||
for cs_name in missing:
|
for cs_name in missing:
|
||||||
|
|
@ -80,7 +214,15 @@ def main():
|
||||||
print("Insert them in alphabetical order within the enum.")
|
print("Insert them in alphabetical order within the enum.")
|
||||||
|
|
||||||
class_name = f"Palette{class_suffix}"
|
class_name = f"Palette{class_suffix}"
|
||||||
output_path = OUTPUT_DIR / f"{class_name}.cs"
|
output_path = OUTPUT_DIR / OUTPUT_FILE_ALIASES.get(class_suffix, f"{class_name}.cs")
|
||||||
|
state_lines, property_definition_count = render_state_definitions(block_ranges)
|
||||||
|
|
||||||
|
if update_existing_palette(output_path, state_lines):
|
||||||
|
print(
|
||||||
|
f"Updated {output_path} with {property_definition_count} property definitions "
|
||||||
|
"while preserving material mappings"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
lines = [
|
lines = [
|
||||||
"using System.Collections.Generic;",
|
"using System.Collections.Generic;",
|
||||||
|
|
@ -95,24 +237,36 @@ def main():
|
||||||
" {",
|
" {",
|
||||||
]
|
]
|
||||||
|
|
||||||
for min_s, max_s, cs_name in block_ranges:
|
for min_s, max_s, cs_name, _ in block_ranges:
|
||||||
lines.append(f" for (int i = {min_s}; i <= {max_s}; i++)")
|
lines.append(f" for (int i = {min_s}; i <= {max_s}; i++)")
|
||||||
lines.append(f" materials[i] = Material.{cs_name};")
|
lines.append(f" materials[i] = Material.{cs_name};")
|
||||||
|
|
||||||
lines += [
|
lines += [
|
||||||
" }",
|
" }",
|
||||||
"",
|
"",
|
||||||
|
*state_lines,
|
||||||
|
"",
|
||||||
|
]
|
||||||
|
lines += [
|
||||||
" protected override Dictionary<int, Material> GetDict()",
|
" protected override Dictionary<int, Material> GetDict()",
|
||||||
" {",
|
" {",
|
||||||
" return materials;",
|
" return materials;",
|
||||||
" }",
|
" }",
|
||||||
|
"",
|
||||||
|
" protected override BlockStateDefinition[] GetStateDefinitions()",
|
||||||
|
" {",
|
||||||
|
" return stateDefinitions;",
|
||||||
|
" }",
|
||||||
" }",
|
" }",
|
||||||
"}",
|
"}",
|
||||||
"",
|
"",
|
||||||
]
|
]
|
||||||
|
|
||||||
output_path.write_text("\n".join(lines))
|
output_path.write_text("\n".join(lines), encoding="utf-8")
|
||||||
print(f"Generated {output_path} with {len(block_ranges)} blocks ({max_state + 1} total states)")
|
print(
|
||||||
|
f"Generated {output_path} with {len(block_ranges)} blocks, "
|
||||||
|
f"{max_state + 1} total states, and {property_definition_count} property definitions"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue