Decompiled source of DeathBoard v1.0.0

BepInEx/plugins/DeathBoard/DeathBoard.dll

Decompiled 6 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Utils;
using TMPro;
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("DeathBoard")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+11fde89c7cc8ad9a9b4a9d9be327658002dfaae9")]
[assembly: AssemblyProduct("DeathBoard")]
[assembly: AssemblyTitle("DeathBoard")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace DeathBoard;

[BepInPlugin("local.valheim.deathboard", "Death Board", "1.0.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
public sealed class Plugin : BaseUnityPlugin
{
	[HarmonyPatch(typeof(Game), "Start")]
	private static class GameStartPatch
	{
		[HarmonyPostfix]
		private static void Postfix()
		{
			serverBoard = null;
			serverBoardPath = null;
			clientBoard = new Board();
			ZRoutedRpc.instance.Register<long, string, int>("DeathBoard_Report", (Action<long, long, string, int>)OnReport);
			ZRoutedRpc.instance.Register<string>("DeathBoard_Board", (Action<long, string>)OnBoard);
		}
	}

	[HarmonyPatch(typeof(Player), "OnSpawned")]
	private static class SpawnPatch
	{
		[HarmonyPostfix]
		private static void Postfix(Player __instance)
		{
			if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer)
			{
				Report();
			}
		}
	}

	[HarmonyPatch(typeof(Player), "OnDeath")]
	private static class DeathPatch
	{
		[HarmonyPostfix]
		private static void Postfix(Player __instance)
		{
			if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer)
			{
				Report();
			}
		}
	}

	[HarmonyPatch(typeof(Sign), "OnCheckPermissionCompleted")]
	private static class SignPatch
	{
		[HarmonyPostfix]
		private static void Postfix(Sign __instance, string ___m_currentText, bool ___m_isViewable)
		{
			if (___m_isViewable && !((Object)(object)__instance.m_textWidget == (Object)null) && Board.TryReadToken(___m_currentText, out var rows))
			{
				((TMP_Text)__instance.m_textWidget).text = clientBoard.Render(rows);
			}
		}
	}

	private const string ReportRpc = "DeathBoard_Report";

	private const string BoardRpc = "DeathBoard_Board";

	private static ManualLogSource log;

	private static Board serverBoard;

	private static string serverBoardPath;

	private static Board clientBoard = new Board();

	private void Awake()
	{
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		log = ((BaseUnityPlugin)this).Logger;
		new Harmony("local.valheim.deathboard").PatchAll(typeof(Plugin).Assembly);
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Signs with {{deaths}} show each player's deaths.");
	}

	private static void Report()
	{
		Game instance = Game.instance;
		PlayerProfile val = ((instance != null) ? instance.GetPlayerProfile() : null);
		Player localPlayer = Player.m_localPlayer;
		if (val != null && !((Object)(object)localPlayer == (Object)null) && ZRoutedRpc.instance != null)
		{
			int num = (int)val.GetStat((PlayerStatType)0, (DifficultyRequirement)0);
			ZRoutedRpc.instance.InvokeRoutedRPC("DeathBoard_Report", new object[3]
			{
				localPlayer.GetPlayerID(),
				val.GetName(),
				num
			});
		}
	}

	private static void OnReport(long sender, long id, string name, int lifetime)
	{
		if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
		{
			return;
		}
		Board board = ServerBoard();
		if (board.Report(id, name, lifetime))
		{
			try
			{
				Directory.CreateDirectory(Path.GetDirectoryName(serverBoardPath));
				File.WriteAllText(serverBoardPath, board.Serialize());
			}
			catch (Exception ex)
			{
				log.LogWarning((object)("Could not save the death board: " + ex.Message));
			}
		}
		ZRoutedRpc.instance.InvokeRoutedRPC(0L, "DeathBoard_Board", new object[1] { board.Serialize() });
	}

	private static void OnBoard(long sender, string text)
	{
		clientBoard = Board.Parse(text);
	}

	private static Board ServerBoard()
	{
		if (serverBoard != null)
		{
			return serverBoard;
		}
		serverBoardPath = Path.Combine(Paths.ConfigPath, "DeathBoard", SafeFileName(ZNet.instance.GetWorldName()) + ".tsv");
		try
		{
			serverBoard = (File.Exists(serverBoardPath) ? Board.Parse(File.ReadAllText(serverBoardPath)) : new Board());
		}
		catch (Exception ex)
		{
			log.LogWarning((object)("Could not read the death board, starting a new one: " + ex.Message));
			serverBoard = new Board();
		}
		return serverBoard;
	}

	private static string SafeFileName(string world)
	{
		if (string.IsNullOrEmpty(world))
		{
			return "world";
		}
		char[] invalidFileNameChars = Path.GetInvalidFileNameChars();
		foreach (char oldChar in invalidFileNameChars)
		{
			world = world.Replace(oldChar, '_');
		}
		return world;
	}
}
internal sealed class BoardEntry
{
	public long Id;

	public string Name = "";

	public int Lifetime;

	public int Baseline;

	public int Here => Math.Max(0, Lifetime - Baseline);
}
internal sealed class Board
{
	public const string Token = "{{deaths";

	public const int DefaultRows = 10;

	private const int MaxRows = 50;

	private readonly Dictionary<long, BoardEntry> entries = new Dictionary<long, BoardEntry>();

	public IEnumerable<BoardEntry> Entries => entries.Values;

	public bool Report(long id, string name, int lifetime)
	{
		name = CleanName(name);
		if (id == 0L || name.Length == 0 || lifetime < 0)
		{
			return false;
		}
		if (!entries.TryGetValue(id, out var value))
		{
			entries[id] = new BoardEntry
			{
				Id = id,
				Name = name,
				Lifetime = lifetime,
				Baseline = lifetime
			};
			return true;
		}
		if (value.Name == name && value.Lifetime == lifetime)
		{
			return false;
		}
		value.Name = name;
		value.Lifetime = lifetime;
		if (value.Baseline > lifetime)
		{
			value.Baseline = lifetime;
		}
		return true;
	}

	public string Serialize()
	{
		StringBuilder stringBuilder = new StringBuilder();
		foreach (BoardEntry item in entries.Values.OrderBy((BoardEntry e) => e.Id))
		{
			stringBuilder.Append(item.Id.ToString(CultureInfo.InvariantCulture)).Append('\t').Append(item.Lifetime.ToString(CultureInfo.InvariantCulture))
				.Append('\t')
				.Append(item.Baseline.ToString(CultureInfo.InvariantCulture))
				.Append('\t')
				.Append(item.Name)
				.Append('\n');
		}
		return stringBuilder.ToString();
	}

	public static Board Parse(string text)
	{
		Board board = new Board();
		if (string.IsNullOrEmpty(text))
		{
			return board;
		}
		string[] array = text.Replace("\r", "").Split('\n');
		for (int i = 0; i < array.Length; i++)
		{
			string[] array2 = array[i].Split(new char[1] { '\t' }, 4);
			if (array2.Length == 4 && long.TryParse(array2[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) && int.TryParse(array2[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var result2) && int.TryParse(array2[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out var result3))
			{
				string text2 = CleanName(array2[3]);
				if (result != 0L && text2.Length != 0 && result2 >= 0 && result3 >= 0)
				{
					board.entries[result] = new BoardEntry
					{
						Id = result,
						Name = text2,
						Lifetime = result2,
						Baseline = Math.Min(result3, result2)
					};
				}
			}
		}
		return board;
	}

	public string Render(int rows)
	{
		rows = ((rows <= 0) ? 10 : Math.Min(rows, 50));
		StringBuilder stringBuilder = new StringBuilder("Deaths: total (this server)");
		if (entries.Count == 0)
		{
			return stringBuilder.Append("\nNo deaths recorded yet").ToString();
		}
		int num = 0;
		foreach (BoardEntry item in (from e in entries.Values
			orderby e.Lifetime descending, e.Here descending
			select e).ThenBy<BoardEntry, string>((BoardEntry e) => e.Name, StringComparer.OrdinalIgnoreCase).Take(rows))
		{
			stringBuilder.Append('\n').Append(++num).Append(". ")
				.Append(item.Name)
				.Append(": ")
				.Append(item.Lifetime)
				.Append(" (")
				.Append(item.Here)
				.Append(')');
		}
		return stringBuilder.ToString();
	}

	public static bool TryReadToken(string signText, out int rows)
	{
		rows = 10;
		if (string.IsNullOrEmpty(signText))
		{
			return false;
		}
		int num = signText.IndexOf("{{deaths", StringComparison.OrdinalIgnoreCase);
		if (num < 0)
		{
			return false;
		}
		int num2 = signText.IndexOf("}}", num + "{{deaths".Length, StringComparison.Ordinal);
		if (num2 < 0)
		{
			return false;
		}
		string text = signText.Substring(num + "{{deaths".Length, num2 - num - "{{deaths".Length).Trim();
		if (text.Length == 0)
		{
			return true;
		}
		if (!char.IsWhiteSpace(signText[num + "{{deaths".Length]))
		{
			return false;
		}
		if (int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) && result > 0)
		{
			rows = Math.Min(result, 50);
		}
		return true;
	}

	internal static string CleanName(string name)
	{
		if (name == null)
		{
			return "";
		}
		StringBuilder stringBuilder = new StringBuilder(name.Length);
		foreach (char c in name)
		{
			if (c != '\t' && c != '\n' && c != '\r' && c != '<' && c != '>')
			{
				stringBuilder.Append(c);
			}
		}
		return stringBuilder.ToString().Trim();
	}
}