Decompiled source of BetterCustomServer v0.5.6

BepInEx/plugins/BetterCustomServer/BetterCustomServer.dll

Decompiled 31 minutes ago
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Photon.Pun;
using Photon.Realtime;
using Photon.Voice;
using Photon.Voice.PUN;
using Platforms;
using Steamworks;
using Steamworks.Data;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("BetterCustomServer")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.5.6.0")]
[assembly: AssemblyInformationalVersion("0.5.6+1b4a52627c1f1c817d4325e0325d28754f57b411")]
[assembly: AssemblyProduct("BetterCustomServer")]
[assembly: AssemblyTitle("BetterCustomServer")]
[assembly: AssemblyVersion("0.5.6.0")]
namespace BetterCustomServer;

[BepInPlugin("errorawa.repo.customserver", "BetterCustomServer", "0.5.6")]
public class BetterCustomServer : BaseUnityPlugin
{
	private sealed class ServerRegions : AcceptableValueList<string>
	{
		internal ServerRegions()
			: base(new string[18]
			{
				"asia", "au", "cae", "eu", "hk", "in", "jp", "ru", "rue", "za",
				"sa", "kr", "tr", "uae", "us", "usw", "ussc", "cn"
			})
		{
		}

		public override object Clamp(object value)
		{
			string text = (value as string)?.Replace(" ", "");
			if (!((AcceptableValueBase)this).IsValid((object)text))
			{
				return "hk";
			}
			return text;
		}
	}

	internal const string DefaultRegion = "hk";

	internal static ConfigEntry<string> Region;

	internal static ConfigEntry<string> GlobalId;

	internal static ConfigEntry<string> ChinaId;

	internal static ConfigEntry<string> VoiceId;

	internal static ConfigEntry<bool> UseVoice;

	internal static ManualLogSource Log;

	private void Awake()
	{
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Expected O, but got Unknown
		Log = ((BaseUnityPlugin)this).Logger;
		Bind(((BaseUnityPlugin)this).Config);
		Harmony val = new Harmony(((BaseUnityPlugin)this).Info.Metadata.GUID);
		try
		{
			val.PatchAll(typeof(BetterCustomServer).Assembly);
		}
		catch
		{
			val.UnpatchSelf();
			throw;
		}
		SteamMatchmaking.OnLobbyCreated += LobbyConfigSync.OnCreated;
	}

	private void OnDestroy()
	{
		SteamMatchmaking.OnLobbyCreated -= LobbyConfigSync.OnCreated;
	}

	private static void Bind(ConfigFile config)
	{
		//IL_0133: Unknown result type (might be due to invalid IL or missing references)
		//IL_013d: Expected O, but got Unknown
		bool saveOnConfigSet = config.SaveOnConfigSet;
		config.SaveOnConfigSet = false;
		try
		{
			ConfigEntry<bool> val = config.Bind<bool>("Server", "Use China Server", false, "");
			config.Remove(((ConfigEntryBase)val).Definition);
			config.Remove(((ConfigEntryBase)config.Bind<string>("Debug", "Language", "", "")).Definition);
			config.Remove(((ConfigEntryBase)config.Bind<int>("Server", "Max Player Count", 8, "")).Definition);
			config.Remove(((ConfigEntryBase)config.Bind<bool>("Debug", "Log Output", true, "")).Definition);
			GlobalId = config.Bind<string>("Server", "Photon Pun Global AppId", "", "Your global Photon PUN application ID.");
			ChinaId = config.Bind<string>("Server", "Photon Pun China AppId", "", "Your China PUN application ID for region cn. Falls back to Global in hk.");
			VoiceId = config.Bind<string>("Server", "Photon Voice AppId", "", "Optional global Photon Voice application ID.");
			UseVoice = config.Bind<bool>("Server", "Use Voice Server", true, "Allow Photon Voice connections.");
			Region = config.Bind<string>("Server", "Server Region", "hk", new ConfigDescription("Custom Photon region. cn uses China PUN and global Voice in hk.", (AcceptableValueBase)(object)new ServerRegions(), Array.Empty<object>()));
			if (val.Value)
			{
				Region.Value = "cn";
			}
			if (saveOnConfigSet)
			{
				config.Save();
			}
		}
		finally
		{
			config.SaveOnConfigSet = saveOnConfigSet;
		}
	}

