Decompiled source of Classic Chat Everywhere v1.0.0

plugins/GlobalChat.dll

Decompiled 16 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("BenjSammy")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("GlobalChat")]
[assembly: AssemblyTitle("GlobalChat")]
[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 BenjSammy.GlobalChat
{
	internal sealed class ConfigurationManagerAttributes
	{
		public string DispName;

		public string Category;

		public Action<ConfigEntryBase> CustomDrawer;
	}
	[BepInPlugin("benjsammy.globalchat", "Classic Chat Everywhere by BenjSammy", "1.0.0")]
	public sealed class GlobalChat : BaseUnityPlugin
	{
		private delegate void PrepareChatMessage(string text, bool filter, out UserInfo user, out string message);

		private const string Id = "benjsammy.globalchat";

		private const string ChatTranslateId = "benjsammy.valheimchattranslate";

		private const string PresenceRpc = "BenjSammy.ClassicChatEverywhere.Presence.v1";

		private const string DistantChatRpc = "BenjSammy.ClassicChatEverywhere.Message.v1";

		private const long BroadcastPeerId = 0L;

		private const float PresenceInterval = 10f;

		private const float PresenceLifetime = 30f;

		private static GlobalChat plugin;

		private readonly Dictionary<long, (bool Receive, float LastSeen)> peers = new Dictionary<long, (bool, float)>();

		private ZRoutedRpc router;

		private float nextPresence;

		private static Action<SendChatMessageRPCHandler> sendToPermittedPlayers;

		private static Action<Chat, long, Vector3, int, UserInfo, string> receiveChat;

		private static Func<long> localUid;

		private static PrepareChatMessage prepareMessage;

		private static ConfigEntry<bool> sendEverywhere;

		private static ConfigEntry<bool> receiveFar;

		private static FieldRef<Talker, float> normalRange;

		private Harmony harmony;

		private void Awake()
		{
			//IL_02ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b5: Expected O, but got Unknown
			//IL_02cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d3: Expected O, but got Unknown
			bool flag = UsesFrench();
			sendEverywhere = BindToggle("Send everywhere", flag ? "Envoyer partout" : "Send everywhere", flag ? "Envoie aussi tes messages aux joueurs équipés du mod qui acceptent les messages lointains." : "Also send your messages to players using the mod who accept distant chat.", flag);
			receiveFar = BindToggle("Receive distant messages", flag ? "Recevoir les messages lointains" : "Receive distant messages", flag ? "Affiche les messages lointains des joueurs équipés du mod qui activent Envoyer partout." : "Show distant messages from players using the mod with Send everywhere enabled.", flag);
			receiveFar.SettingChanged += delegate
			{
				nextPresence = 0f;
			};
			MethodInfo methodInfo = AccessTools.Method(typeof(Chat), "RPC_ChatMessage", new Type[5]
			{
				typeof(long),
				typeof(Vector3),
				typeof(int),
				typeof(UserInfo),
				typeof(string)
			}, (Type[])null);
			FieldInfo fieldInfo = AccessTools.Field(typeof(Talker), "m_normalDistance");
			if (fieldInfo?.FieldType == typeof(float))
			{
				normalRange = AccessTools.FieldRefAccess<Talker, float>(fieldInfo);
			}
			MethodInfo methodInfo2 = AccessTools.Method(typeof(Chat), "SendText", new Type[2]
			{
				typeof(Type),
				typeof(string)
			}, (Type[])null);
			MethodInfo methodInfo3 = AccessTools.Method(typeof(Chat), "CheckPermissionsAndSendChatMessageRPCsAsync", new Type[1] { typeof(SendChatMessageRPCHandler) }, (Type[])null);
			Type type = typeof(UserInfo).MakeByRefType();
			Type type2 = typeof(string).MakeByRefType();
			MethodInfo methodInfo4 = AccessTools.Method(typeof(Chat), "GetChatMessageData", new Type[4]
			{
				typeof(string),
				typeof(bool),
				type,
				type2
			}, (Type[])null);
			MethodInfo methodInfo5 = AccessTools.Method(typeof(ZNet), "GetUID", Type.EmptyTypes, (Type[])null);
			if (methodInfo2 == null || methodInfo == null || methodInfo3 == null || methodInfo4 == null || methodInfo5 == null)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"Valheim chat methods were not found.");
				return;
			}
			sendToPermittedPlayers = (Action<SendChatMessageRPCHandler>)methodInfo3.CreateDelegate(typeof(Action<SendChatMessageRPCHandler>));
			prepareMessage = (PrepareChatMessage)methodInfo4.CreateDelegate(typeof(PrepareChatMessage));
			receiveChat = (Action<Chat, long, Vector3, int, UserInfo, string>)methodInfo.CreateDelegate(typeof(Action<Chat, long, Vector3, int, UserInfo, string>));
			localUid = (Func<long>)methodInfo5.CreateDelegate(typeof(Func<long>));
			plugin = this;
			harmony = new Harmony("benjsammy.globalchat");
			try
			{
				Harmony obj = harmony;
				HarmonyMethod val = new HarmonyMethod(typeof(GlobalChat), "SendDistantChat", (Type[])null);
				val.priority = 0;
				val.after = new string[1] { "benjsammy.valheimchattranslate" };
				obj.Patch((MethodBase)methodInfo2, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			catch
			{
				harmony.UnpatchSelf();
				throw;
			}
		}

		private void OnDestroy()
		{
			Harmony obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			if ((Object)(object)plugin == (Object)(object)this)
			{
				plugin = null;
			}
		}

		private void Update()
		{
			if ((Object)(object)plugin != (Object)(object)this)
			{
				return;
			}
			if (router != ZRoutedRpc.instance)
			{
				router = ZRoutedRpc.instance;
				peers.Clear();
				nextPresence = 0f;
				ZRoutedRpc obj = router;
				if (obj != null)
				{
					obj.Register<bool, bool>("BenjSammy.ClassicChatEverywhere.Presence.v1", (Action<long, bool, bool>)ReceivePresence);
				}
				ZRoutedRpc obj2 = router;
				if (obj2 != null)
				{
					obj2.Register<Vector3, Vector3, UserInfo, string>("BenjSammy.ClassicChatEverywhere.Message.v1", (Method<Vector3, Vector3, UserInfo, string>)ReceiveDistantChat);
				}
			}
			if (router == null || (Object)(object)Player.m_localPlayer == (Object)null)
			{
				return;
			}
			float now = Time.unscaledTime;
			if (!(now < nextPresence))
			{
				nextPresence = now + 10f;
				long[] array = (from entry in peers
					where now - entry.Value.LastSeen > 30f
					select entry.Key).ToArray();
				foreach (long key in array)
				{
					peers.Remove(key);
				}
				router.InvokeRoutedRPC(0L, "BenjSammy.ClassicChatEverywhere.Presence.v1", new object[2] { receiveFar.Value, true });
			}
		}

		private void ReceivePresence(long sender, bool acceptsDistantChat, bool requestReply)
		{
			if (!((Object)(object)plugin != (Object)(object)this) && router == ZRoutedRpc.instance && sender != localUid() && sender != 0L)
			{
				peers[sender] = (acceptsDistantChat, Time.unscaledTime);
				if (requestReply && (Object)(object)Player.m_localPlayer != (Object)null)
				{
					router.InvokeRoutedRPC(sender, "BenjSammy.ClassicChatEverywhere.Presence.v1", new object[2] { receiveFar.Value, false });
				}
			}
		}

		private ConfigEntry<bool> BindToggle(string key, string label, string description, bool french)
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Expected O, but got Unknown
			return ((BaseUnityPlugin)this).Config.Bind<bool>("Chat", key, true, new ConfigDescription(description, (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					DispName = label,
					Category = (french ? "Discussion" : "Chat"),
					CustomDrawer = delegate(ConfigEntryBase entry)
					{
						ConfigEntry<bool> val = (ConfigEntry<bool>)(object)entry;
						val.Value = GUILayout.Toggle(val.Value, (!val.Value) ? (french ? "Non" : "No") : (french ? "Oui" : "Yes"), Array.Empty<GUILayoutOption>());
					}
				}
			}));
		}

		private static bool UsesFrench()
		{
			string text = PlayerPrefs.GetString("language", "English");
			Type type = AccessTools.TypeByName("Localization");
			if (type != null)
			{
				try
				{
					MethodInfo methodInfo = AccessTools.Method(type, "GetSelectedLanguage", Type.EmptyTypes, (Type[])null);
					object obj = (((object)methodInfo == null || methodInfo.IsStatic) ? null : AccessTools.PropertyGetter(type, "instance")?.Invoke(null, null));
					if (methodInfo != null && (methodInfo.IsStatic || obj != null))
					{
						text = (methodInfo.Invoke(obj, null) as string) ?? text;
					}
				}
				catch (Exception)
				{
				}
			}
			if (!string.Equals(text, "French", StringComparison.OrdinalIgnoreCase) && !string.Equals(text, "Français", StringComparison.OrdinalIgnoreCase) && !string.Equals(text, "fr", StringComparison.OrdinalIgnoreCase))
			{
				return text.StartsWith("fr-", StringComparison.OrdinalIgnoreCase);
			}
			return true;
		}

		private void ReceiveDistantChat(long sender, Vector3 position, Vector3 head, UserInfo user, string text)
		{
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			Chat instance = Chat.instance;
			if (!((Object)(object)plugin != (Object)(object)this) && receiveFar.Value && !((Object)(object)localPlayer == (Object)null) && !((Object)(object)instance == (Object)null) && sender != localUid() && peers.ContainsKey(sender) && !string.IsNullOrWhiteSpace(text))
			{
				Talker component = ((Component)localPlayer).GetComponent<Talker>();
				float num = (((Object)(object)component != (Object)null && normalRange != null) ? normalRange.Invoke(component) : 15f);
				Vector3 val = position - ((Component)localPlayer).transform.position;
				if (((Vector3)(ref val)).sqrMagnitude > num * num)
				{
					receiveChat(instance, sender, head, 1, user, text);
				}
			}
		}

		private bool AcceptsDistantChat(long recipient)
		{
			if (peers.TryGetValue(recipient, out (bool, float) value) && value.Item1)
			{
				return Time.unscaledTime - value.Item2 <= 30f;
			}
			return false;
		}

		private static bool SendDistantChat(Type __0, string __1)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Invalid comparison between Unknown and I4
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Expected O, but got Unknown
			GlobalChat mod = plugin;
			Player player = Player.m_localPlayer;
			ZRoutedRpc connection = mod?.router;
			if (!sendEverywhere.Value || (int)__0 != 1 || string.IsNullOrWhiteSpace(__1) || (Object)(object)player == (Object)null || connection == null || connection != ZRoutedRpc.instance || mod.peers.Count == 0)
			{
				return true;
			}
			Vector3 position = ((Component)player).transform.position;
			Vector3 head = ((Character)player).GetHeadPoint();
			sendToPermittedPlayers((SendChatMessageRPCHandler)delegate(long recipient, bool filter)
			{
				//IL_0064: 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)
				if (connection == ZRoutedRpc.instance && !((Object)(object)player != (Object)(object)Player.m_localPlayer) && sendEverywhere.Value && mod.AcceptsDistantChat(recipient))
				{
					prepareMessage(__1, filter, out var user, out var message);
					connection.InvokeRoutedRPC(recipient, "BenjSammy.ClassicChatEverywhere.Message.v1", new object[4] { position, head, user, message });
				}
			});
			return true;
		}
	}
}