using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using HarmonyLib;
using Il2Cpp;
using Il2CppGame.Menu;
using Il2CppGame.Networking;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppTMPro;
using MelonLoader;
using MelonLoader.Preferences;
using Microsoft.CodeAnalysis;
using POGMods.ModCheck;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.UI;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(ModCheckMod), "POG Mod Check", "0.1.1", "largo", "https://github.com/largoz/POGModCheck")]
[assembly: MelonGame(null, "Pit of Goblin")]
[assembly: HarmonyDontPatchAll]
[assembly: InternalsVisibleTo("POGLanTest")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("POGModCheck")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+241e8c16bf465de71b6f9b6e06a1ccb5ed84c846")]
[assembly: AssemblyProduct("POGModCheck")]
[assembly: AssemblyTitle("POGModCheck")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
[CompilerGenerated]
[Embedded]
internal sealed class EmbeddedAttribute : Attribute
{
}
}
namespace System.Runtime.CompilerServices
{
[CompilerGenerated]
[Embedded]
[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
internal sealed class RefSafetyRulesAttribute : Attribute
{
public readonly int Version;
public RefSafetyRulesAttribute(int P_0)
{
Version = P_0;
}
}
}
namespace POGMods.ModCheck
{
public sealed class ModCheckMod : MelonMod
{
public const string VERSION = "0.1.1";
private const string MessageName = "POGModCheck/List";
private const float NoAnswerAfter = 15f;
private const float WatchEvery = 1f;
internal const string RetrySentinel = "POGModCheck:choice";
private const int MaxOfferChars = 600;
private const int MaxRefusalChars = 450;
private const float PopupLostAfter = 1f;
internal static ModCheckMod Instance;
private MelonPreferences_Entry<string> _requiredCfg;
private MelonPreferences_Entry<string> _sameVersionCfg;
private MelonPreferences_Entry<bool> _showWindow;
private MelonPreferences_Entry<bool> _askBeforeJoin;
private bool _hostHook;
private bool _playerHooks;
private JoinOffer.Kind _offerSent = JoinOffer.Kind.Unchecked;
private bool _accepted;
private bool _joinedAnyway;
private ModDiff _choice;
private bool _choiceShown;
private bool _choiceInGamePopup;
private float _popupGoneSince = -1f;
private int _answer;
private bool _joinWhenShutDown;
private bool _passThrough;
private int _idleFrames;
private bool _unknownDataWarned;
private readonly ChoiceWindow _fallback = new ChoiceWindow();
private readonly ChoicePopup _popup = new ChoicePopup();
private List<ModEntry> _local;
private string _localText;
private CustomMessagingManager _registeredOn;
private HandleNamedMessageDelegate _handler;
private bool _sent;
private float _sentAt;
private bool _answered;
private bool _noAnswerReported;
private PeerWatch _peers;
private float _nextWatch;
private bool _cannotListPlayers;
private readonly ModCheckWindow _window = new ModCheckWindow();
public override void OnInitializeMelon()
{
MelonPreferences_Category val = MelonPreferences.CreateCategory("POGModCheck");
_requiredCfg = val.CreateEntry<string>("Required", "", (string)null, "Mods every player must have, besides those found by themselves (network content through POGContentLib, or marked by their authors). Names as in the MelonLoader console, comma-separated.", false, false, (ValueValidator)null, (string)null);
_sameVersionCfg = val.CreateEntry<string>("SameVersion", "", (string)null, "Mods nobody has to have, but whoever has them must run the same version as the other side (besides those marked so by their authors). Names as in the MelonLoader console, comma-separated.", false, false, (ValueValidator)null, (string)null);
_showWindow = val.CreateEntry<bool>("ShowWindow", true, (string)null, "Show the window when mods differ (the log always gets the report).", false, false, (ValueValidator)null, (string)null);
_askBeforeJoin = val.CreateEntry<bool>("AskBeforeJoin", true, (string)null, "Check mods before a player loads into a game. As the host: a joining player whose mods differ is stopped and chooses Join anyway or Cancel (that player needs POG Mod Check too). As a player: when off, you are never stopped; the report shows after joining instead.", false, false, (ValueValidator)null, (string)null);
Instance = this;
Hook();
}
private void Hook()
{
_hostHook = TryPatch(typeof(Patch_Approve));
bool flag = TryPatch(typeof(Patch_StartClient));
bool flag2 = TryPatch(typeof(Patch_LostConnection));
bool flag3 = TryPatch(typeof(Patch_ReconnectStep));
bool flag4 = TryPatch(typeof(Patch_ClientDisconnected));
TryPatch(typeof(Patch_UpdateConnectionData));
_playerHooks = flag && flag2 && flag3 && flag4;
if (!_hostHook)
{
((MelonBase)this).LoggerInstance.Warning("As the host this game cannot stop a joining player whose mods differ (the game changed); the report shows after joining.");
}
if (!_playerHooks)
{
((MelonBase)this).LoggerInstance.Warning("As a player this game cannot ask before loading (the game changed); the report shows after joining.");
}
}
private bool TryPatch(Type patch)
{
try
{
((MelonBase)this).HarmonyInstance.CreateClassProcessor(patch).Patch();
return true;
}
catch (Exception ex)
{
((MelonBase)this).LoggerInstance.Warning("Hook " + patch.Name + " not applied: " + ex.GetBaseException().Message);
return false;
}
}
public override void OnUpdate()
{
if (Input.GetKeyDown((KeyCode)291))
{
_window.Close();
}
try
{
TickJoin();
}
catch (Exception ex)
{
((MelonBase)this).LoggerInstance.Warning("Mod check before loading: " + ex.GetType().Name + ": " + ex.Message);
}
try
{
Tick();
}
catch (Exception ex2)
{
((MelonBase)this).LoggerInstance.Warning("Mod check: " + ex2.GetType().Name + ": " + ex2.Message);
ResetSession();
}
}
public override void OnGUI()
{
_window.Draw();
int num = _fallback.Draw();
if (num != 0 && _answer == 0)
{
_answer = num;
}
}
internal bool OnApproving(ConnectionApprovalRequest request, ConnectionApprovalResponse response)
{
if (request == null || response == null || !_askBeforeJoin.Value)
{
return true;
}
ulong clientNetworkId = request.ClientNetworkId;
if (clientNetworkId == NetworkManager.ServerClientId)
{
return true;
}
string text = ConnectionPayload.FindOffer(TextOf(request.Payload));
if (text == null)
{
return true;
}
if (!JoinOffer.TryParse(text, out var offer))
{
((MelonBase)this).LoggerInstance.Warning($"Player {clientNetworkId} sent a mod check this version cannot read; letting it in, the mods are compared after joining.");
return true;
}
if (offer.Mode == JoinOffer.Kind.Accept)
{
((MelonBase)this).LoggerInstance.Msg($"Player {clientNetworkId} joins without being stopped (it chose Join anyway, or it does not want the check before loading).");
return true;
}
if (offer.Mode == JoinOffer.Kind.Unchecked)
{
((MelonBase)this).LoggerInstance.Msg($"Player {clientNetworkId} has too many mods to check before loading; they are compared after joining.");
return true;
}
EnsureLocal();
if (!JoinCheck.Differs(_local, offer))
{
return true;
}
string text2 = JoinRefusal.Build(JoinRefusal.EntriesFor(_local, offer), 450);
if (text2 == null)
{
((MelonBase)this).LoggerInstance.Msg($"Player {clientNetworkId}'s mods differ, but my list is too long to send before loading; letting it in, the report shows after joining.");
return true;
}
((MelonBase)this).LoggerInstance.Msg($"Player {clientNetworkId} asks to join with different mods: not let in yet; it sees the differences and chooses Join anyway or Cancel.");
response.Approved = false;
response.Reason = text2;
response.Pending = false;
return false;
}
internal void BeforeStartClient(NetworkManager nm)
{
if (_choice != null || _joinWhenShutDown)
{
DropChoice("a new join started");
}
Stamp(nm);
((MelonBase)this).LoggerInstance.Msg((_offerSent == JoinOffer.Kind.Ask) ? $"Joining: the host may stop me before loading if required mods differ ({_local.Count} mods, {_local.Count((ModEntry m) => m.Required)} required)." : $"Joining: the host will not stop me ({_offerSent}).");
}
internal void Stamp(NetworkManager nm)
{
NetworkConfig val = ((nm != null) ? nm.NetworkConfig : null);
if (val == null)
{
return;
}
EnsureLocal();
JoinOffer.Kind mode = ((_accepted || !_askBeforeJoin.Value || !_playerHooks) ? JoinOffer.Kind.Accept : JoinOffer.Kind.Ask);
string text = JoinOffer.From(_local, mode).SerializeWithin(600);
string text2 = TextOf(val.ConnectionData);
string text3 = ConnectionPayload.WithOffer(text2, text);
if (text3 == null)
{
if (!_unknownDataWarned)
{
_unknownDataWarned = true;
((MelonBase)this).LoggerInstance.Warning("The game's connection data has a form this version does not know, so the mods are compared after joining, not before.");
}
_offerSent = JoinOffer.Kind.Unchecked;
}
else
{
_offerSent = (JoinOffer.TryParse(text, out var offer) ? offer.Mode : JoinOffer.Kind.Unchecked);
if (text3 != text2)
{
val.ConnectionData = Il2CppStructArray<byte>.op_Implicit(Encoding.UTF8.GetBytes(text3));
}
}
}
internal void OnLostConnection(NetworkHandler h, bool host)
{
if (!host && !_passThrough && !((Object)(object)h == (Object)null) && _offerSent == JoinOffer.Kind.Ask && string.IsNullOrEmpty(h.m_contentRetryKey))
{
NetworkManager obj = h.m_networkManager ?? NetworkManager.Singleton;
if (JoinRefusal.TryParse((obj != null) ? obj.DisconnectReason : null, out var entries))
{
TakeRefusal(h, entries);
}
}
}
internal bool OnClientDisconnected(NetworkHandler h, ulong clientId)
{
if (_passThrough || (Object)(object)h == (Object)null || _offerSent != JoinOffer.Kind.Ask)
{
return false;
}
NetworkManager val = h.m_networkManager ?? NetworkManager.Singleton;
if ((Object)(object)val == (Object)null || val.IsServer || clientId != val.LocalClientId)
{
return false;
}
if (!string.IsNullOrEmpty(h.m_contentRetryKey))
{
return false;
}
if (!JoinRefusal.TryParse(val.DisconnectReason, out var entries))
{
return false;
}
TakeRefusal(h, entries);
return true;
}
private void TakeRefusal(NetworkHandler h, List<ModEntry> hostMods)
{
h.m_disconnectReason = "";
EnsureLocal();
_choice = ModCompare.Compare(_local, hostMods);
_choiceShown = false;
_answer = 0;
_popupGoneSince = -1f;
h.m_contentRetryKey = "POGModCheck:choice";
List<string> list = _choice.Lines("the host");
((MelonBase)this).LoggerInstance.Msg((list.Count == 0) ? "The host stopped me before loading, but my exact comparison finds nothing that matters (a DLL hash is unknown on one side): joining." : "The host stopped me before loading; my mods differ from the host's:");
foreach (string item in list)
{
((MelonBase)this).LoggerInstance.Msg(" " + item);
}
}
internal void OnRetryTakenOver(NetworkHandler h)
{
if ((Object)(object)h != (Object)null)
{
h.m_contentReconnecting = true;
}
if (_choice != null && _choice.IsEmpty)
{
_choice = null;
_answer = 1;
}
}
private void TickJoin()
{
NetworkManager singleton = NetworkManager.Singleton;
if (_choice != null && !_choiceShown)
{
ShowChoice();
}
if (_choice != null && _choiceShown && _choiceInGamePopup && _answer == 0)
{
WatchPopup();
}
if (_answer != 0)
{
int answer = _answer;
_answer = 0;
CloseChoice();
if (answer == 1)
{
((MelonBase)this).LoggerInstance.Msg("Join anyway: connecting again, telling the host I accept the differences.");
_accepted = true;
_joinedAnyway = true;
_joinWhenShutDown = true;
}
else
{
ReturnToMenu("Cancelled: back to the menu, nothing was loaded.");
}
}
if (_joinWhenShutDown && (Object)(object)singleton != (Object)null && !singleton.ShutdownInProgress && !singleton.IsListening)
{
_joinWhenShutDown = false;
JoinAgain(singleton);
}
if ((_accepted || _joinedAnyway) && _choice == null && !_joinWhenShutDown)
{
NetworkHandler singleton2 = NetworkHandler.Singleton;
bool flag = ((Object)(object)singleton != (Object)null && singleton.IsListening) || ((Object)(object)singleton2 != (Object)null && singleton2.m_contentReconnecting);
_idleFrames = ((!flag) ? (_idleFrames + 1) : 0);
if (_idleFrames > 2)
{
_accepted = false;
_joinedAnyway = false;
_idleFrames = 0;
}
}
}
private void ShowChoice()
{
_choiceShown = true;
ModTable table = ModTable.ForPlayer(_choice);
try
{
Action<PopupButtonFlag> answer = OnPopupButton;
if (_popup.Show("Your mods differ from the host's.\nJoin anyway?", table, answer, delegate(string w)
{
((MelonBase)this).LoggerInstance.Warning(w);
}))
{
_choiceInGamePopup = true;
((MelonBase)this).LoggerInstance.Msg("Asking the player: Join anyway or Cancel (the game's popup).");
return;
}
}
catch (Exception ex)
{
((MelonBase)this).LoggerInstance.Warning("The game's popup failed (" + ex.Message + "); using my own window.");
_popup.Close();
}
_choiceInGamePopup = false;
_fallback.Show("Your mods differ from the host's.\nJoin anyway?", table);
((MelonBase)this).LoggerInstance.Msg("Asking the player: Join anyway or Cancel (my own window; Enter joins, Esc cancels).");
}
private void OnPopupButton(PopupButtonFlag button)
{
//IL_0009: Unknown result type (might be due to invalid IL or missing references)
//IL_000c: Invalid comparison between Unknown and I4
if (_answer == 0)
{
_answer = (((int)button == 16) ? 1 : 2);
}
}
private void WatchPopup()
{
if (_popup.StillOurs)
{
_popupGoneSince = -1f;
return;
}
if (_popup.Replaced)
{
_popup.Close();
}
if (_popupGoneSince < 0f)
{
_popupGoneSince = Time.unscaledTime;
}
else if (Time.unscaledTime - _popupGoneSince > 1f)
{
((MelonBase)this).LoggerInstance.Msg("The popup closed without an answer: taking it as Cancel.");
_answer = 2;
}
}
private void CloseChoice()
{
_choice = null;
_choiceShown = false;
_popupGoneSince = -1f;
_popup.Close();
_fallback.Close();
}
private void DropChoice(string why)
{
if (_choiceInGamePopup && _choiceShown)
{
_popup.Hide();
}
CloseChoice();
_answer = 0;
_joinWhenShutDown = false;
NetworkHandler singleton = NetworkHandler.Singleton;
if ((Object)(object)singleton != (Object)null)
{
singleton.m_contentReconnecting = false;
}
((MelonBase)this).LoggerInstance.Msg("The open question was dropped: " + why + ".");
}
private void JoinAgain(NetworkManager nm)
{
NetworkHandler singleton = NetworkHandler.Singleton;
if ((Object)(object)singleton == (Object)null)
{
ReturnToMenu("Cannot join again: the game's network handler is gone.");
return;
}
singleton.m_contentReconnecting = false;
singleton.m_contentRetried = false;
singleton.EnsureNetworkPrefabsRegistered();
if (!nm.StartClient())
{
ReturnToMenu("The game did not start the client again: back to the menu.");
}
}
private void ReturnToMenu(string why)
{
_accepted = false;
_joinedAnyway = false;
_joinWhenShutDown = false;
((MelonBase)this).LoggerInstance.Msg(why);
NetworkHandler singleton = NetworkHandler.Singleton;
if ((Object)(object)singleton == (Object)null)
{
return;
}
singleton.m_contentReconnecting = false;
singleton.m_disconnectReason = "";
ServicesEOS onlineService = singleton.m_onlineService;
Action<string, string> onConnectionFailed = null;
if (onlineService != null)
{
onConnectionFailed = onlineService.OnConnectionFailed;
onlineService.OnConnectionFailed = null;
}
_passThrough = true;
try
{
singleton.m_contentRetryKey = null;
singleton.m_contentRetried = true;
singleton.OnLostConnection(false);
}
finally
{
_passThrough = false;
if (onlineService != null)
{
onlineService.OnConnectionFailed = onConnectionFailed;
}
}
try
{
singleton.m_callback?.Invoke(false);
}
catch (Exception ex)
{
((MelonBase)this).LoggerInstance.Warning("The join's callback: " + ex.Message);
}
}
private static string TextOf(Il2CppStructArray<byte> data)
{
if (data == null)
{
return "";
}
byte[] array = new byte[((Il2CppArrayBase<byte>)(object)data).Length];
for (int i = 0; i < array.Length; i++)
{
array[i] = ((Il2CppArrayBase<byte>)(object)data)[i];
}
return Encoding.UTF8.GetString(array);
}
private void Tick()
{
NetworkManager singleton = NetworkManager.Singleton;
if ((Object)(object)singleton == (Object)null || !singleton.IsListening)
{
if (_registeredOn != null || _sent || _peers != null)
{
ResetSession();
}
return;
}
CustomMessagingManager customMessagingManager = singleton.CustomMessagingManager;
if (customMessagingManager == null)
{
return;
}
if (_registeredOn == null || ((Il2CppObjectBase)_registeredOn).Pointer != ((Il2CppObjectBase)customMessagingManager).Pointer)
{
if ((Delegate)(object)_handler == (Delegate)null)
{
Action<ulong, FastBufferReader> action = OnMessage;
_handler = HandleNamedMessageDelegate.op_Implicit(action);
}
customMessagingManager.RegisterNamedMessageHandler("POGModCheck/List", _handler);
_registeredOn = customMessagingManager;
EnsureLocal();
}
if (singleton.IsServer)
{
WatchPlayers(singleton);
return;
}
if (singleton.IsConnectedClient && !_sent)
{
Send(customMessagingManager, NetworkManager.ServerClientId);
_sent = true;
_sentAt = Time.unscaledTime;
((MelonBase)this).LoggerInstance.Msg($"Sent my mod list to the host ({_local.Count} mods, {_local.Count((ModEntry m) => m.Required)} required).");
}
if (_sent && !_answered && !_noAnswerReported && Time.unscaledTime - _sentAt > 15f)
{
_noAnswerReported = true;
((MelonBase)this).LoggerInstance.Msg("The host did not answer the mod check: it has no POG Mod Check (or it is too old). Nothing to compare.");
ShowSilence("Mod check", "The host did not answer the mod check (no POG Mod Check there?).");
}
}
private void WatchPlayers(NetworkManager nm)
{
float unscaledTime = Time.unscaledTime;
if (unscaledTime < _nextWatch)
{
return;
}
_nextWatch = unscaledTime + 1f;
List<ulong> list = ConnectedIds(nm);
if (list == null)
{
return;
}
Peers().Present(list, unscaledTime);
foreach (ulong item in Peers().Overdue(unscaledTime))
{
((MelonBase)this).LoggerInstance.Msg($"Player {item} sent no mod list in {15f:0} s: it has no POG Mod Check (or it is too old), so its mods cannot be compared.");
ShowSilence($"Player {item}: no mod check", $"Player {item} sent no mod list (no POG Mod Check there?).");
}
}
private List<ulong> ConnectedIds(NetworkManager nm)
{
IReadOnlyList<ulong> connectedClientsIds = nm.ConnectedClientsIds;
List<ulong> val = ((connectedClientsIds != null) ? ((Il2CppObjectBase)connectedClientsIds).TryCast<List<ulong>>() : null);
if (val == null)
{
if (!_cannotListPlayers)
{
_cannotListPlayers = true;
((MelonBase)this).LoggerInstance.Warning("Cannot read the list of joined players: a player without POG Mod Check will not be reported.");
}
return null;
}
List<ulong> list = new List<ulong>(val.Count);
for (int i = 0; i < val.Count; i++)
{
list.Add(val[i]);
}
return list;
}
private PeerWatch Peers()
{
return _peers ?? (_peers = new PeerWatch(NetworkManager.ServerClientId, 15f));
}
private void ShowSilence(string title, string first)
{
List<string> list = (from m in _local?.Where((ModEntry m) => m.Required)
select m.Id).ToList() ?? new List<string>();
if (list.Count != 0 && _showWindow.Value)
{
_window.Show(title, new List<string>
{
first,
"You run mods every player needs: " + string.Join(", ", list) + "."
});
}
}
private void ResetSession()
{
_registeredOn = null;
_sent = false;
_answered = false;
_noAnswerReported = false;
_peers = null;
_nextWatch = 0f;
}
private void OnMessage(ulong sender, FastBufferReader reader)
{
//IL_003a: Unknown result type (might be due to invalid IL or missing references)
try
{
NetworkManager singleton = NetworkManager.Singleton;
bool flag = (Object)(object)singleton != (Object)null && singleton.IsServer;
if (flag)
{
Peers().Answered(sender);
}
if (!ModListCodec.TryParse(ReadText(reader), out var mods))
{
((MelonBase)this).LoggerInstance.Warning("Unreadable mod list from " + ((sender == NetworkManager.ServerClientId) ? "the host" : $"player {sender}") + ".");
return;
}
EnsureLocal();
if (flag)
{
Send(singleton.CustomMessagingManager, sender);
Report($"player {sender}", mods, $"Player {sender} joined with different mods", (ModDiff d) => ModTable.ForHost(d, $"Player {sender}"));
}
else if (sender == NetworkManager.ServerClientId)
{
_answered = true;
Report("the host", mods, "Your mods differ from the host's", ModTable.ForPlayer, !_joinedAnyway);
}
}
catch (Exception ex)
{
((MelonBase)this).LoggerInstance.Warning($"Mod list from {sender}: {ex.GetType().Name}: {ex.Message}");
}
}
private void Report(string other, List<ModEntry> theirs, string title, Func<ModDiff, ModTable> table, bool window = true)
{
ModDiff modDiff = ModCompare.Compare(_local, theirs);
if (modDiff.IsEmpty)
{
((MelonBase)this).LoggerInstance.Msg($"Mods match {other} ({theirs.Count} mods there, {theirs.Count((ModEntry m) => m.Required)} required).");
return;
}
List<string> list = modDiff.Lines(other);
((MelonBase)this).LoggerInstance.Msg(title + ":");
foreach (string item in list)
{
((MelonBase)this).LoggerInstance.Msg(" " + item);
}
if (_showWindow.Value && window)
{
_window.Show(title, table(modDiff));
}
}
private void Send(CustomMessagingManager cmm, ulong to)
{
//IL_006b: Unknown result type (might be due to invalid IL or missing references)
if (cmm == null)
{
return;
}
byte[] bytes = Encoding.UTF8.GetBytes(_localText);
FastBufferWriter val = default(FastBufferWriter);
((FastBufferWriter)(ref val))..ctor(bytes.Length + 4, (Allocator)2, -1);
try
{
for (int i = 0; i < 4; i++)
{
((FastBufferWriter)(ref val)).WriteByteSafe((byte)(bytes.Length >> 8 * i));
}
byte[] array = bytes;
foreach (byte b in array)
{
((FastBufferWriter)(ref val)).WriteByteSafe(b);
}
cmm.SendNamedMessage("POGModCheck/List", to, val, (NetworkDelivery)4);
}
finally
{
((FastBufferWriter)(ref val)).Dispose();
}
}
private static string ReadText(FastBufferReader r)
{
int num = 0;
byte b = default(byte);
for (int i = 0; i < 4; i++)
{
((FastBufferReader)(ref r)).ReadByteSafe(ref b);
num |= b << 8 * i;
}
if (num < 0 || num > 65536 || num > ((FastBufferReader)(ref r)).Length - ((FastBufferReader)(ref r)).Position)
{
return null;
}
byte[] array = new byte[num];
byte b2 = default(byte);
for (int j = 0; j < num; j++)
{
((FastBufferReader)(ref r)).ReadByteSafe(ref b2);
array[j] = b2;
}
return Encoding.UTF8.GetString(array);
}
private void EnsureLocal()
{
if (_local != null)
{
return;
}
HashSet<string> hashSet = ContentAssemblies();
HashSet<string> names = Names(_requiredCfg.Value);
HashSet<string> names2 = Names(_sameVersionCfg.Value);
_local = new List<ModEntry>();
List<string> list = new List<string>();
List<string> list2 = new List<string>();
foreach (MelonBase item in MelonTypeBase<MelonMod>.RegisteredMelons.Cast<MelonBase>().Concat((IEnumerable<MelonBase>)MelonTypeBase<MelonPlugin>.RegisteredMelons))
{
MelonBase melon = item;
MelonAssembly melonAssembly = melon.MelonAssembly;
Assembly assembly = ((melonAssembly != null) ? melonAssembly.Assembly : null);
string asmName = assembly?.GetName().Name ?? "";
string unknownValue;
ModMarker.Mark mark = ModMarker.Read(assembly, out unknownValue);
if (mark == ModMarker.Mark.Unknown)
{
((MelonBase)this).LoggerInstance.Warning($"{melon.Info.Name} marks itself \"{"POGModCheck"}\" = \"{unknownValue}\"; only \"{"required"}\" and \"{"same-version"}\" are known here, so the mark is ignored.");
}
ModNeed modNeed = ModNeed.Required;
string text;
if (hashSet.Contains(asmName))
{
text = "network content through POGContentLib";
}
else if (mark == ModMarker.Mark.Required)
{
text = "its author marks it";
}
else if (Listed(names))
{
text = "your config";
}
else
{
modNeed = ModNeed.SameVersion;
text = ((mark == ModMarker.Mark.SameVersion) ? "its author marks it" : (Listed(names2) ? "your config" : null));
if (text == null)
{
modNeed = ModNeed.OwnOnly;
}
}
switch (modNeed)
{
case ModNeed.Required:
list.Add(melon.Info.Name + " (" + text + ")");
break;
case ModNeed.SameVersion:
list2.Add(melon.Info.Name + " (" + text + ")");
break;
}
_local.Add(new ModEntry(melon.Info.Name, melon.Info.Version, HashOf(assembly), modNeed));
bool Listed(HashSet<string> hashSet2)
{
if (!hashSet2.Contains(ModEntry.KeyOf(melon.Info.Name)))
{
return hashSet2.Contains(ModEntry.KeyOf(asmName));
}
return true;
}
}
_localText = ModListCodec.Serialize(_local);
((MelonBase)this).LoggerInstance.Msg("My mods: " + string.Join("; ", _local));
((MelonBase)this).LoggerInstance.Msg((list.Count > 0) ? ("Every player needs: " + string.Join("; ", list) + ".") : "None of my mods is one every player needs.");
if (list2.Count > 0)
{
((MelonBase)this).LoggerInstance.Msg("Whoever has them needs the same version: " + string.Join("; ", list2) + ".");
}
}
private static HashSet<string> Names(string csv)
{
return new HashSet<string>(from k in (csv ?? "").Split(',').Select(ModEntry.KeyOf)
where k.Length > 0
select k);
}
private HashSet<string> ContentAssemblies()
{
HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
try
{
Type type = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((Assembly a) => a.GetName().Name == "POGContentLib")?.GetType("POGContentLib.Items.Content");
if (type == null)
{
return hashSet;
}
if (type.GetProperty("ContentAssemblies", BindingFlags.Static | BindingFlags.Public)?.GetValue(null) is IEnumerable<string> enumerable)
{
foreach (string item in enumerable)
{
hashSet.Add(item);
}
return hashSet;
}
object obj = type.GetProperty("Parity", BindingFlags.Static | BindingFlags.Public)?.GetValue(null);
object obj2 = obj?.GetType().GetProperty("LocalManifest")?.GetValue(obj);
if (obj2?.GetType().GetProperty("Entries")?.GetValue(obj2) is IEnumerable enumerable2)
{
HashSet<string> hashSet2 = new HashSet<string>();
foreach (object item2 in enumerable2)
{
string text = item2?.GetType().GetProperty("FullId")?.GetValue(item2) as string;
if (!string.IsNullOrEmpty(text))
{
hashSet2.Add(ModEntry.KeyOf(text.Split(':')[0]));
}
}
if (hashSet2.Count > 0)
{
hashSet.Add("POGContentLib");
}
foreach (MelonMod registeredMelon in MelonTypeBase<MelonMod>.RegisteredMelons)
{
MelonAssembly melonAssembly = ((MelonBase)registeredMelon).MelonAssembly;
string text2 = ((melonAssembly == null) ? null : melonAssembly.Assembly?.GetName().Name) ?? "";
if (hashSet2.Contains(ModEntry.KeyOf(text2)) || hashSet2.Contains(ModEntry.KeyOf(((MelonBase)registeredMelon).Info.Name)))
{
hashSet.Add(text2);
}
}
}
}
catch (Exception ex)
{
((MelonBase)this).LoggerInstance.Warning("Reading POGContentLib's content list: " + ex.Message);
}
return hashSet;
}
private static string HashOf(Assembly asm)
{
try
{
string text = asm?.Location;
if (string.IsNullOrEmpty(text) || !File.Exists(text))
{
return "";
}
using SHA256 sHA = SHA256.Create();
return BitConverter.ToString(sHA.ComputeHash(File.ReadAllBytes(text)), 0, 6).Replace("-", "").ToLowerInvariant();
}
catch
{
return "";
}
}
}
internal sealed class TableGui
{
public const float RowHeight = 22f;
public const int MaxRows = 10;
private GUIStyle _cell;
private GUIStyle _dim;
private GUIStyle _absent;
private GUIStyle _changed;
public static int LinesOf(ModTable t)
{
return 1 + Math.Min(t.Rows.Count, 10) + ((t.Rows.Count > 10) ? 1 : 0);
}
public float Height(ModTable t)
{
return (float)LinesOf(t) * 22f;
}
public float Draw(ModTable t, float x, float y, float w)
{
//IL_010c: Unknown result type (might be due to invalid IL or missing references)
//IL_0129: Unknown result type (might be due to invalid IL or missing references)
//IL_0147: Unknown result type (might be due to invalid IL or missing references)
//IL_0016: Unknown result type (might be due to invalid IL or missing references)
//IL_001b: Unknown result type (might be due to invalid IL or missing references)
//IL_0023: Unknown result type (might be due to invalid IL or missing references)
//IL_002a: Unknown result type (might be due to invalid IL or missing references)
//IL_0036: Expected O, but got Unknown
//IL_003d: Unknown result type (might be due to invalid IL or missing references)
//IL_0047: Expected O, but got Unknown
//IL_0061: Unknown result type (might be due to invalid IL or missing references)
//IL_0072: Unknown result type (might be due to invalid IL or missing references)
//IL_0077: Unknown result type (might be due to invalid IL or missing references)
//IL_0083: Expected O, but got Unknown
//IL_009d: Unknown result type (might be due to invalid IL or missing references)
//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
//IL_00b8: Expected O, but got Unknown
//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
//IL_024b: Unknown result type (might be due to invalid IL or missing references)
if (_cell == null)
{
_cell = new GUIStyle(GUI.skin.label)
{
fontSize = 15,
wordWrap = false,
clipping = (TextClipping)1
};
_dim = new GUIStyle(_cell);
_dim.normal.textColor = new Color(0.65f, 0.65f, 0.65f);
_absent = new GUIStyle(_cell)
{
fontStyle = (FontStyle)1
};
_absent.normal.textColor = new Color(1f, 0.42f, 0.38f);
_changed = new GUIStyle(_cell);
_changed.normal.textColor = new Color(1f, 0.78f, 0.4f);
}
float num = w * 0.48f;
float num2 = w * 0.25f;
float num3 = x + w * 0.5f;
float num4 = x + w * 0.75f;
GUI.Label(new Rect(x, y, num, 22f), "Mod", _dim);
GUI.Label(new Rect(num3, y, num2, 22f), t.HostHeader, _dim);
GUI.Label(new Rect(num4, y, num2, 22f), t.PlayerHeader, _dim);
y += 22f;
int num5 = ((t.Rows.Count > 10) ? 10 : t.Rows.Count);
foreach (ModTable.Row item in t.Rows.Take(num5))
{
GUI.Label(new Rect(x, y, num, 22f), item.Name, _cell);
GUI.Label(new Rect(num3, y, num2, 22f), item.Host, StyleOf(item.Host));
GUI.Label(new Rect(num4, y, num2, 22f), item.Player, StyleOf(item.Player));
y += 22f;
}
if (t.Rows.Count > num5)
{
GUI.Label(new Rect(x, y, w, 22f), $"+{t.Rows.Count - num5} more (see the log)", _dim);
y += 22f;
}
return y;
}
private GUIStyle StyleOf(string cell)
{
if (!(cell == "—"))
{
return _changed;
}
return _absent;
}
}
internal sealed class ModCheckWindow
{
private sealed class Report
{
public string Title;
public List<string> Lines;
public ModTable Table;
}
private const int MaxReports = 4;
private readonly List<Report> _reports = new List<Report>();
private readonly TableGui _table = new TableGui();
private GUIStyle _text;
private GUIStyle _head;
public void Show(string title, List<string> lines)
{
Add(new Report
{
Title = title,
Lines = (lines ?? new List<string>())
});
}
public void Show(string title, ModTable table)
{
Add(new Report
{
Title = title,
Lines = new List<string>(),
Table = table
});
}
private void Add(Report r)
{
_reports.RemoveAll((Report x) => x.Title == r.Title);
_reports.Add(r);
while (_reports.Count > 4)
{
_reports.RemoveAt(0);
}
}
public void Close()
{
_reports.Clear();
}
public void Draw()
{
//IL_0021: Unknown result type (might be due to invalid IL or missing references)
//IL_0026: Unknown result type (might be due to invalid IL or missing references)
//IL_002d: Unknown result type (might be due to invalid IL or missing references)
//IL_003a: Expected O, but got Unknown
//IL_0045: Unknown result type (might be due to invalid IL or missing references)
//IL_004a: Unknown result type (might be due to invalid IL or missing references)
//IL_0052: Unknown result type (might be due to invalid IL or missing references)
//IL_005e: Expected O, but got Unknown
//IL_0078: Unknown result type (might be due to invalid IL or missing references)
//IL_0187: Unknown result type (might be due to invalid IL or missing references)
//IL_019b: Unknown result type (might be due to invalid IL or missing references)
//IL_0105: Unknown result type (might be due to invalid IL or missing references)
//IL_0110: Expected O, but got Unknown
//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
//IL_02d8: Unknown result type (might be due to invalid IL or missing references)
//IL_030a: Unknown result type (might be due to invalid IL or missing references)
//IL_021f: Unknown result type (might be due to invalid IL or missing references)
//IL_022a: Expected O, but got Unknown
//IL_0238: Unknown result type (might be due to invalid IL or missing references)
if (_reports.Count == 0)
{
return;
}
if (_text == null)
{
_text = new GUIStyle(GUI.skin.label)
{
wordWrap = true,
fontSize = 15
};
_head = new GUIStyle(GUI.skin.label)
{
fontSize = 18,
fontStyle = (FontStyle)1
};
_head.normal.textColor = new Color(1f, 0.82f, 0.35f);
}
float num = Mathf.Min(560f, (float)Screen.width - 32f);
float num2 = (float)Screen.width - num - 16f;
float num3 = 16f;
float num4 = num - 24f;
float num5 = 8f;
foreach (Report report in _reports)
{
num5 += 30f;
foreach (string line in report.Lines)
{
num5 += _text.CalcHeight(new GUIContent(line), num4) + 2f;
}
if (report.Table != null)
{
num5 += _table.Height(report.Table);
}
num5 += 6f;
}
num5 += 40f;
GUI.Box(new Rect(num2, num3, num, num5), "");
GUI.Box(new Rect(num2, num3, num, num5), "");
float num6 = num3 + 6f;
foreach (Report report2 in _reports)
{
GUI.Label(new Rect(num2 + 12f, num6, num4, 26f), report2.Title, _head);
num6 += 30f;
foreach (string line2 in report2.Lines)
{
float num7 = _text.CalcHeight(new GUIContent(line2), num4);
GUI.Label(new Rect(num2 + 12f, num6, num4, num7), line2, _text);
num6 += num7 + 2f;
}
if (report2.Table != null)
{
num6 = _table.Draw(report2.Table, num2 + 12f, num6, num4);
}
num6 += 6f;
}
if (GUI.Button(new Rect(num2 + num - 132f, num6 + 4f, 120f, 28f), "Close (F10)"))
{
Close();
}
GUI.Label(new Rect(num2 + 12f, num6 + 8f, num - 160f, 24f), "The game goes on; the log has the details.", _text);
}
}
internal sealed class ChoicePopup
{
private const float Width = 470f;
private const float Padding = 20f;
private const float FontSize = 12.5f;
private const string TableFont = "Roboto-Medium SDF";
private const string ObjectName = "POGModCheck Table";
private const int Rows = 6;
private static readonly ModTable.RichStyle Style = new ModTable.RichStyle();
private NetworkMenuPopup _shownOn;
private string _question;
private RectTransform _window;
private Vector2 _windowSize;
private GameObject _table;
private GameObject _error;
private bool _errorWasActive;
private static TMP_FontAsset _font;
public bool StillOurs
{
get
{
try
{
return (Object)(object)_shownOn != (Object)null && _shownOn.IsShowing && _shownOn.m_messageText.text == _question;
}
catch
{
return false;
}
}
}
public bool Replaced
{
get
{
try
{
return (Object)(object)_shownOn != (Object)null && _shownOn.IsShowing && _shownOn.m_messageText.text != _question;
}
catch
{
return false;
}
}
}
public bool Show(string question, ModTable table, Action<PopupButtonFlag> answer, Action<string> warn)
{
Close();
NetworkMenuPopup val = null;
try
{
NetworkMenu instance = NetworkMenu.Instance;
val = ((instance != null) ? instance.Popup : null);
}
catch
{
}
if ((Object)(object)val == (Object)null)
{
return false;
}
val.ShowPopup(question, "Join", (PopupButtonFlag)24, Action<PopupButtonFlag>.op_Implicit(answer), false, false, "");
_shownOn = val;
_question = question;
try
{
Fit(val, table);
}
catch (Exception ex)
{
warn($"The table did not fit the game's popup ({ex.GetType().Name}: {ex.Message}); a short line instead.");
Restore();
try
{
val.m_errorText.text = string.Join("; ", from r in table.Rows.Take(2)
select $"{r.Name}: host {r.Host}, you {r.Player}");
}
catch
{
}
}
return true;
}
private void Fit(NetworkMenuPopup popup, ModTable table)
{
//IL_001f: Unknown result type (might be due to invalid IL or missing references)
//IL_0024: Unknown result type (might be due to invalid IL or missing references)
//IL_0045: Unknown result type (might be due to invalid IL or missing references)
//IL_004b: Expected O, but got Unknown
//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
//IL_0115: Unknown result type (might be due to invalid IL or missing references)
//IL_017d: Unknown result type (might be due to invalid IL or missing references)
TMP_Text errorText = popup.m_errorText;
_window = popup.m_window.GetComponent<RectTransform>();
_windowSize = _window.sizeDelta;
LayoutElement component = ((Component)errorText).GetComponent<LayoutElement>();
float num = ((component != null) ? component.preferredHeight : 32f);
GameObject val = new GameObject("POGModCheck Table");
val.transform.SetParent(errorText.transform.parent, false);
val.transform.SetSiblingIndex(errorText.transform.GetSiblingIndex() + 1);
_table = val;
TextMeshProUGUI obj = val.AddComponent<TextMeshProUGUI>();
((TMP_Text)obj).font = FontOr(errorText.font);
((TMP_Text)obj).fontSize = 12.5f;
((TMP_Text)obj).fontStyle = (FontStyles)0;
((TMP_Text)obj).enableWordWrapping = false;
((TMP_Text)obj).overflowMode = (TextOverflowModes)0;
((TMP_Text)obj).richText = true;
((TMP_Text)obj).alignment = (TextAlignmentOptions)257;
((Graphic)obj).color = Color.white;
((Graphic)obj).raycastTarget = false;
string text = (((TMP_Text)obj).text = table.RichText(6, Style));
float num2 = Math.Max(_windowSize.x, 470f);
float num3 = ((TMP_Text)obj).GetPreferredValues(text, num2 - 20f, 0f).y + 6f;
LayoutElement obj2 = val.AddComponent<LayoutElement>();
obj2.preferredHeight = num3;
obj2.minHeight = num3;
_error = ((Component)errorText).gameObject;
_errorWasActive = _error.activeSelf;
_error.SetActive(false);
_window.sizeDelta = new Vector2(num2, _windowSize.y - num + num3);
}
private static TMP_FontAsset FontOr(TMP_FontAsset fallback)
{
if ((Object)(object)_font == (Object)null)
{
try
{
_font = ((IEnumerable<TMP_FontAsset>)Resources.FindObjectsOfTypeAll<TMP_FontAsset>()).FirstOrDefault((Func<TMP_FontAsset, bool>)((TMP_FontAsset f) => (Object)(object)f != (Object)null && ((Object)f).name == "Roboto-Medium SDF"));
}
catch
{
}
}
return _font ?? fallback;
}
private void Restore()
{
//IL_0059: Unknown result type (might be due to invalid IL or missing references)
try
{
if ((Object)(object)_table != (Object)null)
{
Object.Destroy((Object)(object)_table);
}
}
catch
{
}
try
{
if ((Object)(object)_error != (Object)null)
{
_error.SetActive(_errorWasActive);
}
}
catch
{
}
try
{
if ((Object)(object)_window != (Object)null)
{
_window.sizeDelta = _windowSize;
}
}
catch
{
}
_table = null;
_error = null;
_window = null;
}
public void Close()
{
Restore();
_shownOn = null;
_question = null;
}
public void Hide()
{
try
{
if (StillOurs)
{
_shownOn.HidePopup();
}
}
catch
{
}
Close();
}
}
internal sealed class ChoiceWindow
{
private string _question;
private ModTable _tableData;
private readonly TableGui _table = new TableGui();
private GUIStyle _style;
public void Show(string question, ModTable table)
{
_question = question;
_tableData = table;
}
public void Close()
{
_question = null;
_tableData = null;
}
public int Draw()
{
//IL_0014: Unknown result type (might be due to invalid IL or missing references)
//IL_001a: Invalid comparison between Unknown and I4
//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
//IL_00af: Expected O, but got Unknown
//IL_0060: Unknown result type (might be due to invalid IL or missing references)
//IL_0065: Unknown result type (might be due to invalid IL or missing references)
//IL_006c: Unknown result type (might be due to invalid IL or missing references)
//IL_0079: Expected O, but got Unknown
//IL_001d: Unknown result type (might be due to invalid IL or missing references)
//IL_0024: Invalid comparison between Unknown and I4
//IL_0027: Unknown result type (might be due to invalid IL or missing references)
//IL_0031: Invalid comparison between Unknown and I4
//IL_010c: Unknown result type (might be due to invalid IL or missing references)
//IL_0122: Unknown result type (might be due to invalid IL or missing references)
//IL_0143: Unknown result type (might be due to invalid IL or missing references)
//IL_003c: Unknown result type (might be due to invalid IL or missing references)
//IL_0043: Invalid comparison between Unknown and I4
//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
if (_question == null)
{
return 0;
}
Event current = Event.current;
if (current != null && (int)current.type == 4)
{
if ((int)current.keyCode == 13 || (int)current.keyCode == 271)
{
Close();
return 1;
}
if ((int)current.keyCode == 27)
{
Close();
return 2;
}
}
if (_style == null)
{
_style = new GUIStyle(GUI.skin.label)
{
wordWrap = true,
fontSize = 16
};
}
float num = Mathf.Min(620f, (float)Screen.width - 32f);
float num2 = num - 32f;
float num3 = _style.CalcHeight(new GUIContent(_question), num2);
float num4 = ((_tableData != null) ? (_table.Height(_tableData) + 8f) : 0f);
float num5 = num3 + num4 + 76f;
float num6 = ((float)Screen.width - num) / 2f;
float num7 = ((float)Screen.height - num5) / 2f;
GUI.Box(new Rect(num6, num7, num, num5), "POG Mod Check");
GUI.Box(new Rect(num6, num7, num, num5), "");
GUI.Label(new Rect(num6 + 16f, num7 + 24f, num2, num3), _question, _style);
if (_tableData != null)
{
_table.Draw(_tableData, num6 + 16f, num7 + 24f + num3 + 8f, num2);
}
if (GUI.Button(new Rect(num6 + num - 292f, num7 + num5 - 40f, 132f, 28f), "Join anyway"))
{
Close();
return 1;
}
if (GUI.Button(new Rect(num6 + num - 148f, num7 + num5 - 40f, 132f, 28f), "Cancel"))
{
Close();
return 2;
}
return 0;
}
}
[HarmonyPatch(typeof(NetworkHandler), "OnApprovingConnection")]
internal static class Patch_Approve
{
private static bool Prefix(ConnectionApprovalRequest request, ConnectionApprovalResponse response)
{
try
{
return ModCheckMod.Instance?.OnApproving(request, response) ?? true;
}
catch (Exception ex)
{
MelonLogger.Warning($"[POG Mod Check] Approving a join: {ex.GetType().Name}: {ex.Message}; letting it in.");
return true;
}
}
}
[HarmonyPatch(typeof(NetworkManager), "StartClient")]
internal static class Patch_StartClient
{
private static void Prefix(NetworkManager __instance)
{
try
{
ModCheckMod.Instance?.BeforeStartClient(__instance);
}
catch (Exception ex)
{
MelonLogger.Warning("[POG Mod Check] Before joining: " + ex.GetType().Name + ": " + ex.Message);
}
}
}
[HarmonyPatch(typeof(NetworkContent), "UpdateConnectionData")]
internal static class Patch_UpdateConnectionData
{
private static void Postfix()
{
try
{
ModCheckMod.Instance?.Stamp(NetworkManager.Singleton);
}
catch (Exception ex)
{
MelonLogger.Warning("[POG Mod Check] Connection data: " + ex.GetType().Name + ": " + ex.Message);
}
}
}
[HarmonyPatch(typeof(NetworkHandler), "OnLostConnection")]
internal static class Patch_LostConnection
{
private static void Prefix(NetworkHandler __instance, bool host)
{
try
{
ModCheckMod.Instance?.OnLostConnection(__instance, host);
}
catch (Exception ex)
{
MelonLogger.Warning("[POG Mod Check] Lost connection: " + ex.GetType().Name + ": " + ex.Message);
}
}
}
[HarmonyPatch(typeof(NetworkHandler), "OnClientDisconnected")]
internal static class Patch_ClientDisconnected
{
private static bool Prefix(NetworkHandler __instance, ulong clientID)
{
try
{
return !(ModCheckMod.Instance?.OnClientDisconnected(__instance, clientID) ?? false);
}
catch (Exception ex)
{
MelonLogger.Warning("[POG Mod Check] Client disconnected: " + ex.GetType().Name + ": " + ex.Message);
return true;
}
}
}
[HarmonyPatch(typeof(_ReconnectWithContent_d__116), "MoveNext")]
internal static class Patch_ReconnectStep
{
private static bool Prefix(_ReconnectWithContent_d__116 __instance, ref bool __result)
{
try
{
if (__instance.contentKey != "POGModCheck:choice")
{
return true;
}
__instance.__1__state = -1;
__result = false;
ModCheckMod.Instance?.OnRetryTakenOver(__instance.__4__this);
return false;
}
catch (Exception ex)
{
MelonLogger.Warning("[POG Mod Check] Taking over the retry: " + ex.GetType().Name + ": " + ex.Message);
return true;
}
}
}
public enum ModNeed
{
OwnOnly,
SameVersion,
Required
}
public sealed class ModEntry
{
public string Id { get; }
public string Version { get; }
public string Hash { get; }
public ModNeed Need { get; }
public bool Required => Need == ModNeed.Required;
public bool Compared => Need != ModNeed.OwnOnly;
public string Key => KeyOf(Id);
public ModEntry(string id, string version, string hash, ModNeed need)
{
Id = id ?? "";
Version = version ?? "";
Hash = hash ?? "";
Need = need;
}
public ModEntry(string id, string version, string hash, bool required)
: this(id, version, hash, required ? ModNeed.Required : ModNeed.OwnOnly)
{
}
public static string KeyOf(string id)
{
if (string.IsNullOrEmpty(id))
{
return "";
}
StringBuilder stringBuilder = new StringBuilder(id.Length);
foreach (char c in id)
{
if (char.IsLetterOrDigit(c))
{
stringBuilder.Append(char.ToLowerInvariant(c));
}
}
return stringBuilder.ToString();
}
public override string ToString()
{
return Id + " " + Version + ((Hash.Length > 0) ? (" (" + Hash + ")") : "") + ((Need == ModNeed.Required) ? " [required]" : ((Need == ModNeed.SameVersion) ? " [same version]" : ""));
}
}
public static class ModListCodec
{
public const string Magic = "POGMC1";
public static string Serialize(IEnumerable<ModEntry> mods)
{
StringBuilder stringBuilder = new StringBuilder("POGMC1");
foreach (ModEntry item in mods ?? Enumerable.Empty<ModEntry>())
{
stringBuilder.Append('\n').Append(Clean(item.Id)).Append('\t')
.Append(Clean(item.Version))
.Append('\t')
.Append(Clean(item.Hash))
.Append('\t')
.Append(Flag(item.Need));
}
return stringBuilder.ToString();
}
public static bool TryParse(string text, out List<ModEntry> mods)
{
mods = new List<ModEntry>();
if (string.IsNullOrEmpty(text))
{
return false;
}
string[] array = text.Split('\n');
if (array[0] != "POGMC1")
{
return false;
}
for (int i = 1; i < array.Length; i++)
{
if (array[i].Length != 0)
{
string[] array2 = array[i].Split('\t');
if (array2.Length != 4 || array2[0].Length == 0 || array2[3].Length != 1 || !TryNeed(array2[3][0], out var need))
{
return false;
}
mods.Add(new ModEntry(array2[0], array2[1], array2[2], need));
}
}
return true;
}
private static char Flag(ModNeed n)
{
return n switch
{
ModNeed.SameVersion => '2',
ModNeed.Required => '1',
_ => '0',
};
}
private static bool TryNeed(char c, out ModNeed need)
{
need = c switch
{
'2' => ModNeed.SameVersion,
'1' => ModNeed.Required,
_ => ModNeed.OwnOnly,
};
if (c != '0' && c != '1')
{
return c == '2';
}
return true;
}
private static string Clean(string s)
{
return (s ?? "").Replace('\t', ' ').Replace('\n', ' ').Replace('\r', ' ');
}
}
public sealed class ModDiff
{
public const string PopupQuestion = "Your mods differ from the host's.\nJoin anyway?";
public List<ModEntry> Missing { get; } = new List<ModEntry>();
public List<ModEntry> Extra { get; } = new List<ModEntry>();
public List<(ModEntry Mine, ModEntry Theirs)> Different { get; } = new List<(ModEntry, ModEntry)>();
public bool IsEmpty
{
get
{
if (Missing.Count == 0 && Extra.Count == 0)
{
return Different.Count == 0;
}
return false;
}
}
public List<string> Lines(string other)
{
List<string> list = new List<string>();
foreach (ModEntry item3 in Missing)
{
list.Add($"Missing: {item3.Id} {item3.Version} ({other} has it; everyone needs it)");
}
foreach (ModEntry item4 in Extra)
{
list.Add($"Extra: {item4.Id} {item4.Version} (you have it, {other} does not; everyone needs it)");
}
foreach (var item5 in Different)
{
ModEntry item = item5.Mine;
ModEntry item2 = item5.Theirs;
string value = ((Math.Max((int)item.Need, (int)item2.Need) == 2) ? "everyone needs the same one" : "whoever has it needs the same one");
list.Add((item.Version != item2.Version) ? $"Different version: {item.Id} {item.Version}, {other} has {item2.Version} ({value})" : $"Different build: {item.Id} {item.Version} ({item.Hash}), {other} has {item2.Hash} ({value})");
}
return list;
}
}
public enum DiffKind
{
HostOnly,
PlayerOnly,
Version,
Build
}
public sealed class ModTable
{
public sealed class Row
{
public string Name { get; }
public string Host { get; }
public string Player { get; }
public DiffKind Kind { get; }
public Row(string name, string host, string player, DiffKind kind)
{
Name = name;
Host = host;
Player = player;
Kind = kind;
}
public override string ToString()
{
return $"{Name} | {Host} | {Player}";
}
}
public sealed class RichStyle
{
public int HostAt = 52;
public int PlayerAt = 76;
public int NameChars = 24;
public int CellChars = 15;
public string Dim = "#9aa0a6";
public string Absent = "#ff6b61";
public string Cell = "#ffc766";
}
public const string Absent = "—";
public const int BuildDigits = 6;
public string HostHeader { get; }
public string PlayerHeader { get; }
public List<Row> Rows { get; } = new List<Row>();
private ModTable(string hostHeader, string playerHeader)
{
HostHeader = hostHeader;
PlayerHeader = playerHeader;
}
public static ModTable ForPlayer(ModDiff d)
{
return Fill(new ModTable("Host", "You"), d, iAmHost: false);
}
public static ModTable ForHost(ModDiff d, string player)
{
return Fill(new ModTable("You (host)", player), d, iAmHost: true);
}
private static ModTable Fill(ModTable t, ModDiff d, bool iAmHost)
{
foreach (ModEntry item in d.Missing)
{
Add(item.Id, "—", item.Version, iAmHost ? DiffKind.PlayerOnly : DiffKind.HostOnly);
}
foreach (ModEntry item2 in d.Extra)
{
Add(item2.Id, item2.Version, "—", (!iAmHost) ? DiffKind.PlayerOnly : DiffKind.HostOnly);
}
foreach (var (modEntry, modEntry2) in d.Different)
{
if (modEntry.Version != modEntry2.Version)
{
Add(modEntry.Id, modEntry.Version, modEntry2.Version, DiffKind.Version);
}
else
{
Add(modEntry.Id, Built(modEntry), Built(modEntry2), DiffKind.Build);
}
}
return t;
void Add(string name, string mine, string theirs, DiffKind kind)
{
t.Rows.Add(iAmHost ? new Row(name, mine, theirs, kind) : new Row(name, theirs, mine, kind));
}
}
private static string Built(ModEntry m)
{
return m.Version + " (" + ((m.Hash.Length > 6) ? m.Hash.Substring(0, 6) : m.Hash) + ")";
}
public string RichText(int maxRows, RichStyle style)
{
if (style == null)
{
style = new RichStyle();
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("<align=left>");
stringBuilder.Append(Colored(style.Dim, Rich(Cut("Mod", style.NameChars)) + $"<pos={style.HostAt}%>" + Rich(Cut(HostHeader, style.CellChars)) + $"<pos={style.PlayerAt}%>" + Rich(Cut(PlayerHeader, style.CellChars))));
int num = Math.Max(1, maxRows);
if (Rows.Count > num)
{
num = Math.Max(1, num - 1);
}
foreach (Row item in Rows.Take(num))
{
StringBuilder stringBuilder2 = stringBuilder.Append('\n').Append(Rich(Cut(item.Name, style.NameChars)));
StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(7, 1, stringBuilder2);
handler.AppendLiteral("<pos=");
handler.AppendFormatted(style.HostAt);
handler.AppendLiteral("%>");
StringBuilder stringBuilder3 = stringBuilder2.Append(ref handler).Append(Cell(item.Host, style));
StringBuilder.AppendInterpolatedStringHandler handler2 = new StringBuilder.AppendInterpolatedStringHandler(7, 1, stringBuilder3);
handler2.AppendLiteral("<pos=");
handler2.AppendFormatted(style.PlayerAt);
handler2.AppendLiteral("%>");
stringBuilder3.Append(ref handler2).Append(Cell(item.Player, style));
}
if (Rows.Count > num)
{
stringBuilder.Append('\n').Append(Colored(style.Dim, $"+{Rows.Count - num} more (see the log)"));
}
return stringBuilder.ToString();
}
private static string Cell(string text, RichStyle style)
{
if (!(text == "—"))
{
return Colored(style.Cell, Rich(Cut(text, style.CellChars)));
}
return Colored(style.Absent, "—");
}
private static string Colored(string color, string text)
{
if (!string.IsNullOrEmpty(color))
{
return $"<color={color}>{text}</color>";
}
return text;
}
public static string Cut(string text, int chars)
{
if (text == null)
{
text = "";
}
if (chars < 3 || text.Length <= chars)
{
return text;
}
return text.Substring(0, chars - 2).TrimEnd() + "..";
}
private static string Rich(string text)
{
return (text ?? "").Replace("<", "<\u200b");
}
}
public static class ModCompare
{
public static ModDiff Compare(IEnumerable<ModEntry> mine, IEnumerable<ModEntry> theirs)
{
ModDiff modDiff = new ModDiff();
Dictionary<string, ModEntry> dictionary = Index(mine);
Dictionary<string, ModEntry> dictionary2 = Index(theirs);
foreach (KeyValuePair<string, ModEntry> item in dictionary2)
{
if (item.Value.Required && !dictionary.ContainsKey(item.Key))
{
modDiff.Missing.Add(item.Value);
}
}
foreach (KeyValuePair<string, ModEntry> item2 in dictionary)
{
if (!dictionary2.TryGetValue(item2.Key, out var value))
{
if (item2.Value.Required)
{
modDiff.Extra.Add(item2.Value);
}
continue;
}
ModEntry value2 = item2.Value;
if (value2.Compared || value.Compared)
{
bool num = value2.Version != value.Version;
bool flag = value2.Hash.Length > 0 && value.Hash.Length > 0 && !string.Equals(value2.Hash, value.Hash, StringComparison.OrdinalIgnoreCase);
if (num || flag)
{
modDiff.Different.Add((value2, value));
}
}
}
modDiff.Missing.Sort((ModEntry a, ModEntry b) => string.CompareOrdinal(a.Key, b.Key));
modDiff.Extra.Sort((ModEntry a, ModEntry b) => string.CompareOrdinal(a.Key, b.Key));
modDiff.Different.Sort(((ModEntry Mine, ModEntry Theirs) a, (ModEntry Mine, ModEntry Theirs) b) => string.CompareOrdinal(a.Mine.Key, b.Mine.Key));
return modDiff;
}
internal static Dictionary<string, ModEntry> Index(IEnumerable<ModEntry> mods)
{
Dictionary<string, ModEntry> dictionary = new Dictionary<string, ModEntry>(StringComparer.Ordinal);
foreach (ModEntry item in mods ?? Enumerable.Empty<ModEntry>())
{
if (item != null && item.Key.Length > 0 && !dictionary.ContainsKey(item.Key))
{
dictionary[item.Key] = item;
}
}
return dictionary;
}
}
public static class ModDigest
{
public const int Length = 8;
public const int TagLength = 4;
public static string Of(ModEntry m)
{
return Hex(m.Key + "\t" + m.Version + "\t" + m.Hash.ToLowerInvariant(), 8);
}
public static string TagOf(string key)
{
return Hex("tag\t" + key, 4);
}
public static bool IsHex(string d, int length)
{
if (d != null && d.Length == length)
{
return d.All((char c) => (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'));
}
return false;
}
private static string Hex(string text, int length)
{
using SHA256 sHA = SHA256.Create();
return BitConverter.ToString(sHA.ComputeHash(Encoding.UTF8.GetBytes(text)), 0, length / 2).Replace("-", "").ToLowerInvariant();
}
}
public sealed class OfferedMod
{
public string Tag { get; }
public string Digest { get; }
public ModNeed Need { get; }
internal string Token => Tag + Digest + ((Need == ModNeed.Required) ? 'r' : ((Need == ModNeed.SameVersion) ? 's' : 'o'));
public OfferedMod(string tag, string digest, ModNeed need)
{
Tag = tag;
Digest = digest;
Need = need;
}
public static OfferedMod Of(ModEntry m)
{
return new OfferedMod(ModDigest.TagOf(m.Key), ModDigest.Of(m), m.Need);
}
internal static bool TryParse(string token, out OfferedMod mod)
{
mod = null;
if (token == null || token.Length != 13)
{
return false;
}
string text = token.Substring(0, 4);
string text2 = token.Substring(4, 8);
char c = token[token.Length - 1];
if (!ModDigest.IsHex(text, 4) || !ModDigest.IsHex(text2, 8) || (c != 'r' && c != 's' && c != 'o'))
{
return false;
}
mod = new OfferedMod(text, text2, c switch
{
's' => ModNeed.SameVersion,
'r' => ModNeed.Required,
_ => ModNeed.OwnOnly,
});
return true;
}
}
public sealed class JoinOffer
{
public enum Kind
{
Ask,
Accept,
Unchecked
}
public const string Magic = "POGMC2";
public const string Family = "POGMC";
private const char Field = '\u001e';
private readonly Dictionary<string, List<OfferedMod>> _byTag;
public Kind Mode { get; }
public List<OfferedMod> Mods { get; }
public HashSet<string> Digests { get; }
public JoinOffer(Kind mode, IEnumerable<OfferedMod> mods)
{
Mode = mode;
Mods = (mods ?? Enumerable.Empty<OfferedMod>()).Where((OfferedMod m) => m != null).OrderBy<OfferedMod, string>((OfferedMod m) => m.Token, StringComparer.Ordinal).ToList();
Digests = new HashSet<string>(Mods.Select((OfferedMod m) => m.Digest), StringComparer.Ordinal);
_byTag = new Dictionary<string, List<OfferedMod>>(StringComparer.Ordinal);
foreach (OfferedMod mod in Mods)
{
if (!_byTag.TryGetValue(mod.Tag, out var value))
{
value = (_byTag[mod.Tag] = new List<OfferedMod>());
}
value.Add(mod);
}
}
public List<OfferedMod> WithTag(string tag)
{
if (!_byTag.TryGetValue(tag, out var value))
{
return new List<OfferedMod>();
}
return value;
}
public static JoinOffer From(IEnumerable<ModEntry> mods, Kind mode)
{
return new JoinOffer(mode, ModCompare.Index(mods).Values.Select(OfferedMod.Of));
}
private static char Letter(Kind k)
{
return k switch
{
Kind.Accept => 'A',
Kind.Ask => 'Q',
_ => 'U',
};
}
public string Serialize()
{
return "POGMC2" + Letter(Mode) + "\u001e" + string.Join(",", Mods.Select((OfferedMod m) => m.Token));
}
public string SerializeWithin(int maxChars)
{
string text = Serialize();
if (text.Length > maxChars)
{
return new JoinOffer(Kind.Unchecked, null).Serialize();
}
return text;
}
public static bool TryParse(string text, out JoinOffer offer)
{
offer = null;
if (text == null || !text.StartsWith("POGMC2", StringComparison.Ordinal))
{
return false;
}
string[] array = text.Split('\u001e');
if (array.Length != 2 || array[0].Length != "POGMC2".Length + 1)
{
return false;
}
Kind mode;
switch (array[0]["POGMC2".Length])
{
case 'Q':
mode = Kind.Ask;
break;
case 'A':
mode = Kind.Accept;
break;
case 'U':
mode = Kind.Unchecked;
break;
default:
return false;
}
List<OfferedMod> list = new List<OfferedMod>();
if (array[1].Length > 0)
{
string[] array2 = array[1].Split(',');
for (int i = 0; i < array2.Length; i++)
{
if (!OfferedMod.TryParse(array2[i], out var mod))
{
return false;
}
list.Add(mod);
}
}
offer = new JoinOffer(mode, list);
return true;
}
}
public static class ConnectionPayload
{
public const string GamePrefix = "POGC1|";
public static string WithOffer(string text, string offer)
{
if (string.IsNullOrEmpty(text))
{
return "POGC1|" + offer;
}
if (!text.StartsWith("POGC1|", StringComparison.Ordinal))
{
return null;
}
List<string> list = (from k in text.Substring("POGC1|".Length).Split(';')
where k.Length > 0 && !k.StartsWith("POGMC", StringComparison.Ordinal)
select k).ToList();
list.Add(offer);
return "POGC1|" + string.Join(";", list);
}
public static string FindOffer(string text)
{
if (string.IsNullOrEmpty(text) || !text.StartsWith("POGC1|", StringComparison.Ordinal))
{
return null;
}
return text.Substring("POGC1|".Length).Split(';').FirstOrDefault((string k) => k.StartsWith("POGMC2", StringComparison.Ordinal));
}
}
public static class JoinCheck
{
public static bool Differs(IEnumerable<ModEntry> mine, JoinOffer offer)
{
List<ModEntry> list = ModCompare.Index(mine).Values.ToList();
foreach (ModEntry item in list)
{
if (!offer.Digests.Contains(ModDigest.Of(item)))
{
if (item.Required)
{
return true;
}
List<OfferedMod> list2 = offer.WithTag(ModDigest.TagOf(item.Key));
if (list2.Count > 0 && (item.Compared || list2.Any((OfferedMod c) => c.Need != ModNeed.OwnOnly)))
{
return true;
}
}
}
HashSet<string> myTags = new HashSet<string>(list.Select((ModEntry m) => ModDigest.TagOf(m.Key)), StringComparer.Ordinal);
return offer.Mods.Any((OfferedMod p) => p.Need == ModNeed.Required && !myTags.Contains(p.Tag));
}
}
public static class JoinRefusal
{
public const string Prefix = "POGModCheck:";
public static List<ModEntry> EntriesFor(IEnumerable<ModEntry> mine, JoinOffer offer)
{
List<ModEntry> list = new List<ModEntry>();
foreach (ModEntry value in ModCompare.Index(mine).Values)
{
List<OfferedMod> list2 = offer.WithTag(ModDigest.TagOf(value.Key));
bool num = offer.Digests.Contains(ModDigest.Of(value));
bool flag = value.Required || (list2.Count > 0 && (value.Compared || list2.Any((OfferedMod c) => c.Need != ModNeed.OwnOnly)));
if ((!num && flag) || list2.Any((OfferedMod c) => c.Need == ModNeed.Required))
{
list.Add(value);
}
}
list.Sort((ModEntry a, ModEntry b) => string.CompareOrdinal(a.Key, b.Key));
return list;
}
public static string Build(IEnumerable<ModEntry> entries, int maxChars)
{
List<ModEntry> list = (entries ?? Enumerable.Empty<ModEntry>()).ToList();
string text = "POGModCheck:" + ModListCodec.Serialize(list);
if (text.Length <= maxChars)
{
return text;
}
string text2 = "POGModCheck:" + ModListCodec.Serialize(list.Select((ModEntry m) => new ModEntry(m.Id, m.Version, "", m.Need)));
if (text2.Length > maxChars)
{
return null;
}
return text2;
}
public static bool TryParse(string reason, out List<ModEntry> entries)
{
entries = null;
if (reason == null || !reason.StartsWith("POGModCheck:", StringComparison.Ordinal))
{
return false;
}
return ModListCodec.TryParse(reason.Substring("POGModCheck:".Length), out entries);
}
}
public static class ModMarker
{
public enum Mark
{
None,
Required,
SameVersion,
Unknown
}
public const string Key = "POGModCheck";
public const string RequiredValue = "required";
public const string SameVersionValue = "same-version";
public static Mark Interpret(IEnumerable<KeyValuePair<string, string>> metadata, out string unknownValue)
{
unknownValue = null;
bool flag = false;
bool flag2 = false;
bool flag3 = false;
foreach (KeyValuePair<string, string> item in metadata ?? Enumerable.Empty<KeyValuePair<string, string>>())
{
if (string.Equals(item.Key?.Trim(), "POGModCheck", StringComparison.OrdinalIgnoreCase))
{
string text = ModEntry.KeyOf(item.Value);
if (text == ModEntry.KeyOf("required"))
{
flag = true;
}
else if (text == ModEntry.KeyOf("same-version"))
{
flag2 = true;
}
else if (!flag3)
{
flag3 = true;
unknownValue = item.Value?.Trim() ?? "";
}
}
}
if (flag || flag2)
{
unknownValue = null;
if (!flag)
{
return Mark.SameVersion;
}
return Mark.Required;
}
if (!flag3)
{
return Mark.None;
}
return Mark.Unknown;
}
public static Mark Read(Assembly asm, out string unknownValue)
{
return Interpret(MetadataOf(asm), out unknownValue);
}
private static List<KeyValuePair<string, string>> MetadataOf(Assembly asm)
{
List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
if (asm == null)
{
return list;
}
IList<CustomAttributeData> customAttributesData;
try
{
customAttributesData = asm.GetCustomAttributesData();
}
catch
{
return list;
}
string fullName = typeof(AssemblyMetadataAttribute).FullName;
foreach (CustomAttributeData item in customAttributesData)
{
try
{
if (!(item.AttributeType.FullName != fullName))
{
IList<CustomAttributeTypedArgument> constructorArguments = item.ConstructorArguments;
if (constructorArguments.Count == 2)
{
list.Add(new KeyValuePair<string, string>(constructorArguments[0].Value as string, constructorArguments[1].Value as string));
}
}
}
catch
{
}
}
return list;
}
}
public sealed class PeerWatch
{
private readonly ulong _self;
private readonly float _wait;
private readonly Dictionary<ulong, float> _joinedAt = new Dictionary<ulong, float>();
private readonly HashSet<ulong> _answered = new HashSet<ulong>();
private readonly HashSet<ulong> _named = new HashSet<ulong>();
public PeerWatch(ulong self, float wait)
{
_self = self;
_wait = wait;
}
public void Present(IEnumerable<ulong> ids, float now)
{
HashSet<ulong> present = new HashSet<ulong>(ids ?? Enumerable.Empty<ulong>());
present.Remove(_self);
foreach (ulong item in present)
{
if (!_joinedAt.ContainsKey(item))
{
_joinedAt[item] = now;
}
}
foreach (ulong item2 in _joinedAt.Keys.Where((ulong k) => !present.Contains(k)).ToList())
{
_joinedAt.Remove(item2);
}
}
public void Answered(ulong id)
{
_answered.Add(id);
}
public List<ulong> Overdue(float now)
{
List<ulong> list = new List<ulong>();
foreach (KeyValuePair<ulong, float> item in _joinedAt)
{
if (!_answered.Contains(item.Key) && !_named.Contains(item.Key) && now - item.Value > _wait)
{
list.Add(item.Key);
}
}
foreach (ulong item2 in list)
{
_named.Add(item2);
}
list.Sort();
return list;
}
}
}