	internal static string ReadId(ConfigEntry<string> entry, string directory, string filename)
	{
		string text = entry.Value?.Trim();
		if (string.IsNullOrEmpty(text))
		{
			string path = Path.Combine(directory, filename);
			if (File.Exists(path))
			{
				text = File.ReadAllText(path).Trim();
			}
		}
		if (string.IsNullOrEmpty(text))
		{
			return null;
		}
		if (Guid.TryParse(text, out var result) && result != Guid.Empty)
		{
			return result.ToString();
		}
		throw new FormatException(((ConfigEntryBase)entry).Definition.Key);
	}

	internal static string Text(string chinese, string english)
	{
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Invalid comparison between Unknown and I4
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Invalid comparison between Unknown and I4
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: Invalid comparison between Unknown and I4
		if (Object.op_Implicit((Object)(object)LocalizationManager.instance))
		{
			string text = SemiFunc.LocaleGetCode();
			if (!string.Equals(text, "zh", StringComparison.OrdinalIgnoreCase) && (text == null || (!text.StartsWith("zh-", StringComparison.OrdinalIgnoreCase) && !text.StartsWith("zh_", StringComparison.OrdinalIgnoreCase))))
			{
				return english;
			}
			return chinese;
		}
		SystemLanguage systemLanguage = Application.systemLanguage;
		if ((int)systemLanguage != 6 && (int)systemLanguage != 40 && (int)systemLanguage != 41)
		{
			return english;
		}
		return chinese;
	}
}
internal static class LobbyConfigSync
{
	internal enum Role
	{
		None,
		Owner,
		Member
	}

	internal const string Key = "BCS.Config";

	private static readonly FieldRef<SteamLobbyManager, Lobby> CurrentLobby = AccessTools.FieldRefAccess<SteamLobbyManager, Lobby>("currentLobby");

	internal static Role Classify(ulong lobby, ulong owner, ulong self)
	{
		if (lobby == 0L || owner == 0L || self == 0L)
		{
			return Role.None;
		}
		if (owner != self)
		{
			return Role.Member;
		}
		return Role.Owner;
	}

	private static Role GetRole(Lobby lobby)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: 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_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		if (SteamClient.IsValid)
		{
			SteamId id = ((Lobby)(ref lobby)).Id;
			if (((SteamId)(ref id)).IsValid)
			{
				return Classify(SteamId.op_Implicit(((Lobby)(ref lobby)).Id), SteamId.op_Implicit(((Lobby)(ref lobby)).Owner.Id), SteamId.op_Implicit(SteamClient.SteamId));
			}
		}
		return Role.None;
	}

	internal static void OnCreated(Result result, Lobby lobby)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0002: Invalid comparison between Unknown and I4
		//IL_0004: 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)
		if ((int)result != 1 || GetRole(lobby) != Role.Owner)
		{
			return;
		}
		try
		{
			Publish(lobby, ServerConfig.Local("C:\\"));
		}
		catch (Exception ex) when (ex is IOException || ex is FormatException || ex is UnauthorizedAccessException)
		{
			BetterCustomServer.Log.LogWarning((object)BetterCustomServer.Text("本地 Photon 配置无效,未同步至大厅。", "Invalid local Photon configuration. Lobby settings were not published."));
		}
	}

	private static void Publish(Lobby lobby, ServerConfig settings)
	{
		if (!((Lobby)(ref lobby)).SetData("BCS.Config", settings.Serialize()))
		{
			BetterCustomServer.Log.LogWarning((object)BetterCustomServer.Text("Steam 未接受大厅配置,房员可能会使用本地配置。", "Steam did not accept the lobby settings. Guests may use their local configuration."));
		}
	}

	internal static ServerConfig Resolve(bool gameConnect)
	{
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		Lobby lobby = (Lobby)((Object.op_Implicit((Object)(object)SteamLobbyManager.instance) && SteamClient.IsValid) ? CurrentLobby.Invoke(SteamLobbyManager.instance) : default(Lobby));
		return Select(GetRole(lobby), () => ((Lobby)(ref lobby)).GetData("BCS.Config"), () => ServerConfig.Local("C:\\"), gameConnect ? ((Action<ServerConfig>)delegate(ServerConfig settings)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			Publish(lobby, settings);
		}) : null);
	}

	internal static ServerConfig Select(Role role, Func<string> readMetadata, Func<ServerConfig> readLocal, Action<ServerConfig> publish)
	{
		if (role == Role.Member)
		{
			ServerConfig serverConfig = ServerConfig.Parse(readMetadata());
			if (serverConfig != null)
			{
				return serverConfig;
			}
		}
		ServerConfig serverConfig2 = readLocal();
		if (role == Role.Owner)
		{
			publish?.Invoke(serverConfig2);
		}
		return serverConfig2;
	}
}
internal sealed class ServerConfig
{
	internal string GlobalId;

