Decompiled source of SansaraPersonalProgression v0.1.0

plugins/PersonalProgression.dll

Decompiled 4 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Sansara.Chronicle;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: AssemblyCompany("PersonalProgression")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+b497f2598de479c169daea3e792bd8aa9ba5955e")]
[assembly: AssemblyProduct("PersonalProgression")]
[assembly: AssemblyTitle("PersonalProgression")]
[assembly: AssemblyVersion("0.1.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 Sansara.Chronicle
{
	public sealed class ChroniclePlayer
	{
		public long Id { get; }

		public string Name { get; }

		public ChroniclePlayer(long id, string name)
		{
			Id = id;
			Name = name ?? "";
		}
	}
	public sealed class ChronicleEntry
	{
		public double Time;

		public string Date = "";

		public string Kind = "";

		public string Id = "";

		public string Result = "";

		public List<ChroniclePlayer> Players = new List<ChroniclePlayer>();

		public const string Victory = "victory";

		public bool IsVictory
		{
			get
			{
				if (!(Result == "victory"))
				{
					return Result == "found";
				}
				return true;
			}
		}

		public static string Clean(string s)
		{
			return new string((s ?? "").Where((char c) => c != '\t' && c != '\n' && c != '\r' && c != '|' && c != '=').ToArray()).Trim();
		}

		public string ToLine()
		{
			string text = string.Join("|", Players.Select((ChroniclePlayer p) => p.Id.ToString(CultureInfo.InvariantCulture) + "=" + Clean(p.Name)));
			return string.Join("\t", Time.ToString("R", CultureInfo.InvariantCulture), Clean(Date), Clean(Kind), Clean(Id), Clean(Result), text);
		}

		public static ChronicleEntry Parse(string line)
		{
			if (string.IsNullOrWhiteSpace(line) || line.TrimStart(Array.Empty<char>()).StartsWith("#", StringComparison.Ordinal))
			{
				return null;
			}
			string[] array = line.TrimEnd(new char[1] { '\r' }).Split(new char[1] { '\t' });
			if (array.Length < 5 || !double.TryParse(array[0], NumberStyles.Float, CultureInfo.InvariantCulture, out var result) || array[2].Trim() == "" || array[3].Trim() == "")
			{
				return null;
			}
			ChronicleEntry chronicleEntry = new ChronicleEntry
			{
				Time = result,
				Date = array[1].Trim(),
				Kind = array[2].Trim(),
				Id = array[3].Trim(),
				Result = array[4].Trim()
			};
			if (array.Length > 5)
			{
				string[] array2 = array[5].Split(new char[1] { '|' }, StringSplitOptions.RemoveEmptyEntries);
				foreach (string text in array2)
				{
					int num = text.IndexOf('=');
					long.TryParse((num > 0) ? text.Substring(0, num) : "0", NumberStyles.Integer, CultureInfo.InvariantCulture, out var result2);
					chronicleEntry.Players.Add(new ChroniclePlayer(result2, (num >= 0) ? text.Substring(num + 1) : text));
				}
			}
			return chronicleEntry;
		}

		public static List<ChronicleEntry> ParseAll(string text, out int bad)
		{
			List<ChronicleEntry> list = new List<ChronicleEntry>();
			bad = 0;
			string[] array = (text ?? "").Split(new char[1] { '\n' });
			foreach (string text2 in array)
			{
				ChronicleEntry chronicleEntry = Parse(text2);
				if (chronicleEntry != null)
				{
					list.Add(chronicleEntry);
				}
				else if (!string.IsNullOrWhiteSpace(text2) && !text2.TrimStart(Array.Empty<char>()).StartsWith("#", StringComparison.Ordinal))
				{
					bad++;
				}
			}
			return list;
		}
	}
	public static class ChronicleFile
	{
		public static string PathFor(string configDir, string world)
		{
			string text = string.Concat((world ?? "world").Split(Path.GetInvalidFileNameChars()));
			return Path.Combine(configDir, "sansara.Chronicle", text + ".tsv");
		}

		public static void Append(string path, ChronicleEntry entry)
		{
			Directory.CreateDirectory(Path.GetDirectoryName(path));
			File.AppendAllText(path, entry.ToLine() + "\n", new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
		}

		public static List<ChronicleEntry> Read(string path, out int bad)
		{
			bad = 0;
			if (!File.Exists(path))
			{
				return new List<ChronicleEntry>();
			}
			return ChronicleEntry.ParseAll(File.ReadAllText(path), out bad);
		}
	}
	public sealed class FirstVictory
	{
		public string Id;

		public string Date;

		public List<string> Names = new List<string>();

		public int Count;
	}
	public sealed class Leader
	{
		public string Name;

		public int Count;
	}
	public static class ChronicleStats
	{
		public static Dictionary<string, FirstVictory> Firsts(IEnumerable<ChronicleEntry> all, string kind)
		{
			Dictionary<string, FirstVictory> dictionary = new Dictionary<string, FirstVictory>();
			foreach (ChronicleEntry item in from e in all
				where e.Kind == kind && e.IsVictory
				orderby e.Time
				select e)
			{
				if (!dictionary.TryGetValue(item.Id, out var value))
				{
					value = new FirstVictory
					{
						Id = item.Id,
						Date = item.Date,
						Names = (from p in item.Players
							select p.Name into n
							where n != ""
							select n).Distinct().ToList()
					};
					dictionary[item.Id] = value;
				}
				value.Count++;
			}
			return dictionary;
		}

		public static List<Leader> Leaders(IEnumerable<ChronicleEntry> all, string kind)
		{
			Dictionary<long, int> dictionary = new Dictionary<long, int>();
			Dictionary<long, string> names = new Dictionary<long, string>();
			foreach (ChronicleEntry item in from e in all
				where e.Kind == kind && e.IsVictory
				orderby e.Time
				select e)
			{
				foreach (ChroniclePlayer item2 in from p in item.Players
					group p by (p.Id == 0L) ? p.Name : p.Id.ToString() into g
					select g.First())
				{
					long key = ((item2.Id != 0L) ? item2.Id : item2.Name.GetHashCode());
					dictionary[key] = ((!dictionary.TryGetValue(key, out var value)) ? 1 : (value + 1));
					if (item2.Name != "")
					{
						names[key] = item2.Name;
					}
				}
			}
			string value2;
			return (from kv in dictionary
				select new Leader
				{
					Name = (names.TryGetValue(kv.Key, out value2) ? value2 : "?"),
					Count = kv.Value
				} into l
				orderby l.Count descending
				select l).ThenBy<Leader, string>((Leader l) => l.Name, StringComparer.Ordinal).ToList();
		}

		public static string Names(IList<string> names, int max)
		{
			if (names.Count == 0)
			{
				return "";
			}
			for (int num = names.Count; num >= 1; num--)
			{
				string text = string.Join(", ", names.Take(num)) + ((num < names.Count) ? $" +{names.Count - num}" : "");
				if (text.Length <= max)
				{
					return text;
				}
			}
			string text2 = names[0];
			if (text2.Length <= max)
			{
				return text2;
			}
			return text2.Substring(0, Math.Max(1, max - 1)) + "…";
		}
	}
}
namespace PersonalProgression
{
	[HarmonyPatch(typeof(Trader), "GetAvailableItems")]
	internal static class TraderPatch
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = instructions.ToList();
			CodeInstruction obj = list.Single((CodeInstruction instruction) => CodeInstructionExtensions.Calls(instruction, SpawnPatch.GlobalKey));
			obj.opcode = OpCodes.Call;
			obj.operand = AccessTools.Method(typeof(TraderPatch), "HasKey", (Type[])null, (Type[])null);
			return list;
		}

		private static bool HasKey(ZoneSystem zone, string key)
		{
			if (!Plugin.ClientActive || !Plugin.IsBossKey(key))
			{
				return zone.GetGlobalKey(key);
			}
			return Plugin.HasVictory(Player.m_localPlayer, key);
		}
	}
	[HarmonyPatch(typeof(SpawnSystem), "UpdateSpawnList")]
	internal static class SpawnPatch
	{
		private delegate bool CheckPoint(SpawnSystem system, SpawnData spawn, ref Vector3 point);

		internal static readonly MethodInfo GlobalKey = AccessTools.Method(typeof(ZoneSystem), "GetGlobalKey", new Type[1] { typeof(string) }, (Type[])null);

		private static readonly MethodInfo SpawnPoint = AccessTools.Method(typeof(SpawnSystem), "IsSpawnPointGood", (Type[])null, (Type[])null);

		private static readonly CheckPoint OriginalCheck = AccessTools.MethodDelegate<CheckPoint>(SpawnPoint, (object)null, true);

		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = instructions.ToList();
			ReplaceCall(list, GlobalKey, "HasKey");
			ReplaceCall(list, SpawnPoint, "IsPointAllowed");
			return list;
		}

		private static void ReplaceCall(List<CodeInstruction> code, MethodInfo original, string replacement)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			CodeInstruction val = code.Single((CodeInstruction instruction) => CodeInstructionExtensions.Calls(instruction, original));
			CodeInstruction val2 = new CodeInstruction(OpCodes.Ldarg_3, (object)null);
			val2.labels.AddRange(val.labels);
			val2.blocks.AddRange(val.blocks);
			val.labels.Clear();
			val.blocks.Clear();
			code.Insert(code.IndexOf(val), val2);
			val.opcode = OpCodes.Call;
			val.operand = AccessTools.Method(typeof(SpawnPatch), replacement, (Type[])null, (Type[])null);
		}

		private static bool HasKey(ZoneSystem zone, string key, bool raid)
		{
			if (raid || !Plugin.ClientActive || !Plugin.IsBossKey(key))
			{
				return zone.GetGlobalKey(key);
			}
			return true;
		}

		private static bool IsPointAllowed(SpawnSystem system, SpawnData spawn, ref Vector3 point, bool raid)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			if (!OriginalCheck(system, spawn, ref point))
			{
				return false;
			}
			string requiredGlobalKey = spawn.m_requiredGlobalKey;
			if (!raid && Plugin.ClientActive && Plugin.IsBossKey(requiredGlobalKey))
			{
				return Plugin.AllowsSpawn(point, requiredGlobalKey);
			}
			return true;
		}
	}
	[BepInPlugin("sansara.PersonalProgression", "Sansara Personal Progression", "0.1.0")]
	public sealed class Plugin : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static class ConnectionPatch
		{
			private static void Postfix(ZNet __instance, ZNetPeer peer)
			{
				//IL_0045: Unknown result type (might be due to invalid IL or missing references)
				//IL_004f: Expected O, but got Unknown
				ZRpc rpc = peer.m_rpc;
				if (__instance.IsServer())
				{
					float nextReply = 0f;
					rpc.Register("SansaraPersonalProgression_Request", (Method)delegate(ZRpc connection)
					{
						if (!(Time.realtimeSinceStartup < nextReply) && peer.IsReady())
						{
							nextReply = Time.realtimeSinceStartup + 3f - 0.5f;
							_instance.SendSnapshot(__instance, connection);
						}
					});
				}
				else
				{
					_server = rpc;
					_snapshot = null;
					_instance._nextRequest = 0f;
					rpc.Register<ZPackage>("SansaraPersonalProgression_Snapshot", (Action<ZRpc, ZPackage>)ReceiveSnapshot);
				}
			}
		}

		public const string Version = "0.1.0";

		private const string Request = "SansaraPersonalProgression_Request";

		private const string Snapshot = "SansaraPersonalProgression_Snapshot";

		private const float PollSeconds = 3f;

		private const float SnapshotLifetime = 12f;

		private static Plugin _instance;

		private static ZRpc _server;

		private static Dictionary<long, HashSet<string>> _snapshot;

		private static float _receivedAt;

		private static float _protectionRadius;

		private static readonly Action<StoreGui> RefreshStore = AccessTools.MethodDelegate<Action<StoreGui>>(AccessTools.Method(typeof(StoreGui), "FillList", (Type[])null, (Type[])null), (object)null, true);

		private float _nextRequest;

		private ConfigEntry<float> _radius;

		private string _chroniclePath;

		private DateTime _chronicleWriteTime;

		private long _chronicleLength = -1L;

		private Dictionary<long, HashSet<string>> _wins = new Dictionary<long, HashSet<string>>();

		internal static bool ClientActive
		{
			get
			{
				if (_server != null)
				{
					ZNet instance = ZNet.instance;
					return ((instance == null) ? null : instance.GetServerPeer()?.m_rpc) == _server;
				}
				return false;
			}
		}

		private void Awake()
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Expected O, but got Unknown
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			if (((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", false, "Enable on the server and in its client profile. Restart after changing.").Value)
			{
				_radius = ((BaseUnityPlugin)this).Config.Bind<float>("Spawns", "ProtectionRadius", 100f, new ConfigDescription("Horizontal radius around a spawn point, in meters.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(40f, 150f), Array.Empty<object>()));
				_instance = this;
				new Harmony("sansara.PersonalProgression").PatchAll();
			}
		}

		private void Update()
		{
			if (_snapshot != null && (!ClientActive || Time.realtimeSinceStartup - _receivedAt > 12f))
			{
				_snapshot = null;
				RefreshOpenStore();
			}
			if (_server != null)
			{
				ZNet instance = ZNet.instance;
				if (((instance == null) ? null : instance.GetServerPeer()?.m_rpc) == _server && !(Time.realtimeSinceStartup < _nextRequest))
				{
					_nextRequest = Time.realtimeSinceStartup + 3f;
					_server.Invoke("SansaraPersonalProgression_Request", Array.Empty<object>());
				}
			}
		}

		internal static bool IsBossKey(string key)
		{
			return key?.StartsWith("defeated_", StringComparison.OrdinalIgnoreCase) ?? false;
		}

		internal static bool HasVictory(Player player, string key)
		{
			if ((Object)(object)player != (Object)null && _snapshot != null && Time.realtimeSinceStartup - _receivedAt <= 12f && _snapshot.TryGetValue(player.GetPlayerID(), out var value))
			{
				return value.Contains(key);
			}
			return false;
		}

		internal static bool AllowsSpawn(Vector3 point, string key)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: 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_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			bool result = false;
			float num = _protectionRadius * _protectionRadius;
			foreach (Player allPlayer in Player.GetAllPlayers())
			{
				if ((Object)(object)allPlayer == (Object)null)
				{
					continue;
				}
				Vector3 val = ((Component)allPlayer).transform.position - point;
				if (val.x * val.x + val.z * val.z <= num)
				{
					result = true;
					if (!HasVictory(allPlayer, key))
					{
						return false;
					}
				}
			}
			return result;
		}

		private void SendSnapshot(ZNet net, ZRpc rpc)
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Expected O, but got Unknown
			try
			{
				RefreshWins(net.GetWorldName());
				Dictionary<long, HashSet<string>> dictionary = new Dictionary<long, HashSet<string>>();
				foreach (ZNetPeer peer in net.GetPeers())
				{
					ZDO obj = (((ZDOID)(ref peer.m_characterID)).IsNone() ? null : ZDOMan.instance.GetZDO(peer.m_characterID));
					long num = ((obj != null) ? obj.GetLong(ZDOVars.s_playerID, 0L) : 0);
					if (num != 0L && _wins.TryGetValue(num, out var value))
					{
						dictionary[num] = value;
					}
				}
				ZPackage val = new ZPackage();
				val.Write(_radius.Value);
				val.Write(dictionary.Count);
				foreach (KeyValuePair<long, HashSet<string>> item in dictionary)
				{
					val.Write(item.Key);
					val.Write(item.Value.Count);
					foreach (string item2 in item.Value)
					{
						val.Write(item2);
					}
				}
				rpc.Invoke("SansaraPersonalProgression_Snapshot", new object[1] { val });
			}
			catch (IOException ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Не удалось прочитать летопись побед: " + ex.Message));
			}
			catch (UnauthorizedAccessException ex2)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Нет доступа к летописи побед: " + ex2.Message));
			}
		}

		private void RefreshWins(string world)
		{
			string text = ChronicleFile.PathFor(Paths.ConfigPath, world);
			FileInfo fileInfo = new FileInfo(text);
			long num = (fileInfo.Exists ? fileInfo.Length : (-1));
			if (text == _chroniclePath && num == _chronicleLength && fileInfo.LastWriteTimeUtc == _chronicleWriteTime)
			{
				return;
			}
			Dictionary<long, HashSet<string>> dictionary = new Dictionary<long, HashSet<string>>();
			int bad;
			foreach (ChronicleEntry item in ChronicleFile.Read(text, out bad))
			{
				if (item.Kind != "boss" || item.Result != "victory" || !IsBossKey(item.Id))
				{
					continue;
				}
				foreach (ChroniclePlayer player in item.Players)
				{
					if (player.Id != 0L)
					{
						if (!dictionary.TryGetValue(player.Id, out var value))
						{
							value = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
							dictionary.Add(player.Id, value);
						}
						value.Add(item.Id);
					}
				}
			}
			_wins = dictionary;
			_chroniclePath = text;
			_chronicleLength = num;
			_chronicleWriteTime = fileInfo.LastWriteTimeUtc;
		}

		private static void ReceiveSnapshot(ZRpc rpc, ZPackage package)
		{
			if (rpc != _server)
			{
				return;
			}
			float protectionRadius = package.ReadSingle();
			Dictionary<long, HashSet<string>> dictionary = new Dictionary<long, HashSet<string>>();
			int num = package.ReadInt();
			for (int i = 0; i < num; i++)
			{
				long key = package.ReadLong();
				int num2 = package.ReadInt();
				HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
				for (int j = 0; j < num2; j++)
				{
					hashSet.Add(package.ReadString());
				}
				dictionary.Add(key, hashSet);
			}
			long key2 = (((Object)(object)Player.m_localPlayer == (Object)null) ? 0 : Player.m_localPlayer.GetPlayerID());
			HashSet<string> value = null;
			_snapshot?.TryGetValue(key2, out value);
			dictionary.TryGetValue(key2, out var value2);
			_protectionRadius = protectionRadius;
			_snapshot = dictionary;
			_receivedAt = Time.realtimeSinceStartup;
			bool num3;
			if (value != null)
			{
				if (value2 == null)
				{
					goto IL_00e5;
				}
				num3 = !value.SetEquals(value2);
			}
			else
			{
				num3 = value2 != null;
			}
			if (!num3)
			{
				return;
			}
			goto IL_00e5;
			IL_00e5:
			RefreshOpenStore();
		}

		private static void RefreshOpenStore()
		{
			if ((Object)(object)Player.m_localPlayer != (Object)null && StoreGui.IsVisible())
			{
				RefreshStore(StoreGui.instance);
			}
		}
	}
}