using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using FishNet.Connection;
using FishNet.Managing;
using FishNet.Object;
using FishNet.Object.Delegating;
using FishNet.Serializing;
using FishNet.Transporting;
using HarmonyLib;
using Steamworks;
using UnityEngine;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace Spellmender;
internal static class BlackMagicApiFix
{
internal static readonly ManualLogSource Log = Logger.CreateLogSource("BlackMagicAPI Fix");
private const string FailingPatch = "BlackMagicAPI.Patches.Generation.PaperInteractPatch";
private static MethodInfo serverCraftPrefix;
private static PropertyInfo isServerInitialized;
private static MethodInfo soupStartPostfix;
private static FieldInfo soupMapping;
public static void Install(PluginInfo bmapi)
{
//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
//IL_00a6: Expected O, but got Unknown
if (bmapi.Metadata.Version.ToString() != "3.0.2")
{
Log.LogWarning((object)("Written for BlackMagicAPI 3.0.2, found " + bmapi.Metadata.Version?.ToString() + "."));
}
Assembly assembly = ((object)bmapi.Instance).GetType().Assembly;
Type[] typesFromAssembly = AccessTools.GetTypesFromAssembly(assembly);
if (!typesFromAssembly.Any((Type t) => t.FullName == "BlackMagicAPI.Patches.Generation.PaperInteractPatch"))
{
Log.LogWarning((object)"BlackMagicAPI.Patches.Generation.PaperInteractPatch not found: this BlackMagicAPI build is different, doing nothing.");
return;
}
Harmony val = new Harmony("com.d1gq.black.magic.api");
HashSet<Type> hashSet = InstalledPatchTypes();
int num = 0;
int num2 = 0;
int num3 = 0;
Type[] array = typesFromAssembly;
foreach (Type type in array)
{
if (!type.IsDefined(typeof(HarmonyAttribute), inherit: false))
{
continue;
}
if (hashSet.Contains(type))
{
num3++;
}
else
{
if (type.FullName == "BlackMagicAPI.Patches.Generation.PaperInteractPatch")
{
continue;
}
try
{
if (type.Name == "ServerCraftPatch")
{
PatchServerCraft(val, type);
}
else if (type.Name == "SoupManControllerPatch")
{
PatchSoupManController(val, type);
}
else
{
val.CreateClassProcessor(type).Patch();
}
num++;
Log.LogInfo((object)("Applied " + type.FullName));
}
catch (Exception e)
{
num2++;
Log.LogError((object)("Could not apply " + type.FullName + ": " + Plugin.Message(e)));
}
}
}
Log.LogInfo((object)("BlackMagicAPI patch classes: " + num3 + " installed by BlackMagicAPI, " + num + " installed here, " + num2 + " failed."));
RunSkippedStartup(assembly, bmapi.Instance);
}
public static void ReportOldSpellMods(PluginInfo bmapi)
{
try
{
Type type = ((object)bmapi.Instance).GetType().Assembly.GetType("BlackMagicAPI.Modules.Spells.SpellLogic");
bool flag = type != null && type.GetMethods().Any((MethodInfo m) => m.Name == "CastSpell" && m.GetParameters().Length != 0 && m.GetParameters()[0].ParameterType == typeof(GameObject));
List<string> list = new List<string>();
foreach (PluginInfo value in Chainloader.PluginInfos.Values)
{
if (!((Object)(object)value.Instance == (Object)null))
{
AssemblyName assemblyName = ((object)value.Instance).GetType().Assembly.GetReferencedAssemblies().FirstOrDefault((AssemblyName a) => a.Name == "BlackMagicAPI");
if (assemblyName != null && assemblyName.Version != null && assemblyName.Version.Major < 3)
{
list.Add(value.Metadata.Name);
}
}
}
if (flag)
{
Log.LogInfo((object)("BlackMagicAPI.dll is patched for the old spell API" + ((list.Count > 0) ? ("; old spell mods: " + string.Join(", ", list.ToArray())) : "") + "."));
}
else if (list.Count > 0)
{
Log.LogWarning((object)("BlackMagicAPI.dll is not patched for the old spell API (is Spellmender.Patcher.dll in BepInEx\\patchers? see the preloader lines at the top of the log); these spells will not load: " + string.Join(", ", list.ToArray())));
}
}
catch (Exception e)
{
Log.LogWarning((object)("Old spell API check failed: " + Plugin.Message(e)));
}
}
private static HashSet<Type> InstalledPatchTypes()
{
HashSet<Type> hashSet = new HashSet<Type>();
foreach (MethodBase allPatchedMethod in Harmony.GetAllPatchedMethods())
{
Patches patchInfo = Harmony.GetPatchInfo(allPatchedMethod);
if (patchInfo == null)
{
continue;
}
foreach (Patch item in patchInfo.Prefixes.Concat(patchInfo.Postfixes).Concat(patchInfo.Transpilers).Concat(patchInfo.Finalizers))
{
if (item.PatchMethod != null)
{
hashSet.Add(item.PatchMethod.DeclaringType);
}
}
}
return hashSet;
}
private static void PatchServerCraft(Harmony harmony, Type patchType)
{
//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_0071: Expected O, but got Unknown
MethodInfo methodInfo = AccessTools.DeclaredMethod(AccessTools.TypeByName("CraftingForge"), "ServerCraft", (Type[])null, (Type[])null);
serverCraftPrefix = AccessTools.DeclaredMethod(patchType, "Prefix", (Type[])null, (Type[])null);
if (methodInfo == null || serverCraftPrefix == null)
{
throw new Exception("CraftingForge.ServerCraft or the patch's Prefix is missing");
}
HarmonyMethod val = new HarmonyMethod(AccessTools.DeclaredMethod(typeof(BlackMagicApiFix), "ServerCraftGuard", (Type[])null, (Type[])null))
{
priority = 800
};
harmony.Patch((MethodBase)methodInfo, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
}
private static bool ServerCraftGuard(object __instance)
{
if (isServerInitialized == null)
{
isServerInitialized = AccessTools.Property(__instance.GetType(), "IsServerInitialized");
}
if (!(bool)isServerInitialized.GetValue(__instance, null))
{
return true;
}
return (bool)serverCraftPrefix.Invoke(null, new object[1] { __instance });
}
private static void PatchSoupManController(Harmony harmony, Type patchType)
{
//IL_009a: Unknown result type (might be due to invalid IL or missing references)
//IL_009f: Unknown result type (might be due to invalid IL or missing references)
//IL_00ab: Expected O, but got Unknown
MethodInfo methodInfo = AccessTools.DeclaredMethod(AccessTools.TypeByName("SoupManController"), "Awake", (Type[])null, (Type[])null);
soupStartPostfix = AccessTools.DeclaredMethod(patchType, "Start_Postfix", (Type[])null, (Type[])null);
Type type = patchType.Assembly.GetType("BlackMagicAPI.Managers.SoupManager");
soupMapping = ((type == null) ? null : AccessTools.Field(type, "Mapping"));
if (methodInfo == null || soupStartPostfix == null || soupMapping == null)
{
throw new Exception("SoupManController.Awake, Start_Postfix or SoupManager.Mapping is missing");
}
HarmonyMethod val = new HarmonyMethod(AccessTools.DeclaredMethod(typeof(BlackMagicApiFix), "SoupManControllerGuard", (Type[])null, (Type[])null))
{
priority = 800
};
harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
}
private static void SoupManControllerGuard(object __instance)
{
object? value = soupMapping.GetValue(null);
ICollection collection = value as ICollection;
IEnumerable enumerable = value as IEnumerable;
bool num;
if (collection == null)
{
if (enumerable == null)
{
return;
}
num = enumerable.GetEnumerator().MoveNext();
}
else
{
num = collection.Count > 0;
}
if (num)
{
soupStartPostfix.Invoke(null, new object[1] { __instance });
}
}
private static void RunSkippedStartup(Assembly asm, BaseUnityPlugin bmapi)
{
try
{
AccessTools.Method(asm.GetType("BlackMagicAPI.Managers.SynchronizeManager"), "UpdateSyncHash", (Type[])null, (Type[])null).Invoke(null, null);
}
catch (Exception e)
{
Log.LogWarning((object)("UpdateSyncHash: " + Plugin.Message(e)));
}
try
{
MethodInfo methodInfo = AccessTools.Method(((object)bmapi).GetType(), "CoWaitForChainloaderToLog", (Type[])null, (Type[])null);
if (methodInfo != null)
{
((MonoBehaviour)bmapi).StartCoroutine((IEnumerator)methodInfo.Invoke(bmapi, null));
}
}
catch (Exception e2)
{
Log.LogWarning((object)("CoWaitForChainloaderToLog: " + Plugin.Message(e2)));
}
}
}
internal static class Diag
{
private static ManualLogSource log;
private static FieldInfo spellprefabField;
private static Type spellLogicType;
private static bool tableLogged;
public static void Install(Harmony harmony)
{
log = BlackMagicApiFix.Log;
Type type = AccessTools.TypeByName("PageController");
spellprefabField = AccessTools.Field(type, "spellprefab");
spellLogicType = AccessTools.TypeByName("BlackMagicAPI.Modules.Spells.SpellLogic");
Patch(harmony, AccessTools.DeclaredMethod(type, "CastSpellServer", (Type[])null, (Type[])null), "OnCastSent", postfix: false);
Patch(harmony, FirstStartingWith(type, "RpcReader___Server_CastSpellServer"), "OnServerReceivedCast", postfix: false);
Patch(harmony, FirstStartingWith(type, "RpcReader___Observers_CastSpellObs"), "OnClientReceivedCast", postfix: false);
Patch(harmony, AccessTools.DeclaredMethod(AccessTools.TypeByName("BlackMagicAPI.Patches.Items.PageControllerPatch"), "CastSpellObs_Logic", (Type[])null, (Type[])null), "OnModdedSpellSpawned", postfix: false);
Patch(harmony, AccessTools.DeclaredMethod(AccessTools.TypeByName("PlayerMovement"), "OnStartClient", (Type[])null, (Type[])null), "OnPlayerStartClient", postfix: true);
log.LogInfo((object)"[diag] spell-cast diagnostics on");
}
private static void Patch(Harmony harmony, MethodBase target, string handler, bool postfix)
{
//IL_0031: Unknown result type (might be due to invalid IL or missing references)
//IL_0036: Unknown result type (might be due to invalid IL or missing references)
//IL_0042: Expected O, but got Unknown
if (target == null)
{
log.LogWarning((object)("[diag] no target for " + handler));
return;
}
HarmonyMethod val = new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Diag), handler, (Type[])null, (Type[])null))
{
priority = 900
};
try
{
if (postfix)
{
harmony.Patch(target, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
}
else
{
harmony.Patch(target, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
}
}
catch (Exception e)
{
log.LogWarning((object)("[diag] " + handler + ": " + Plugin.Message(e)));
}
}
private static MethodInfo FirstStartingWith(Type type, string prefix)
{
return AccessTools.GetDeclaredMethods(type).FirstOrDefault((MethodInfo m) => m.Name.StartsWith(prefix));
}
private static void OnCastSent(NetworkBehaviour __instance, GameObject ownerobj)
{
Safe(() => "cast sent: " + Describe(__instance) + " isOwner=" + __instance.IsOwner + " clientInit=" + __instance.IsClientInitialized + " caster=" + Name(ownerobj));
}
private static void OnServerReceivedCast(NetworkBehaviour __instance, NetworkConnection conn)
{
Safe(() => "server received cast from client " + ((conn == (NetworkConnection)null) ? "?" : conn.ClientId.ToString()) + ": " + Describe(__instance) + " observers=[" + Observers(__instance) + "]");
}
private static void OnClientReceivedCast(NetworkBehaviour __instance)
{
Safe(() => "cast received: " + Describe(__instance));
}
private static void OnModdedSpellSpawned(GameObject ownerobj)
{
Safe(() => "modded spell spawned here, caster=" + Name(ownerobj));
}
private static void OnPlayerStartClient()
{
if (tableLogged)
{
return;
}
tableLogged = true;
Safe(delegate
{
Type type = AccessTools.TypeByName("FishUtilities.Managers.FishManager");
List<string> list = new List<string>();
if (AccessTools.Field(type, "netObjs").GetValue(null) is IEnumerable enumerable)
{
foreach (object item in enumerable)
{
string text = (item.GetType().GetField("Item1").GetValue(item) as string) ?? "?";
object? value = item.GetType().GetField("Item2").GetValue(item);
NetworkObject val = (NetworkObject)((value is NetworkObject) ? value : null);
list.Add((((Object)(object)val == (Object)null) ? "?" : (val.PrefabId + "=" + ((Object)((Component)val).gameObject).name)) + "#" + text.Substring(0, Math.Min(11, text.Length)));
}
}
object? value2 = AccessTools.Property(type, "NetworkManager").GetValue(null, null);
NetworkManager val2 = (NetworkManager)((value2 is NetworkManager) ? value2 : null);
return "spawnable prefabs: " + (((Object)(object)val2 != (Object)null && (Object)(object)val2.SpawnablePrefabs != (Object)null) ? val2.SpawnablePrefabs.GetObjectCount() : (-1)) + "; FishUtilities prefabs: " + string.Join(" | ", list.ToArray());
});
}
private static string Describe(NetworkBehaviour nb)
{
if ((Object)(object)nb == (Object)null)
{
return "null";
}
NetworkObject networkObject = nb.NetworkObject;
return ((Object)((Component)nb).gameObject).name + " obj=" + nb.ObjectId + " prefab=" + (((Object)(object)networkObject == (Object)null) ? "?" : networkObject.PrefabId.ToString()) + " owner=" + nb.OwnerId + " modded=" + Modded(nb);
}
private static string Modded(NetworkBehaviour nb)
{
GameObject val = (GameObject)((spellprefabField == null) ? null : /*isinst with value type is only supported in some contexts*/);
if ((Object)(object)val == (Object)null)
{
return "no-spellprefab";
}
return ((spellLogicType != null && (Object)(object)val.GetComponent(spellLogicType) != (Object)null) ? "yes(" : "no(") + ((Object)val).name + ")";
}
private static string Observers(NetworkBehaviour nb)
{
HashSet<NetworkConnection> observers = nb.Observers;
if (observers == null)
{
return "?";
}
return string.Join(",", observers.Select((NetworkConnection c) => (!(c == (NetworkConnection)null)) ? c.ClientId.ToString() : "?").ToArray());
}
private static string Name(GameObject go)
{
if (!((Object)(object)go == (Object)null))
{
return ((Object)go).name;
}
return "null";
}
private static void Safe(Func<string> message)
{
try
{
log.LogInfo((object)("[diag] " + message()));
}
catch (Exception e)
{
log.LogWarning((object)("[diag] failed: " + Plugin.Message(e)));
}
}
}
internal static class FishRelay
{
private const uint CmdHash = 100u;
private const uint RpcHash = 101u;
private const uint TargetHash = 102u;
private static readonly string[] CarrierTypes = new string[4] { "GamePlayManager", "PlayerRespawnManager", "NetInteractionManager", "PlayerMovement" };
private static ManualLogSource log;
private static readonly List<NetworkBehaviour> carriers = new List<NetworkBehaviour>();
private static readonly HashSet<string> typesLogged = new HashSet<string>();
private static Type playerType;
private static MethodInfo getter;
private static MethodInfo registerServer;
private static MethodInfo registerObservers;
private static MethodInfo registerTarget;
private static ServerRpcDelegate serverCmd;
private static ClientRpcDelegate clientRpc;
private static ClientRpcDelegate targetRpc;
private static int sendLogs;
private static int receiveLogs;
private static int warnLogs;
private const int MaxLogs = 15;
public static void Install(Harmony harmony, MonoBehaviour host)
{
//IL_016e: Unknown result type (might be due to invalid IL or missing references)
//IL_0178: Expected O, but got Unknown
//IL_0189: Unknown result type (might be due to invalid IL or missing references)
//IL_0193: Expected O, but got Unknown
//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
//IL_01ae: Expected O, but got Unknown
//IL_0214: Unknown result type (might be due to invalid IL or missing references)
//IL_021b: Expected O, but got Unknown
//IL_02c8: Unknown result type (might be due to invalid IL or missing references)
//IL_02d6: Expected O, but got Unknown
//IL_02fa: Unknown result type (might be due to invalid IL or missing references)
//IL_0308: Expected O, but got Unknown
log = Logger.CreateLogSource("FishUtilities Fix");
Type type = AccessTools.TypeByName("FishUtilities.Patches.BootstrapNetworkManagerPatch");
if (type == null)
{
log.LogWarning((object)"[relay] FishUtilities not found, nothing to relay.");
return;
}
getter = AccessTools.DeclaredMethod(type, "get__BootstrapNetworkManager", (Type[])null, (Type[])null);
MethodInfo methodInfo = AccessTools.DeclaredMethod(type, "SendCmd", (Type[])null, (Type[])null);
MethodInfo methodInfo2 = AccessTools.DeclaredMethod(type, "SendRpc", (Type[])null, (Type[])null);
MethodInfo methodInfo3 = AccessTools.DeclaredMethod(type, "SendTargetRpc", (Type[])null, (Type[])null);
MethodInfo methodInfo4 = AccessTools.DeclaredMethod(type, "HandleTargetRpc", new Type[2]
{
typeof(PooledReader),
typeof(Channel)
}, (Type[])null);
MethodInfo methodInfo5 = AccessTools.DeclaredMethod(type, "HandleServerCmd", (Type[])null, (Type[])null);
MethodInfo methodInfo6 = AccessTools.DeclaredMethod(type, "HandleClientRpc", (Type[])null, (Type[])null);
if (getter == null || methodInfo == null || methodInfo2 == null || methodInfo3 == null || methodInfo4 == null || methodInfo5 == null || methodInfo6 == null)
{
throw new Exception("this FishUtilities build is different (1.4.0 expected)");
}
registerServer = AccessTools.Method(typeof(NetworkBehaviour), "RegisterServerRpc", (Type[])null, (Type[])null);
registerObservers = AccessTools.Method(typeof(NetworkBehaviour), "RegisterObserversRpc", (Type[])null, (Type[])null);
registerTarget = AccessTools.Method(typeof(NetworkBehaviour), "RegisterTargetRpc", (Type[])null, (Type[])null);
serverCmd = (ServerRpcDelegate)Delegate.CreateDelegate(typeof(ServerRpcDelegate), methodInfo5);
clientRpc = (ClientRpcDelegate)Delegate.CreateDelegate(typeof(ClientRpcDelegate), methodInfo6);
targetRpc = (ClientRpcDelegate)Delegate.CreateDelegate(typeof(ClientRpcDelegate), methodInfo4);
playerType = AccessTools.TypeByName("PlayerMovement");
Patch(harmony, methodInfo, "SendCmdGuard", "SendCmdIL");
Patch(harmony, methodInfo2, "SendRpcGuard", "SendRpcIL");
Patch(harmony, methodInfo3, "SendTargetGuard", "SendTargetIL");
Patch(harmony, methodInfo4, null, "HandleTargetIL");
HarmonyMethod val = new HarmonyMethod(AccessTools.DeclaredMethod(typeof(FishRelay), "OnCarrierAwake", (Type[])null, (Type[])null));
string[] carrierTypes = CarrierTypes;
foreach (string text in carrierTypes)
{
MethodInfo methodInfo7 = AccessTools.DeclaredMethod(AccessTools.TypeByName(text), "Awake", (Type[])null, (Type[])null);
if (methodInfo7 == null)
{
log.LogWarning((object)("[relay] " + text + ".Awake not found"));
}
else
{
harmony.Patch((MethodBase)methodInfo7, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
}
}
MethodInfo methodInfo8 = AccessTools.DeclaredMethod(type, "HandleCmd", (Type[])null, (Type[])null);
MethodInfo methodInfo9 = AccessTools.DeclaredMethod(type, "HandleRpc", (Type[])null, (Type[])null);
if (methodInfo8 != null)
{
harmony.Patch((MethodBase)methodInfo8, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(FishRelay), "OnCmdReceived", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
}
if (methodInfo9 != null)
{
harmony.Patch((MethodBase)methodInfo9, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(FishRelay), "OnRpcReceived", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
}
FieldInfo fieldInfo = AccessTools.Field(type, "hasLoaded");
if ((bool)fieldInfo.GetValue(null))
{
log.LogInfo((object)"[relay] FishUtilities already started its message setup.");
}
else
{
fieldInfo.SetValue(null, true);
IEnumerator inner = (IEnumerator)AccessTools.DeclaredMethod(type, "CoWaitForChainloader", (Type[])null, (Type[])null).Invoke(null, null);
host.StartCoroutine(RunFishStartup(inner, type));
}
log.LogInfo((object)"[relay] FishUtilities messages relayed through the players' objects (RPCs 100-102).");
}
private static void Patch(Harmony harmony, MethodInfo target, string prefix, string transpiler)
{
//IL_0017: Unknown result type (might be due to invalid IL or missing references)
//IL_0032: Unknown result type (might be due to invalid IL or missing references)
//IL_003e: Expected O, but got Unknown
harmony.Patch((MethodBase)target, (prefix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(AccessTools.DeclaredMethod(typeof(FishRelay), prefix, (Type[])null, (Type[])null)), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(FishRelay), transpiler, (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null);
}
private static IEnumerator RunFishStartup(IEnumerator inner, Type patch)
{
while (true)
{
object current;
try
{
if (!inner.MoveNext())
{
break;
}
current = inner.Current;
goto IL_0057;
}
catch (Exception e)
{
log.LogError((object)("[relay] FishUtilities message setup failed: " + Plugin.Message(e)));
yield break;
}
IL_0057:
yield return current;
}
log.LogInfo((object)("[relay] FishUtilities message setup done: " + Count(patch, "Cmds") + " Cmd, " + Count(patch, "Rpcs") + " Rpc, " + Count(patch, "TargetRpcs") + " TargetRpc methods."));
}
private static int Count(Type patch, string field)
{
if (!(AccessTools.Field(patch, field).GetValue(null) is IDictionary dictionary))
{
return -1;
}
int num = 0;
foreach (object value in dictionary.Values)
{
if (value is ICollection collection)
{
num += collection.Count;
}
}
return num;
}
private static void OnCarrierAwake(NetworkBehaviour __instance)
{
if ((Object)(object)__instance == (Object)null || carriers.Contains(__instance))
{
return;
}
try
{
registerServer.Invoke(__instance, new object[2] { 100u, serverCmd });
registerObservers.Invoke(__instance, new object[2] { 101u, clientRpc });
registerTarget.Invoke(__instance, new object[2] { 102u, targetRpc });
carriers.Add(__instance);
if (typesLogged.Add(((object)__instance).GetType().Name))
{
log.LogInfo((object)("[relay] RPCs 100-102 registered on " + ((object)__instance).GetType().Name));
}
}
catch (Exception e)
{
log.LogWarning((object)("[relay] could not register on " + ((Object)__instance).name + ": " + Plugin.Message(e)));
}
}
private static void Prune()
{
carriers.RemoveAll((NetworkBehaviour c) => (Object)(object)c == (Object)null);
}
private static bool IsPlayer(NetworkBehaviour nb)
{
if (playerType != null)
{
return playerType.IsInstanceOfType(nb);
}
return false;
}
private static NetworkBehaviour CmdCarrier()
{
Prune();
NetworkBehaviour val = null;
foreach (NetworkBehaviour carrier in carriers)
{
if (carrier.IsClientInitialized)
{
if (IsPlayer(carrier) && carrier.IsOwner)
{
return carrier;
}
if ((Object)(object)val == (Object)null)
{
val = carrier;
}
}
}
return val;
}
private static NetworkBehaviour RpcCarrier()
{
Prune();
NetworkBehaviour val = null;
int num = -1;
int num2 = 0;
int num3 = 0;
foreach (NetworkBehaviour carrier in carriers)
{
if (!carrier.IsServerInitialized)
{
continue;
}
int num4 = 0;
int num5 = 0;
HashSet<NetworkConnection> observers = carrier.Observers;
foreach (NetworkConnection value in carrier.ServerManager.Clients.Values)
{
if (!(value == (NetworkConnection)null) && value.IsAuthenticated)
{
num5++;
if (observers != null && observers.Contains(value))
{
num4++;
}
}
}
int num6 = num4 * 2 + ((!IsPlayer(carrier)) ? 1 : 0);
if (num6 > num)
{
val = carrier;
num = num6;
num2 = num4;
num3 = num5;
}
}
if ((Object)(object)val != (Object)null && num2 < num3)
{
Warn("only " + num2 + " of " + num3 + " players observe " + Describe(val) + "; the others miss this Rpc");
}
return val;
}
private static NetworkBehaviour TargetCarrier(NetworkConnection target)
{
Prune();
NetworkBehaviour val = null;
foreach (NetworkBehaviour carrier in carriers)
{
if (!carrier.IsServerInitialized || target == (NetworkConnection)null)
{
continue;
}
HashSet<NetworkConnection> observers = carrier.Observers;
if (observers != null && observers.Contains(target))
{
if (carrier.Owner == target)
{
return carrier;
}
if ((Object)(object)val == (Object)null)
{
val = carrier;
}
}
}
return val;
}
private static NetworkBehaviour AnyCarrier()
{
Prune();
if (carriers.Count <= 0)
{
return null;
}
return carriers[0];
}
private static bool SendCmdGuard(Type type, uint cmdId)
{
return Guard("Cmd", type, cmdId, CmdCarrier());
}
private static bool SendRpcGuard(Type type, uint rpcId)
{
return Guard("Rpc", type, rpcId, RpcCarrier());
}
private static bool SendTargetGuard(Type type, uint rpcId, NetworkConnection target)
{
return Guard("TargetRpc", type, rpcId, TargetCarrier(target));
}
private static bool Guard(string kind, Type type, uint id, NetworkBehaviour carrier)
{
string text = ((type == null) ? "?" : type.Name) + "#" + id;
if ((Object)(object)carrier == (Object)null)
{
Warn("no network object to carry " + kind + " " + text + " (" + carriers.Count + " known), dropped");
return false;
}
if (sendLogs < 15)
{
sendLogs++;
log.LogInfo((object)("[relay] sending " + kind + " " + text + " via " + Describe(carrier)));
}
return true;
}
private static void OnCmdReceived(string type, uint cmdId, NetworkConnection sender)
{
if (receiveLogs < 15)
{
receiveLogs++;
log.LogInfo((object)("[relay] server received Cmd " + Short(type) + "#" + cmdId + " from client " + ((sender == (NetworkConnection)null) ? "?" : sender.ClientId.ToString())));
}
}
private static void OnRpcReceived(string type, uint rpcId)
{
if (receiveLogs < 15)
{
receiveLogs++;
log.LogInfo((object)("[relay] received Rpc " + Short(type) + "#" + rpcId));
}
}
private static string Short(string type)
{
if (type == null)
{
return "?";
}
int num = type.LastIndexOf('.');
if (num >= 0)
{
return type.Substring(num + 1);
}
return type;
}
private static string Describe(NetworkBehaviour nb)
{
return ((object)nb).GetType().Name + " obj=" + nb.ObjectId + " owner=" + nb.OwnerId;
}
private static void Warn(string message)
{
if (warnLogs < 15)
{
warnLogs++;
log.LogWarning((object)("[relay] " + message));
}
}
private static IEnumerable<CodeInstruction> SendCmdIL(IEnumerable<CodeInstruction> code)
{
return Swap(code, "CmdCarrier", passTarget: false);
}
private static IEnumerable<CodeInstruction> SendRpcIL(IEnumerable<CodeInstruction> code)
{
return Swap(code, "RpcCarrier", passTarget: false);
}
private static IEnumerable<CodeInstruction> SendTargetIL(IEnumerable<CodeInstruction> code)
{
return Swap(code, "TargetCarrier", passTarget: true);
}
private static IEnumerable<CodeInstruction> HandleTargetIL(IEnumerable<CodeInstruction> code)
{
return Swap(code, "AnyCarrier", passTarget: false);
}
private static IEnumerable<CodeInstruction> Swap(IEnumerable<CodeInstruction> code, string picker, bool passTarget)
{
//IL_0051: Unknown result type (might be due to invalid IL or missing references)
//IL_0058: Expected O, but got Unknown
//IL_0061: Unknown result type (might be due to invalid IL or missing references)
//IL_0068: Expected O, but got Unknown
MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(FishRelay), picker, (Type[])null, (Type[])null);
List<CodeInstruction> list = new List<CodeInstruction>();
int num = 0;
foreach (CodeInstruction item in code)
{
if (!CodeInstructionExtensions.Calls(item, getter))
{
list.Add(item);
continue;
}
num++;
CodeInstruction val = new CodeInstruction(OpCodes.Call, (object)methodInfo);
if (passTarget)
{
CodeInstruction val2 = new CodeInstruction(OpCodes.Ldarg_2, (object)null);
val2.labels.AddRange(item.labels);
val2.blocks.AddRange(item.blocks);
list.Add(val2);
}
else
{
val.labels.AddRange(item.labels);
val.blocks.AddRange(item.blocks);
}
list.Add(val);
}
if (num == 0)
{
throw new Exception("no read of BootstrapNetworkManager.instance found for " + picker);
}
return list;
}
}
internal static class MageConfigurationApiFix
{
private static readonly ManualLogSource log = Logger.CreateLogSource("MageConfigurationAPI Fix");
private static bool reported;
public static void Install(Harmony harmony, PluginInfo info)
{
//IL_0085: Unknown result type (might be due to invalid IL or missing references)
//IL_0090: Expected O, but got Unknown
Type type = ((object)info.Instance).GetType().Assembly.GetType("MageConfigurationAPI.Patches.UI.MainMenuManagerPatch");
MethodInfo methodInfo = ((type == null) ? null : AccessTools.DeclaredMethod(type, "Awake_Postfix", (Type[])null, (Type[])null));
if (methodInfo == null)
{
throw new Exception("MainMenuManagerPatch.Awake_Postfix not found (MageConfigurationAPI " + info.Metadata.Version?.ToString() + ")");
}
harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(MageConfigurationApiFix), "Finalizer", (Type[])null, (Type[])null)), (HarmonyMethod)null);
log.LogInfo((object)"MageConfigurationAPI's menu errors are caught.");
}
private static Exception Finalizer(Exception __exception)
{
if (__exception != null && !reported)
{
reported = true;
log.LogWarning((object)("MageConfigurationAPI could not add its Mod Settings menu here (" + __exception.GetType().Name + "): the game's menus changed. Ignored; its menu still works in the main menu."));
}
return null;
}
}
public class EscapeMenuGuard : MonoBehaviour
{
private static readonly ManualLogSource log = Logger.CreateLogSource("Escape Menu");
private static int lastMenuUpdateFrame = -1;
private FieldInfo menuInstance;
private FieldInfo inGameMenu;
private FieldInfo gameHasStarted;
private FieldInfo isSettingPage;
private FieldInfo blackBackground;
private FieldInfo selectCanvas;
private PropertyInfo chooserInstance;
private MethodInfo toggleMenu;
private readonly HashSet<string> reported = new HashSet<string>();
public void Init(Harmony harmony)
{
//IL_0168: Unknown result type (might be due to invalid IL or missing references)
//IL_016d: Unknown result type (might be due to invalid IL or missing references)
//IL_0180: Expected O, but got Unknown
Type type = AccessTools.TypeByName("MainMenuManager");
Type type2 = AccessTools.TypeByName("SpellChooser");
if (type == null || type2 == null)
{
throw new Exception("MainMenuManager or SpellChooser not found");
}
menuInstance = AccessTools.Field(type, "instance");
inGameMenu = AccessTools.Field(type, "InGameMenu");
gameHasStarted = AccessTools.Field(type, "GameHasStarted");
toggleMenu = AccessTools.Method(type, "ToggleInGameMenu", (Type[])null, (Type[])null);
chooserInstance = AccessTools.Property(type2, "instance");
isSettingPage = AccessTools.Field(type2, "isSettingPage");
blackBackground = AccessTools.Field(type2, "blackbackgrounnd");
selectCanvas = AccessTools.Field(type2, "spellselectcanvas");
MethodInfo methodInfo = AccessTools.Method(type, "Update", (Type[])null, (Type[])null);
if (menuInstance == null || inGameMenu == null || gameHasStarted == null || toggleMenu == null || chooserInstance == null || isSettingPage == null || blackBackground == null || selectCanvas == null || methodInfo == null)
{
throw new Exception("MainMenuManager or SpellChooser changed");
}
harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(EscapeMenuGuard), "AfterMenuUpdate", (Type[])null, (Type[])null))
{
priority = 800
}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
}
private static void AfterMenuUpdate()
{
lastMenuUpdateFrame = Time.frameCount;
}
private void LateUpdate()
{
if (!UnityInput.Current.GetKeyDown((KeyCode)27))
{
return;
}
try
{
Check();
}
catch (Exception e)
{
if (reported.Add("error"))
{
log.LogWarning((object)("Escape check failed: " + Plugin.Message(e)));
}
}
}
private void Check()
{
object? value = menuInstance.GetValue(null);
MonoBehaviour val = (MonoBehaviour)((value is MonoBehaviour) ? value : null);
if ((Object)(object)val == (Object)null || (Object)/*isinst with value type is only supported in some contexts*/ == (Object)null)
{
return;
}
object? value2 = chooserInstance.GetValue(null, null);
Object val2 = (Object)((value2 is Object) ? value2 : null);
if ((val2 == (Object)null && !(bool)gameHasStarted.GetValue(val)) || (val2 != (Object)null && (Active(blackBackground, val2) || Active(selectCanvas, val2))))
{
return;
}
bool flag = val2 != (Object)null && (bool)isSettingPage.GetValue(val2);
bool flag2 = lastMenuUpdateFrame == Time.frameCount;
if (!flag2 || !(val2 != (Object)null) || flag)
{
string text = ((!flag2) ? "its menu script (MainMenuManager.Update) is not running" : ((val2 == (Object)null) ? "it has no spell book (SpellChooser) in this game" : "the spell book stayed in its \"choosing spells\" state after closing"));
if (flag)
{
isSettingPage.SetValue(val2, false);
}
toggleMenu.Invoke(val, null);
if (reported.Add(text))
{
log.LogWarning((object)("Escape: the game did not open its menu because " + text + "; Spellmender opened it."));
}
}
}
private static bool Active(FieldInfo field, object owner)
{
object? value = field.GetValue(owner);
GameObject val = (GameObject)((value is GameObject) ? value : null);
if ((Object)(object)val != (Object)null)
{
return val.activeSelf;
}
return false;
}
}
public class ModSyncFix : MonoBehaviour
{
private class Mod
{
public string Guid;
public string Name;
public string Version;
public string Hash;
public string Tag;
}
private const string DataKey = "spellmender";
private const string Header = "spellmender 1";
private const float AnswerTimeout = 15f;
private const float KickTimeout = 60f;
private static readonly ManualLogSource log = Logger.CreateLogSource("ModSync Fix");
private MonoBehaviour modSync;
private MethodInfo showMessage;
private Type messageType;
private PropertyInfo uiInstance;
private MethodInfo createUi;
private PropertyInfo bootstrapInstance;
private FieldInfo connectionsField;
private MethodInfo kickPlayer;
private Dictionary<string, Mod> mine;
private string payload;
private Callback<LobbyEnter_t> lobbyEntered;
private Callback<LobbyChatUpdate_t> lobbyChatUpdate;
private Callback<LobbyDataUpdate_t> lobbyDataUpdate;
private bool callbacksReady;
private ulong lobby;
private bool isHost;
private bool lobbyLock;
private readonly Dictionary<ulong, string> compared = new Dictionary<ulong, string>();
private readonly Dictionary<ulong, float> waiting = new Dictionary<ulong, float>();
private readonly HashSet<ulong> mismatched = new HashSet<ulong>();
private readonly Dictionary<ulong, float> kicks = new Dictionary<ulong, float>();
private float nextPoll;
public void Init(PluginInfo info)
{
Type type = AccessTools.TypeByName("BootstrapManager");
bootstrapInstance = ((type == null) ? null : AccessTools.Property(type, "instance"));
connectionsField = ((type == null) ? null : AccessTools.Field(type, "NetworkconnectionToSteamID"));
kickPlayer = ((type == null) ? null : AccessTools.Method(type, "KickPlayer", (Type[])null, (Type[])null));
if (bootstrapInstance == null)
{
log.LogError((object)"BootstrapManager not found: this Mage Arena build is different, ModSync fix is off.");
((Behaviour)this).enabled = false;
return;
}
modSync = (MonoBehaviour)(object)info.Instance;
if (info.Metadata.Version.ToString() != "1.1.0")
{
log.LogWarning((object)("Written for ModSync 1.1.0, found " + info.Metadata.Version?.ToString() + "."));
}
StopModSyncEngine(((object)info.Instance).GetType());
Type type2 = ((object)info.Instance).GetType().Assembly.GetType("MageArena_StealthSpells.ModSyncUI");
if (type2 != null)
{
messageType = type2.GetNestedType("MessageType", BindingFlags.Public | BindingFlags.NonPublic);
showMessage = AccessTools.Method(type2, "ShowMessage", (Type[])null, (Type[])null);
uiInstance = AccessTools.Property(type2, "Instance");
}
createUi = AccessTools.Method(((object)info.Instance).GetType(), "CreateModSyncUI", (Type[])null, (Type[])null);
if (Plugin.IsSteamReady)
{
CreateCallbacks();
}
else
{
Plugin.SteamReady += CreateCallbacks;
}
}
private void OnDestroy()
{
Plugin.SteamReady -= CreateCallbacks;
}
private void StopModSyncEngine(Type type)
{
//IL_0010: Unknown result type (might be due to invalid IL or missing references)
//IL_0016: Expected O, but got Unknown
//IL_002c: Unknown result type (might be due to invalid IL or missing references)
//IL_0032: Expected O, but got Unknown
//IL_0048: Unknown result type (might be due to invalid IL or missing references)
//IL_004e: Expected O, but got Unknown
modSync.StopAllCoroutines();
Harmony val = new Harmony("magearena.spellmender.modsync");
HarmonyMethod val2 = new HarmonyMethod(AccessTools.Method(typeof(ModSyncFix), "Skip", (Type[])null, (Type[])null));
HarmonyMethod val3 = new HarmonyMethod(AccessTools.Method(typeof(ModSyncFix), "SkipCoroutine", (Type[])null, (Type[])null));
int num = 0;
string[] array = new string[19]
{
"Update", "StartModSync", "StartClientModSync", "InitializeChatSystem", "OnChatMessageReceived", "ReinitializeAfterGame", "KickPlayer", "HandleModSyncFailure", "InitializeModSync", "DelayedStartModSync",
"MonitorLobbyEvents", "MonitorPlayerJoins", "RetryChatSystemInitialization", "RetryChatSystem", "ModSyncTimeout", "LeaveLobbyAfterDelay", "LeaveGameAfterDelay", "CheckPlayerModsWithTimeout", "CheckPlayerModsWithTimeoutAndSteamID"
};
foreach (string name in array)
{
foreach (MethodInfo item in from m in type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
where m.Name == name
select m)
{
try
{
if (item.ReturnType == typeof(void))
{
val.Patch((MethodBase)item, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
goto IL_01ae;
}
if (item.ReturnType == typeof(IEnumerator))
{
val.Patch((MethodBase)item, val3, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
goto IL_01ae;
}
goto end_IL_015c;
IL_01ae:
num++;
end_IL_015c:;
}
catch (Exception ex)
{
log.LogWarning((object)("Could not stop ModSync." + name + ": " + ex.Message));
}
}
}
log.LogInfo((object)("ModSync's own mod check stopped (" + num + " methods); its messages and lobby name are kept."));
}
private static bool Skip()
{
return false;
}
private static bool SkipCoroutine(ref IEnumerator __result)
{
__result = Nothing();
return false;
}
private static IEnumerator Nothing()
{
yield break;
}
private void Start()
{
mine = new Dictionary<string, Mod>();
foreach (PluginInfo value in Chainloader.PluginInfos.Values)
{
if (!((Object)(object)value.Instance == (Object)null))
{
Mod mod = new Mod
{
Guid = value.Metadata.GUID,
Name = Clean(value.Metadata.Name),
Version = value.Metadata.Version.ToString(),
Hash = Hash(value.Location),
Tag = Tag(((object)value.Instance).GetType(), value.Metadata.GUID)
};
mine[mod.Guid] = mod;
}
}
StringBuilder stringBuilder = new StringBuilder("spellmender 1");
foreach (Mod item in mine.Values.OrderBy<Mod, string>((Mod m) => m.Guid, StringComparer.Ordinal))
{
stringBuilder.Append('\n').Append(item.Guid).Append('\t')
.Append(item.Name)
.Append('\t')
.Append(item.Version)
.Append('\t')
.Append(item.Hash)
.Append('\t')
.Append(item.Tag);
}
payload = stringBuilder.ToString();
log.LogInfo((object)("Mod list: " + mine.Count + " plugins, " + mine.Values.Count((Mod m) => m.Tag == "all") + " required by all players (" + payload.Length + " bytes of lobby data)."));
}
private static string Clean(string s)
{
return (s ?? "").Replace('\t', ' ').Replace('\n', ' ').Replace('\r', ' ');
}
private static string Hash(string path)
{
try
{
using MD5 mD = MD5.Create();
return BitConverter.ToString(mD.ComputeHash(File.ReadAllBytes(path)), 0, 4).Replace("-", "").ToLowerInvariant();
}
catch
{
return "?";
}
}
private static string Tag(Type type, string guid)
{
if (guid == "com.looney.overpower" || guid == "com.onigremlin.magustoolkit")
{
return "all";
}
try
{
object obj = null;
FieldInfo field = type.GetField("modsync", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
if (field != null)
{
obj = field.GetValue(null);
}
else
{
PropertyInfo property = type.GetProperty("modsync", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
if (property != null)
{
obj = property.GetValue(null, null);
}
}
if (obj == null)
{
return "-";
}
string text = obj.ToString().Trim().ToLowerInvariant();
object result;
switch (text)
{
default:
result = "-";
break;
case "all":
case "client":
case "host":
result = text;
break;
}
return (string)result;
}
catch
{
return "-";
}
}
private void CreateCallbacks()
{
if (callbacksReady)
{
return;
}
try
{
lobbyEntered = Callback<LobbyEnter_t>.Create((DispatchDelegate<LobbyEnter_t>)OnLobbyEntered);
lobbyChatUpdate = Callback<LobbyChatUpdate_t>.Create((DispatchDelegate<LobbyChatUpdate_t>)OnLobbyChatUpdate);
lobbyDataUpdate = Callback<LobbyDataUpdate_t>.Create((DispatchDelegate<LobbyDataUpdate_t>)OnLobbyDataUpdate);
callbacksReady = true;
log.LogInfo((object)"Listening to Steam lobby events.");
}
catch (Exception ex)
{
log.LogError((object)("Could not register Steam callbacks: " + ex.Message));
}
}
private void OnLobbyEntered(LobbyEnter_t cb)
{
//IL_0000: Unknown result type (might be due to invalid IL or missing references)
//IL_0013: Unknown result type (might be due to invalid IL or missing references)
//IL_005e: Unknown result type (might be due to invalid IL or missing references)
//IL_0070: Unknown result type (might be due to invalid IL or missing references)
//IL_0071: Unknown result type (might be due to invalid IL or missing references)
//IL_0076: Unknown result type (might be due to invalid IL or missing references)
//IL_00df: Unknown result type (might be due to invalid IL or missing references)
if (cb.m_EChatRoomEnterResponse != 1 || payload == null)
{
return;
}
lobby = cb.m_ulSteamIDLobby;
compared.Clear();
waiting.Clear();
mismatched.Clear();
kicks.Clear();
lobbyLock = false;
CSteamID val = default(CSteamID);
((CSteamID)(ref val))..ctor(lobby);
SteamMatchmaking.SetLobbyMemberData(val, "spellmender", payload);
isHost = SteamMatchmaking.GetLobbyOwner(val) == SteamUser.GetSteamID();
log.LogInfo((object)("Entered lobby " + lobby + " as " + (isHost ? "host" : "client") + "; mod list published."));
if (isHost)
{
SteamMatchmaking.SetLobbyData(val, "spellmender", payload);
{
foreach (ulong item in Members())
{
Expect(item);
}
return;
}
}
Expect(lobby);
}
private void OnLobbyChatUpdate(LobbyChatUpdate_t cb)
{
//IL_0000: Unknown result type (might be due to invalid IL or missing references)
//IL_0017: Unknown result type (might be due to invalid IL or missing references)
//IL_001e: Unknown result type (might be due to invalid IL or missing references)
//IL_0031: Unknown result type (might be due to invalid IL or missing references)
if (cb.m_ulSteamIDLobby != lobby || lobby == 0L)
{
return;
}
ulong ulSteamIDUserChanged = cb.m_ulSteamIDUserChanged;
if ((cb.m_rgfChatMemberStateChange & 1) != 0)
{
if (isHost && ulSteamIDUserChanged != SteamUser.GetSteamID().m_SteamID)
{
Expect(ulSteamIDUserChanged);
}
}
else
{
waiting.Remove(ulSteamIDUserChanged);
compared.Remove(ulSteamIDUserChanged);
mismatched.Remove(ulSteamIDUserChanged);
kicks.Remove(ulSteamIDUserChanged);
}
}
private void OnLobbyDataUpdate(LobbyDataUpdate_t cb)
{
//IL_0000: 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_001f: Unknown result type (might be due to invalid IL or missing references)
//IL_0044: 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_0057: Unknown result type (might be due to invalid IL or missing references)
if (cb.m_ulSteamIDLobby != lobby || lobby == 0L || cb.m_bSuccess == 0)
{
return;
}
if (cb.m_ulSteamIDMember == lobby)
{
if (!isHost)
{
CheckHost();
}
}
else if (isHost && cb.m_ulSteamIDMember != SteamUser.GetSteamID().m_SteamID)
{
CheckMember(cb.m_ulSteamIDMember);
}
}
private IEnumerable<ulong> Members()
{
CSteamID id = new CSteamID(lobby);
ulong me = SteamUser.GetSteamID().m_SteamID;
int n = SteamMatchmaking.GetNumLobbyMembers(id);
for (int i = 0; i < n; i++)
{
ulong steamID = SteamMatchmaking.GetLobbyMemberByIndex(id, i).m_SteamID;
if (steamID != me)
{
yield return steamID;
}
}
}
private void Expect(ulong who)
{
waiting[who] = Time.unscaledTime + 15f;
if (who == lobby)
{
CheckHost();
}
else
{
CheckMember(who);
}
}
private void CheckHost()
{
//IL_0006: Unknown result type (might be due to invalid IL or missing references)
//IL_0068: Unknown result type (might be due to invalid IL or missing references)
//IL_006d: 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_0074: Unknown result type (might be due to invalid IL or missing references)
string lobbyData = SteamMatchmaking.GetLobbyData(new CSteamID(lobby), "spellmender");
if (!string.IsNullOrEmpty(lobbyData))
{
waiting.Remove(lobby);
if (!compared.TryGetValue(lobby, out var value) || !(value == lobbyData))
{
compared[lobby] = lobbyData;
CSteamID lobbyOwner = SteamMatchmaking.GetLobbyOwner(new CSteamID(lobby));
Report(SteamFriends.GetFriendPersonaName(lobbyOwner), lobbyData, 0uL, withHost: true);
}
}
}
private void CheckMember(ulong member)
{
//IL_0006: Unknown result type (might be due to invalid IL or missing references)
//IL_000c: Unknown result type (might be due to invalid IL or missing references)
//IL_005b: Unknown result type (might be due to invalid IL or missing references)
string lobbyMemberData = SteamMatchmaking.GetLobbyMemberData(new CSteamID(lobby), new CSteamID(member), "spellmender");
if (!string.IsNullOrEmpty(lobbyMemberData))
{
waiting.Remove(member);
if (!compared.TryGetValue(member, out var value) || !(value == lobbyMemberData))
{
compared[member] = lobbyMemberData;
Report(SteamFriends.GetFriendPersonaName(new CSteamID(member)), lobbyMemberData, member, withHost: false);
}
}
}
private static Dictionary<string, Mod> Parse(string data)
{
Dictionary<string, Mod> dictionary = new Dictionary<string, Mod>();
string[] array = data.Split('\n');
for (int i = 1; i < array.Length; i++)
{
string[] array2 = array[i].Split('\t');
if (array2.Length >= 5)
{
dictionary[array2[0]] = new Mod
{
Guid = array2[0],
Name = array2[1],
Version = array2[2],
Hash = array2[3],
Tag = array2[4]
};
}
}
return dictionary;
}
private void Report(string name, string data, ulong member, bool withHost)
{
if (!data.StartsWith("spellmender 1"))
{
Show(3, "ModSync: " + name + " has another version of Spellmender; cannot compare mods.");
log.LogWarning((object)(name + " sent mod data in another format: " + data.Split('\n')[0]));
return;
}
Dictionary<string, Mod> dictionary = Parse(data);
List<string> list = new List<string>();
List<string> list2 = new List<string>();
List<string> list3 = new List<string>();
List<string> list4 = new List<string>();
List<string> list5 = new List<string>();
List<string> list6 = new List<string>();
foreach (Mod value2 in mine.Values)
{
if (value2.Tag == "client" || value2.Tag == "host")
{
continue;
}
if (!dictionary.TryGetValue(value2.Guid, out var value))
{
((value2.Tag == "all") ? list : list5).Add(value2.Name);
}
else if (!(value.Tag == "client") && !(value.Tag == "host"))
{
if (value.Version != value2.Version)
{
list3.Add(value2.Name + " (" + value2.Version + " / " + value.Version + ")");
}
else if (value.Hash != value2.Hash && value.Hash != "?" && value2.Hash != "?")
{
list4.Add(value2.Name);
}
}
}
foreach (Mod value3 in dictionary.Values)
{
if (!mine.ContainsKey(value3.Guid) && !(value3.Tag == "client") && !(value3.Tag == "host"))
{
((value3.Tag == "all") ? list2 : list6).Add(value3.Name);
}
}
string text = (withHost ? ("the host (" + name + ")") : name);
string text2 = (withHost ? "the host" : name);
string text3 = (withHost ? "The host" : name);
bool flag = list.Count + list2.Count + list3.Count + list4.Count > 0;
bool flag2 = list5.Count + list6.Count > 0;
log.LogInfo((object)("Compared with " + (withHost ? "host " : "player ") + name + ": " + (flag ? "MISMATCH" : "match") + Detail(" | missing there: ", list) + Detail(" | missing here: ", list2) + Detail(" | versions (here / there): ", list3) + Detail(" | different file, same version: ", list4) + Detail(" | untagged, only here: ", list5) + Detail(" | untagged, only there: ", list6)));
if (!flag)
{
Show(1, "ModSync: " + (withHost ? ("same mods as the host (" + name + ").") : (name + " has the same mods as you.")));
}
else
{
Show(3, "ModSync: mods differ from " + text + ".");
if (list.Count > 0)
{
Show(3, text3 + " is missing: " + List(list));
}
if (list2.Count > 0)
{
Show(3, "You are missing: " + List(list2));
}
if (list3.Count > 0)
{
Show(3, "Versions (you / " + text2 + "): " + List(list3));
}
if (list4.Count > 0)
{
Show(3, "Same version, different file: " + List(list4));
}
}
if (flag2)
{
Show(2, "Other mods (no modsync tag): " + ((list5.Count > 0) ? (text2 + " is missing " + List(list5)) : "") + ((list5.Count > 0 && list6.Count > 0) ? "; " : "") + ((list6.Count > 0) ? ("you are missing " + List(list6)) : ""));
}
if (member == 0L)
{
return;
}
if (flag)
{
mismatched.Add(member);
if (lobbyLock)
{
Kick(member, name);
}
}
else
{
mismatched.Remove(member);
kicks.Remove(member);
}
}
private static string Detail(string label, List<string> items)
{
if (items.Count != 0)
{
return label + string.Join(", ", items.ToArray());
}
return "";
}
private static string List(List<string> items)
{
if (items.Count > 4)
{
return string.Join(", ", items.Take(4).ToArray()) + " and " + (items.Count - 4) + " more";
}
return string.Join(", ", items.ToArray());
}
private void Show(int level, string text)
{
try
{
if (showMessage != null && messageType != null)
{
showMessage.Invoke(null, new object[2]
{
text,
Enum.ToObject(messageType, level)
});
return;
}
}
catch (Exception ex)
{
log.LogWarning((object)("ModSync message not shown: " + ex.Message));
}
log.LogInfo((object)("[message] " + text));
}
private void Kick(ulong member, string name)
{
if (!kicks.ContainsKey(member))
{
kicks[member] = Time.unscaledTime + 60f;
log.LogInfo((object)("Lobby lock: kicking " + name + " (" + member + ") once connected."));
}
}
private void TryKicks()
{
//IL_0066: Unknown result type (might be due to invalid IL or missing references)
if (kicks.Count == 0)
{
return;
}
object value = bootstrapInstance.GetValue(null, null);
IDictionary dictionary = ((value == null || connectionsField == null) ? null : (connectionsField.GetValue(value) as IDictionary));
foreach (ulong item in kicks.Keys.ToList())
{
string friendPersonaName = SteamFriends.GetFriendPersonaName(new CSteamID(item));
object obj = null;
if (dictionary != null)
{
foreach (DictionaryEntry item2 in dictionary)
{
if (item2.Value is CSteamID && ((CSteamID)item2.Value).m_SteamID == item)
{
obj = item2.Key;
break;
}
}
}
if (obj != null && kickPlayer != null)
{
try
{
kickPlayer.Invoke(null, new object[1] { obj });
Show(3, "ModSync: " + friendPersonaName + " kicked (lobby lock).");
log.LogInfo((object)("Lobby lock: kicked " + friendPersonaName + " (" + item + ")."));
}
catch (Exception ex)
{
log.LogError((object)("Lobby lock: kicking " + friendPersonaName + " failed: " + (ex.InnerException ?? ex).Message));
}
kicks.Remove(item);
}
else if (Time.unscaledTime > kicks[item])
{
log.LogWarning((object)("Lobby lock: " + friendPersonaName + " never got a game connection; not kicked."));
kicks.Remove(item);
}
}
}
private void Update()
{
//IL_000a: Unknown result type (might be due to invalid IL or missing references)
//IL_000f: Unknown result type (might be due to invalid IL or missing references)
//IL_0158: Unknown result type (might be due to invalid IL or missing references)
//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
//IL_0236: Unknown result type (might be due to invalid IL or missing references)
//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
//IL_02f6: Unknown result type (might be due to invalid IL or missing references)
KeyboardShortcut value = Plugin.Instance.LobbyLockKey.Value;
if (((KeyboardShortcut)(ref value)).IsDown())
{
if (lobby == 0L)
{
Show(0, "ModSync: not in a lobby.");
}
else if (!isHost)
{
Show(2, "ModSync: only the host can lock the lobby.");
}
else
{
lobbyLock = !lobbyLock;
log.LogInfo((object)("Lobby lock " + (lobbyLock ? "on" : "off")));
if (lobbyLock)
{
Show(2, "ModSync: lobby locked. Players with different mods or without Spellmender will be kicked.");
foreach (ulong item in mismatched)
{
Kick(item, SteamFriends.GetFriendPersonaName(new CSteamID(item)));
}
}
else
{
kicks.Clear();
Show(0, "ModSync: lobby unlocked.");
}
}
}
if (Time.unscaledTime < nextPoll)
{
return;
}
nextPoll = Time.unscaledTime + 0.5f;
if (!callbacksReady && Time.unscaledTime > 10f && bootstrapInstance.GetValue(null, null) != null)
{
CreateCallbacks();
}
KeepUiAlive();
if (lobby == 0L)
{
return;
}
CSteamID val = default(CSteamID);
((CSteamID)(ref val))..ctor(lobby);
if (SteamMatchmaking.GetNumLobbyMembers(val) == 0)
{
log.LogInfo((object)("Left lobby " + lobby + "."));
lobby = 0uL;
isHost = false;
lobbyLock = false;
compared.Clear();
waiting.Clear();
mismatched.Clear();
kicks.Clear();
return;
}
bool flag = SteamMatchmaking.GetLobbyOwner(val) == SteamUser.GetSteamID();
if (flag != isHost)
{
isHost = flag;
log.LogInfo((object)("Lobby owner changed; now " + (isHost ? "host" : "client") + "."));
compared.Clear();
waiting.Clear();
if (isHost)
{
SteamMatchmaking.SetLobbyData(val, "spellmender", payload);
foreach (ulong item2 in Members())
{
Expect(item2);
}
}
else
{
Expect(lobby);
}
}
foreach (KeyValuePair<ulong, float> item3 in waiting.ToList())
{
if (Time.unscaledTime < item3.Value)
{
continue;
}
waiting.Remove(item3.Key);
if (item3.Key == lobby)
{
Show(2, "ModSync: the host does not have Spellmender; cannot compare mods.");
continue;
}
string friendPersonaName = SteamFriends.GetFriendPersonaName(new CSteamID(item3.Key));
Show(2, "ModSync: " + friendPersonaName + " does not have Spellmender; cannot compare their mods.");
log.LogInfo((object)(friendPersonaName + " (" + item3.Key + ") published no mod list within " + 15f + " s."));
mismatched.Add(item3.Key);
if (lobbyLock)
{
Kick(item3.Key, friendPersonaName);
}
}
TryKicks();
}
private void KeepUiAlive()
{
try
{
if (!(uiInstance == null) && !(createUi == null) && !((Object)(object)modSync == (Object)null) && (Object)/*isinst with value type is only supported in some contexts*/ == (Object)null)
{
createUi.Invoke(modSync, null);
}
}
catch
{
}
}
}
public enum Team
{
Auto,
Sorcerer,
Warlock
}
[BepInPlugin("magearena.spellmender", "Spellmender", "1.0.1")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public class Plugin : BaseUnityPlugin
{
public const string Guid = "magearena.spellmender";
public const string Name = "Spellmender";
public const string Version = "1.0.1";
public const string MageConfigurationApiGuid = "com.d1gq.mage.configuration.api";
private const string OldLocalGuid = "local.magearena.fixes";
public const string BlackMagicApiGuid = "com.d1gq.black.magic.api";
public const string FishUtilitiesGuid = "com.d1gq.fish.utilities";
public const string ModSyncGuid = "com.magearena.modsync";
public static string modsync = "all";
internal static Plugin Instance;
internal static ManualLogSource Log;
internal static bool IsSteamReady;
internal ConfigEntry<bool> FixBlackMagicApi;
internal ConfigEntry<bool> FixFishUtilities;
internal ConfigEntry<bool> FixModSync;
internal ConfigEntry<bool> EnableSteamJoin;
internal ConfigEntry<bool> SpellCastDiagnostics;
internal ConfigEntry<bool> FixMageConfigurationApi;
internal ConfigEntry<bool> FixEscapeMenu;
internal ConfigEntry<Team> JoinTeam;
internal ConfigEntry<bool> ShowJoinGame;
internal ConfigEntry<KeyboardShortcut> InviteKey;
internal ConfigEntry<KeyboardShortcut> LobbyLockKey;
internal static event Action SteamReady;
private void Awake()
{
//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
//IL_015e: Unknown result type (might be due to invalid IL or missing references)
//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
//IL_0204: Unknown result type (might be due to invalid IL or missing references)
//IL_0211: Expected O, but got Unknown
Instance = this;
Log = ((BaseUnityPlugin)this).Logger;
FixBlackMagicApi = ((BaseUnityPlugin)this).Config.Bind<bool>("BlackMagicAPI", "Fix", true, "Install the BlackMagicAPI 3.0.2 patches its own startup skips on this game build (without them the host kicks its own client).");
((BaseUnityPlugin)this).Config.Bind<bool>("BlackMagicAPI", "PatchForOldSpellMods", true, "Before the game loads the mods, rewrites BlackMagicAPI.dll so spell mods written for the old API (1.x/2.x) load and cast. Mods for BlackMagicAPI 3.x are unaffected.");
SpellCastDiagnostics = ((BaseUnityPlugin)this).Config.Bind<bool>("BlackMagicAPI", "SpellCastDiagnostics", false, "Log each step of every spell cast ([diag] lines), to investigate spells that do not show for other players.");
FixFishUtilities = ((BaseUnityPlugin)this).Config.Bind<bool>("FishUtilities", "Fix", true, "Relay FishUtilities' messages through the players' objects, so modded spells (Hellfire, Martial Law...) show for every player.");
FixModSync = ((BaseUnityPlugin)this).Config.Bind<bool>("ModSync", "Fix", true, "Replace ModSync's broken mod check with one through Steam lobby data. ModSync's F8 (FRIENDSMODE) is off with it.");
LobbyLockKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("ModSync", "LobbyLockKey", new KeyboardShortcut((KeyCode)290, Array.Empty<KeyCode>()), "Host only: toggles the lobby lock, which kicks players whose required mods differ or who do not have Spellmender.");
EnableSteamJoin = ((BaseUnityPlugin)this).Config.Bind<bool>("Steam Join", "Enabled", true, "Join a friend's lobby, private ones included, from Steam (Join Game, invites) instead of typing the code.");
JoinTeam = ((BaseUnityPlugin)this).Config.Bind<Team>("Steam Join", "Team", Team.Auto, "Team used when joining from Steam. Auto = the team with fewer players, else Sorcerer.");
ShowJoinGame = ((BaseUnityPlugin)this).Config.Bind<bool>("Steam Join", "ShowJoinGame", true, "While in a lobby, show \"Join Game\" to your Steam friends (private lobbies included).");
InviteKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Steam Join", "InviteKey", new KeyboardShortcut((KeyCode)289, Array.Empty<KeyCode>()), "Opens Steam's invite dialog for the current lobby (Steam overlay must be enabled).");
FixMageConfigurationApi = ((BaseUnityPlugin)this).Config.Bind<bool>("MageConfigurationAPI", "Fix", true, "Catch MageConfigurationAPI's error when a lobby or game loads (it looks for a main menu layout the game no longer has). Its Mod Settings menu stays in the main menu.");
FixEscapeMenu = ((BaseUnityPlugin)this).Config.Bind<bool>("Escape Menu", "Fix", true, "Open the in-game menu with Escape when the game's own check is stuck (menu script not running, spell book state left over). The log says why when it happens.");
Type type = AccessTools.TypeByName("BootstrapManager");
MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "Start", (Type[])null, (Type[])null));
if (methodInfo != null)
{
new Harmony("magearena.spellmender").Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(Plugin), "AfterBootstrapStart", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
}
else
{
Log.LogError((object)"BootstrapManager.Start not found: this Mage Arena build is different.");
}
}
private static void AfterBootstrapStart()
{
IsSteamReady = true;
Plugin.SteamReady?.Invoke();
}
private void Start()
{
if (Loaded("local.magearena.fixes"))
{
Log.LogWarning((object)"Mage Arena Fixes, this mod's earlier local build, is still installed and does the same work: Spellmender stays off. Delete BepInEx\\plugins\\local-MageArenaFixes and BepInEx\\patchers\\local-MageArenaFixes.");
return;
}
bool flag = Loaded("local.blackmagicapi.fix");
bool flag2 = Loaded("local.modsync.fix");
bool flag3 = Loaded("local.steamjoin");
if (flag || flag2 || flag3)
{
Log.LogWarning((object)("The separate fix plugins this mod replaces are still installed: " + (flag ? "local-BlackMagicApiFix " : "") + (flag2 ? "local-ModSyncFix " : "") + (flag3 ? "local-SteamJoin " : "") + "(delete their folders in BepInEx\\plugins). Their parts of Spellmender are off meanwhile."));
}
if (Chainloader.PluginInfos.TryGetValue("com.d1gq.black.magic.api", out var value) && (Object)(object)value.Instance != (Object)null)
{
PluginInfo bmapi = value;
if (!flag && FixBlackMagicApi.Value)
{
Part("BlackMagicAPI", delegate
{
BlackMagicApiFix.Install(bmapi);
});
}
if (!flag && SpellCastDiagnostics.Value)
{
Part("spell-cast diagnostics", delegate
{
//IL_0005: Unknown result type (might be due to invalid IL or missing references)
//IL_000f: Expected O, but got Unknown
Diag.Install(new Harmony("magearena.spellmender.diag"));
});
}
BlackMagicApiFix.ReportOldSpellMods(bmapi);
}
if (Loaded("com.d1gq.fish.utilities") && FixFishUtilities.Value && !flag)
{
Part("FishUtilities", delegate
{
//IL_0005: Unknown result type (might be due to invalid IL or missing references)
//IL_0010: Expected O, but got Unknown
FishRelay.Install(new Harmony("magearena.spellmender.relay"), (MonoBehaviour)(object)this);
});
}
if (Chainloader.PluginInfos.TryGetValue("com.magearena.modsync", out value) && (Object)(object)value.Instance != (Object)null && FixModSync.Value && !flag2)
{
PluginInfo modSync = value;
Part("ModSync", delegate
{
((Component)this).gameObject.AddComponent<ModSyncFix>().Init(modSync);
});
}
if (EnableSteamJoin.Value && !flag3)
{
Part("Steam Join", delegate
{
((Component)this).gameObject.AddComponent<SteamJoin>();
});
}
if (Chainloader.PluginInfos.TryGetValue("com.d1gq.mage.configuration.api", out value) && (Object)(object)value.Instance != (Object)null && FixMageConfigurationApi.Value)
{
PluginInfo mca = value;
Part("MageConfigurationAPI", delegate
{
//IL_0005: Unknown result type (might be due to invalid IL or missing references)
//IL_0015: Expected O, but got Unknown
MageConfigurationApiFix.Install(new Harmony("magearena.spellmender.mca"), mca);
});
}
if (FixEscapeMenu.Value)
{
Part("Escape menu", delegate
{
//IL_0012: Unknown result type (might be due to invalid IL or missing references)
//IL_001c: Expected O, but got Unknown
EscapeMenuGuard escapeMenuGuard = ((Component)this).gameObject.AddComponent<EscapeMenuGuard>();
try
{
escapeMenuGuard.Init(new Harmony("magearena.spellmender.escape"));
}
catch
{
Object.Destroy((Object)(object)escapeMenuGuard);
throw;
}
});
}
Log.LogInfo((object)("Spellmender 1.0.1 ready: BlackMagicAPI " + State("com.d1gq.black.magic.api", FixBlackMagicApi, flag) + ", FishUtilities " + State("com.d1gq.fish.utilities", FixFishUtilities, flag) + ", ModSync " + State("com.magearena.modsync", FixModSync, flag2) + ", MageConfigurationAPI " + State("com.d1gq.mage.configuration.api", FixMageConfigurationApi, old: false) + ", Steam Join " + (flag3 ? "off (old plugin)" : (EnableSteamJoin.Value ? "on" : "off")) + ", Escape menu " + (FixEscapeMenu.Value ? "on" : "off") + "."));
}
private static string State(string guid, ConfigEntry<bool> setting, bool old)
{
if (!Loaded(guid))
{
return "not installed";
}
if (old)
{
return "off (old plugin)";
}
if (!setting.Value)
{
return "off";
}
return "fixed";
}
internal static bool Loaded(string guid)
{
if (Chainloader.PluginInfos.TryGetValue(guid, out var value))
{
return (Object)(object)value.Instance != (Object)null;
}
return false;
}
private static void Part(string name, Action install)
{
try
{
install();
}
catch (Exception e)
{
Log.LogError((object)(name + " fix not installed: " + Message(e)));
}
}
internal static string Message(Exception e)
{
while (e is TargetInvocationException && e.InnerException != null)
{
e = e.InnerException;
}
return e.GetType().Name + ": " + e.Message;
}
}
internal static class Settings
{
public const string ConfigFileName = "magearena.spellmender.cfg";
public const string PatchSection = "BlackMagicAPI";
public const string PatchKey = "PatchForOldSpellMods";
public const string PatchDescription = "Before the game loads the mods, rewrites BlackMagicAPI.dll so spell mods written for the old API (1.x/2.x) load and cast. Mods for BlackMagicAPI 3.x are unaffected.";
}
public class SteamJoin : MonoBehaviour
{
private static readonly ManualLogSource log = Logger.CreateLogSource("Steam Join");
private Type menuType;
private PropertyInfo bootstrapInstance;
private FieldInfo currentLobbyField;
private MethodInfo joinById;
private Callback<GameLobbyJoinRequested_t> lobbyJoinRequested;
private Callback<GameRichPresenceJoinRequested_t> presenceJoinRequested;
private Callback<LobbyDataUpdate_t> lobbyDataUpdated;
private bool callbacksReady;
private ulong pendingLobby;
private float pendingSince;
private ulong advertised;
private ulong currentLobby;
private bool inMenu;
private float nextPoll;
private float lastJoin = -10f;
private ulong waitingForData;
private bool dataArrived;
private Plugin cfg => Plugin.Instance;
private void Awake()
{
//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
Type type = AccessTools.TypeByName("BootstrapManager");
menuType = AccessTools.TypeByName("MainMenuController");
bootstrapInstance = ((type == null) ? null : AccessTools.Property(type, "instance"));
currentLobbyField = ((type == null) ? null : AccessTools.Field(type, "CurrentLobbyID"));
joinById = ((type == null) ? null : AccessTools.Method(type, "JoinByID", new Type[2]
{
typeof(CSteamID),
typeof(bool)
}, (Type[])null));
if (menuType == null || bootstrapInstance == null || currentLobbyField == null || joinById == null)
{
log.LogError((object)"This Mage Arena build is different (BootstrapManager / MainMenuController changed); Steam Join is off.");
((Behaviour)this).enabled = false;
return;
}
if (Plugin.IsSteamReady)
{
CreateCallbacks();
}
else
{
Plugin.SteamReady += CreateCallbacks;
}
string[] commandLineArgs = Environment.GetCommandLineArgs();
for (int i = 0; i + 1 < commandLineArgs.Length; i++)
{
if (commandLineArgs[i] == "+connect_lobby" && ulong.TryParse(commandLineArgs[i + 1], out var result) && result != 0L)
{
Queue(result, "command line");
}
}
log.LogInfo((object)("Steam Join ready: team " + cfg.JoinTeam.Value.ToString() + ", Join Game " + (cfg.ShowJoinGame.Value ? "shown" : "hidden") + ", invite key " + ((object)cfg.InviteKey.Value/*cast due to .constrained prefix*/).ToString()));
}
private void CreateCallbacks()
{
if (callbacksReady)
{
return;
}
try
{
lobbyJoinRequested = Callback<GameLobbyJoinRequested_t>.Create((DispatchDelegate<GameLobbyJoinRequested_t>)OnLobbyJoinRequested);
presenceJoinRequested = Callback<GameRichPresenceJoinRequested_t>.Create((DispatchDelegate<GameRichPresenceJoinRequested_t>)OnPresenceJoinRequested);
lobbyDataUpdated = Callback<LobbyDataUpdate_t>.Create((DispatchDelegate<LobbyDataUpdate_t>)OnLobbyDataUpdated);
callbacksReady = true;
log.LogInfo((object)"Listening for Steam join requests.");
}
catch (Exception ex)
{
log.LogError((object)("Could not register Steam callbacks: " + ex.Message));
}
}
private void Update()
{
//IL_000b: Unknown result type (might be due to invalid IL or missing references)
//IL_0010: Unknown result type (might be due to invalid IL or missing references)
//IL_0030: Unknown result type (might be due to invalid IL or missing references)
KeyboardShortcut value = cfg.InviteKey.Value;
if (((KeyboardShortcut)(ref value)).IsDown())
{
if (currentLobby != 0L && !inMenu)
{
SteamFriends.ActivateGameOverlayInviteDialog(new CSteamID(currentLobby));
log.LogInfo((object)("Invite dialog opened for lobby " + currentLobby));
}
else
{
log.LogInfo((object)"Invite key: not in a lobby.");
}
}
if (Time.unscaledTime < nextPoll)
{
return;
}
nextPoll = Time.unscaledTime + 0.5f;
object? value2 = bootstrapInstance.GetValue(null, null);
Object val = (Object)((value2 is Object) ? value2 : null);
if (val == (Object)null)
{
return;
}
if (!callbacksReady && Time.unscaledTime > 10f)
{
CreateCallbacks();
}
inMenu = Object.FindAnyObjectByType(menuType) != (Object)null;
currentLobby = (inMenu ? 0 : ((ulong)currentLobbyField.GetValue(val)));
if (pendingLobby != 0L)
{
if (Time.unscaledTime - pendingSince > 120f)
{
log.LogInfo((object)("Join request for lobby " + pendingLobby + " dropped (not back in the menu within 2 minutes)."));
pendingLobby = 0uL;
}
else if (inMenu && callbacksReady)
{
ulong lobby = pendingLobby;
pendingLobby = 0uL;
((MonoBehaviour)this).StartCoroutine(Join(lobby));
}
}
ulong num = (cfg.ShowJoinGame.Value ? currentLobby : 0);
if (num != advertised && callbacksReady)
{
if (num == 0L)
{
SteamFriends.ClearRichPresence();
log.LogInfo((object)"Join Game hidden.");
}
else
{
SteamFriends.SetRichPresence("connect", "+connect_lobby " + num);
log.LogInfo((object)("Join Game shown to Steam friends for lobby " + num));
}
advertised = num;
}
}
private void OnDestroy()
{
Plugin.SteamReady -= CreateCallbacks;
if (advertised != 0L)
{
try
{
SteamFriends.ClearRichPresence();
}
catch (InvalidOperationException)
{
}
}
}
private void OnLobbyJoinRequested(GameLobbyJoinRequested_t cb)
{
//IL_0001: Unknown result type (might be due to invalid IL or missing references)
//IL_0002: Unknown result type (might be due to invalid IL or missing references)
Queue(cb.m_steamIDLobby.m_SteamID, "Steam (lobby invite or Join Game) from " + cb.m_steamIDFriend.m_SteamID);
}
private void OnPresenceJoinRequested(GameRichPresenceJoinRequested_t cb)
{
ulong num = ParseConnect(((GameRichPresenceJoinRequested_t)(ref cb)).m_rgchConnect);
if (num == 0L)
{
log.LogWarning((object)("Steam join request without a lobby: \"" + ((GameRichPresenceJoinRequested_t)(ref cb)).m_rgchConnect + "\""));
}
else
{
Queue(num, "Steam (Join Game / invite) from " + cb.m_steamIDFriend.m_SteamID);
}
}
private void OnLobbyDataUpdated(LobbyDataUpdate_t cb)
{
//IL_0000: Unknown result type (might be due to invalid IL or missing references)
if (cb.m_ulSteamIDLobby == waitingForData)
{
dataArrived = true;
}
}
private static ulong ParseConnect(string connect)
{
if (string.IsNullOrEmpty(connect))
{
return 0uL;
}
string[] array = connect.Split(new char[2] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < array.Length; i++)
{
if (ulong.TryParse(array[i], out var result) && result != 0L)
{
return result;
}
}
return 0uL;
}
private void Queue(ulong lobby, string source)
{
log.LogInfo((object)("Join request for lobby " + lobby + " via " + source));
if (inMenu && callbacksReady)
{
((MonoBehaviour)this).StartCoroutine(Join(lobby));
return;
}
pendingLobby = lobby;
pendingSince = Time.unscaledTime;
log.LogInfo((object)"Will join once in the main menu.");
}
private IEnumerator Join(ulong lobby)
{
if (Time.unscaledTime - lastJoin < 3f)
{
yield break;
}
lastJoin = Time.unscaledTime;
CSteamID id = new CSteamID(lobby);
bool sorcerer = cfg.JoinTeam.Value != Team.Warlock;
if (cfg.JoinTeam.Value == Team.Auto)
{
string lobbyData = SteamMatchmaking.GetLobbyData(id, "playercounts");
if (string.IsNullOrEmpty(lobbyData))
{
waitingForData = lobby;
dataArrived = false;
SteamMatchmaking.RequestLobbyData(id);
float until = Time.unscaledTime + 3f;
while (!dataArrived && Time.unscaledTime < until)
{
yield return null;
}
waitingForData = 0uL;
lobbyData = SteamMatchmaking.GetLobbyData(id, "playercounts");
}
string[] array = (lobbyData ?? "").Split(',');
if (array.Length == 2 && int.TryParse(array[0], out var result) && int.TryParse(array[1], out var result2))
{
sorcerer = result <= result2;
log.LogInfo((object)("Lobby has " + result + " sorcerer(s), " + result2 + " warlock(s)."));
}
else
{
log.LogInfo((object)"Lobby player counts unknown, joining as Sorcerer.");
}
}
log.LogInfo((object)("Joining lobby " + lobby + " as " + (sorcerer ? "Sorcerer" : "Warlock") + "."));
try
{
joinById.Invoke(null, new object[2] { id, sorcerer });
}
catch (Exception innerException)
{
while (innerException is TargetInvocationException && innerException.InnerException != null)
{
innerException = innerException.InnerException;
}
log.LogError((object)("JoinByID failed: " + innerException.GetType().Name + ": " + innerException.Message));
}
}
}