	internal string ChinaId;

	internal string VoiceId;

	internal string Region;

	internal static ServerConfig Local(string directory)
	{
		string value = BetterCustomServer.Region.Value;
		string text = ReadLocalId(BetterCustomServer.ChinaId, directory, "PhotonPunChina.txt", value == "cn");
		return new ServerConfig
		{
			Region = value,
			ChinaId = text,
			GlobalId = ReadLocalId(BetterCustomServer.GlobalId, directory, "PhotonPunGlobal.txt", value != "cn" || text == null),
			VoiceId = (BetterCustomServer.UseVoice.Value ? ReadLocalId(BetterCustomServer.VoiceId, directory, "PhotonVoice.txt", needed: false) : null)
		};
	}

	private static string ReadLocalId(ConfigEntry<string> entry, string directory, string file, bool needed)
	{
		try
		{
			return BetterCustomServer.ReadId(entry, directory, file);
		}
		catch (Exception ex) when (!needed && (ex is IOException || ex is UnauthorizedAccessException || ex is FormatException))
		{
			return null;
		}
	}

	internal string Serialize()
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0005: 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_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0062: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: Unknown result type (might be due to invalid IL or missing references)
		return ((JToken)new JObject
		{
			["globalAppId"] = JToken.op_Implicit(GlobalId ?? ""),
			["chinaAppId"] = JToken.op_Implicit(ChinaId ?? ""),
			["voiceAppId"] = JToken.op_Implicit(VoiceId ?? ""),
			["region"] = JToken.op_Implicit(Region),
			["china"] = JToken.op_Implicit(Region == "cn")
		}).ToString((Formatting)0, Array.Empty<JsonConverter>());
	}

	internal static ServerConfig Parse(string json)
	{
		//IL_0019: 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_002a: Expected O, but got Unknown
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Invalid comparison between Unknown and I4
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: Invalid comparison between Unknown and I4
		if (string.IsNullOrWhiteSpace(json) || json.Length > 2048)
		{
			return null;
		}
		try
		{
			JObject val = JObject.Parse(json, new JsonLoadSettings
			{
				DuplicatePropertyNameHandling = (DuplicatePropertyNameHandling)2
			});
			JToken obj = val["region"];
			if (obj != null && (int)obj.Type == 8)
			{
				JToken obj2 = val["china"];
				if (obj2 != null && (int)obj2.Type == 9)
				{
					string text = (string)val["region"];
					if (!((ConfigEntryBase)BetterCustomServer.Region).Description.AcceptableValues.IsValid((object)text) || (bool)val["china"] != (text == "cn"))
					{
						return null;
					}
					if (!TryId(val["globalAppId"], out var value) || !TryId(val["chinaAppId"], out var value2) || !TryId(val["voiceAppId"], out var value3))
					{
						return null;
					}
					return new ServerConfig
					{
						Region = text,
						GlobalId = value,
						ChinaId = value2,
						VoiceId = value3
					};
				}
			}
			return null;
		}
		catch (JsonException)
		{
			return null;
		}
	}

	private static bool TryId(JToken token, out string value)
	{
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Invalid comparison between Unknown and I4
		value = null;
		if (token == null || (int)token.Type != 8)
		{
			return false;
		}
		string text = ((string)token).Trim();
		if (text.Length == 0)
		{
			return true;
		}
		if (!Guid.TryParseExact(text, "D", out var result) || result == Guid.Empty)
		{
			return false;
		}
		value = result.ToString();
		return true;
	}
}
internal sealed class PhotonRoute
{
	internal string AppId;

	internal string Region;

	internal bool China;

	internal bool Disabled;

	internal bool ChinaIdMissing;

	internal static PhotonRoute FromConfig(bool voice, ServerConfig config)
	{
		string region = config.Region;
		bool flag = region == "cn";
		if (voice)
		{
			return new PhotonRoute
			{
				AppId = config.VoiceId,
				Region = (flag ? "hk" : region),
				Disabled = (config.VoiceId == null || !BetterCustomServer.UseVoice.Value)
			};
		}
		string text = (flag ? config.ChinaId : null);
		bool flag2 = flag && text == null;
		return new PhotonRoute
		{
			AppId = (text ?? config.GlobalId),
			Region = (flag2 ? "hk" : region),
			China = (flag && !flag2),
			ChinaIdMissing = flag2
		};
	}

	internal AppSettings Apply(AppSettings original, bool voice, bool discoverRegions)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Expected O, but got Unknown
		//IL_0069: Unknown result type (might be due to invalid IL or missing references)
		AppSettings val = original.CopyTo(new AppSettings());
		if (voice)
		{
			val.AppIdVoice = AppId;
		}
		else
		{
			val.AppIdRealtime = AppId;
		}
		val.FixedRegion = (discoverRegions ? "" : Region);
		val.Server = (China ? "ns.photonengine.cn" : "ns.photonengine.io");
		val.Port = 0;
		val.UseNameServer = true;
		val.AuthMode = (AuthModeOption)1;
		return val;
	}
}
[HarmonyPatch]
internal static class PhotonPatches
{
	private static PhotonRoute Read(bool voice)
	{
		try
		{
			return PhotonRoute.FromConfig(voice, LobbyConfigSync.Resolve(!voice));
		}
		catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException || ex is FormatException)
		{
			BetterCustomServer.Log.LogWarning((object)BetterCustomServer.Text("Photon AppId 无效或无法读取。", "Invalid or unreadable Photon AppId."));
			return new PhotonRoute
			{
				Disabled = true
			};
		}
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(LoadBalancingClient), "ConnectUsingSettings")]
	private static bool Connect(LoadBalancingClient __instance, ref AppSettings appSettings)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Invalid comparison between Unknown and I4
		//IL_0126: Unknown result type (might be due to invalid IL or missing references)
		//IL_0130: Expected O, but got Unknown
		bool flag = __instance is LoadBalancingTransport && (int)__instance.ClientType == 1;
		if ((!flag && __instance != PhotonNetwork.NetworkingClient) || appSettings == null)
		{
			return true;
		}
		PhotonRoute photonRoute = Read(flag);
		if (photonRoute.Disabled)
		{
			return false;
		}
		if (photonRoute.ChinaIdMissing)
		{
			BetterCustomServer.Log.LogWarning((object)BetterCustomServer.Text("缺少国区 PUN AppId,尝试使用国际区配置。", "China PUN AppId missing. Falling back to global settings."));
		}
		if (photonRoute.AppId == null)
		{
			if (appSettings.IsDefaultNameServer && __instance.NameServerHost == "ns.photonengine.cn")
			{
				__instance.NameServerHost = "ns.photonengine.io";
			}
			return true;
		}
		AppSettings appSettings2 = PhotonNetwork.PhotonServerSettings.AppSettings;
		if (string.Equals(photonRoute.AppId, appSettings2.AppIdRealtime, StringComparison.OrdinalIgnoreCase) || string.Equals(photonRoute.AppId, appSettings2.AppIdVoice, StringComparison.OrdinalIgnoreCase))
		{
			BetterCustomServer.Log.LogError((object)BetterCustomServer.Text("请使用自己的 Photon AppId。", "Use your own Photon AppId."));
			return false;
		}
		if (!Object.op_Implicit((Object)(object)PlatformManager.instance) || !PlatformManager.instance.IsInitialised())
		{
			return false;
		}
		bool discoverRegions = !flag && string.IsNullOrEmpty(appSettings.FixedRegion) && Object.op_Implicit((Object)(object)Object.FindFirstObjectByType<MenuPageRegions>());
		appSettings = photonRoute.Apply(appSettings, flag, discoverRegions);
		__instance.AuthValues = new AuthenticationValues(PlatformManager.instance.GetPlatformUserId());
		return true;
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(VoiceFollowClient), "ConnectOrJoinVoice")]
	private static bool AllowVoice(VoiceFollowClient __instance)
	{
		if (__instance is PunVoiceClient)
		{
			return !Read(voice: true).Disabled;
		}
		return true;
	}
}