Decompiled source of Arauto v1.0.0

plugins/Arauto.dll

Decompiled 4 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
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("Arauto")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("Arauto")]
[assembly: AssemblyTitle("Arauto")]
[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 Arauto
{
	internal static class Deaths
	{
		[HarmonyPatch(typeof(Character), "ApplyDamage")]
		private static class ApplyDamagePatch
		{
			private static void Prefix(Character __instance, HitData hit)
			{
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				//IL_0025: Unknown result type (might be due to invalid IL or missing references)
				try
				{
					if (hit != null && !((Object)(object)Player.m_localPlayer == (Object)null) && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer))
					{
						_lastType = hit.m_hitType;
						_lastTime = Time.time;
						Character attacker = hit.GetAttacker();
						if ((Object)(object)attacker == (Object)null || (Object)(object)attacker == (Object)(object)__instance)
						{
							_lastEnemy = null;
							return;
						}
						Player val = (Player)(object)((attacker is Player) ? attacker : null);
						_lastEnemy = ((val != null) ? val.GetPlayerName() : Localization.instance.Localize(attacker.m_name));
					}
				}
				catch
				{
				}
			}
		}

		[HarmonyPatch(typeof(Player), "OnDeath")]
		private static class OnDeathPatch
		{
			private static void Prefix(Player __instance)
			{
				try
				{
					if (!((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && ZRoutedRpc.instance != null)
					{
						bool num = Time.time - _lastTime < 30f;
						string text = (num ? ((object)Unsafe.As<HitType, HitType>(ref _lastType)/*cast due to .constrained prefix*/).ToString() : "");
						string text2 = (num ? (_lastEnemy ?? "") : "");
						ZRoutedRpc.instance.InvokeRoutedRPC("SAFADOS_Arauto_Morte", new object[3]
						{
							text,
							text2,
							__instance.GetPlayerName()
						});
						_lastTime = -1000f;
					}
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("aviso de morte: " + ex.Message));
				}
			}
		}

		internal const string Rpc = "SAFADOS_Arauto_Morte";

		private static readonly (string Key, string Title, string Lines)[] Defaults = new(string, string, string)[25]
		{
			("EnemyHit", "Morto por criatura", "%PLAYER_NAME% foi morto por %ENEMY%.|%PLAYER_NAME% foi despedaçado por %ENEMY%.|%PLAYER_NAME% virou o jantar de %ENEMY%.|%PLAYER_NAME% perdeu a briga com %ENEMY%.|%PLAYER_NAME% foi abatido por %ENEMY%.|%PLAYER_NAME% subestimou %ENEMY%."),
			("PlayerHit", "Morto por outro jogador", "%PLAYER_NAME% foi assassinado por %ENEMY%.|%PLAYER_NAME% não sobreviveu ao duelo com %ENEMY%.|%PLAYER_NAME% foi traído por %ENEMY%."),
			("Fall", "Queda", "%PLAYER_NAME% caiu para a morte.|%PLAYER_NAME% esqueceu que não sabe voar.|%PLAYER_NAME% achou que o chão estava mais perto.|%PLAYER_NAME% testou a gravidade. A gravidade venceu."),
			("Drowning", "Afogamento", "%PLAYER_NAME% se afogou.|%PLAYER_NAME% tentou respirar debaixo d'água.|%PLAYER_NAME% foi dormir com os peixes.|%PLAYER_NAME% esqueceu de voltar à superfície."),
			("Smoke", "Fumaça", "%PLAYER_NAME% sufocou na fumaça.|%PLAYER_NAME% esqueceu de abrir a chaminé.|%PLAYER_NAME% respirou fumaça demais.|%PLAYER_NAME% defumou a si mesmo."),
			("Burning", "Fogo", "%PLAYER_NAME% morreu queimado.|%PLAYER_NAME% virou churrasco.|%PLAYER_NAME% chegou perto demais do fogo.|%PLAYER_NAME% ardeu até virar cinzas."),
			("CinderFire", "Fogo de cinzas", "%PLAYER_NAME% morreu queimado nas brasas.|%PLAYER_NAME% foi consumido pelo fogo de Ashlands."),
			("AshlandsLava", "Lava", "%PLAYER_NAME% tentou nadar na lava.|%PLAYER_NAME% descobriu que lava é quente.|%PLAYER_NAME% derreteu.|%PLAYER_NAME% achou que a lava era só um chão alaranjado."),
			("AshlandsOcean", "Mar fervente", "%PLAYER_NAME% foi cozido no mar fervente.|%PLAYER_NAME% tomou um banho quente demais."),
			("Freezing", "Frio", "%PLAYER_NAME% congelou até a morte.|%PLAYER_NAME% virou picolé.|%PLAYER_NAME% esqueceu o casaco."),
			("Poisoned", "Veneno", "%PLAYER_NAME% sucumbiu ao veneno.|%PLAYER_NAME% provou algo que não devia."),
			("Water", "Água", "%PLAYER_NAME% foi levado pelas águas."),
			("EdgeOfWorld", "Borda do mundo", "%PLAYER_NAME% caiu da borda do mundo.|%PLAYER_NAME% foi longe demais."),
			("Tree", "Árvore", "%PLAYER_NAME% foi esmagado por uma árvore.|%PLAYER_NAME% esqueceu de gritar \"madeira!\"."),
			("Structural", "Estrutura", "%PLAYER_NAME% foi soterrado pela própria construção.|%PLAYER_NAME% confiou demais na engenharia."),
			("Stalagtite", "Estalactite", "%PLAYER_NAME% foi empalado por uma estalactite."),
			("Impact", "Impacto", "%PLAYER_NAME% foi esmagado.|%PLAYER_NAME% levou uma pancada fatal."),
			("Cart", "Carroça", "%PLAYER_NAME% foi atropelado por uma carroça."),
			("Boat", "Barco", "%PLAYER_NAME% foi atropelado por um barco."),
			("Turret", "Balista", "%PLAYER_NAME% foi alvejado por uma balista."),
			("Catapult", "Catapulta", "%PLAYER_NAME% foi atingido por uma catapulta."),
			("Incinerator", "Incinerador", "%PLAYER_NAME% foi incinerado."),
			("DrawBridge", "Ponte levadiça", "%PLAYER_NAME% foi esmagado por uma ponte levadiça."),
			("Self", "Por conta própria", "%PLAYER_NAME% morreu pelas próprias mãos.|%PLAYER_NAME% se derrotou sozinho."),
			("Generico", "Causa desconhecida", "%PLAYER_NAME% morreu.|%PLAYER_NAME% encontrou seu fim.|%PLAYER_NAME% partiu para Valhalla.")
		};

		private static readonly Dictionary<string, ConfigEntry<string>> Lines = new Dictionary<string, ConfigEntry<string>>();

		private static readonly Random Rng = new Random();

		private static HitType _lastType;

		private static string _lastEnemy;

		private static float _lastTime = -1000f;

		internal static void Bind(ConfigFile cfg)
		{
			(string, string, string)[] defaults = Defaults;
			for (int i = 0; i < defaults.Length; i++)
			{
				(string, string, string) tuple = defaults[i];
				Lines[tuple.Item1] = cfg.Bind<string>("Mortes", tuple.Item1, tuple.Item3, tuple.Item2 + ". Frases separadas por '|', uma é sorteada a cada morte. %PLAYER_NAME% = jogador, %ENEMY% = quem matou.");
			}
		}

		internal static string Text(string cause, string player, string enemy)
		{
			bool flag = !string.IsNullOrWhiteSpace(enemy);
			if ((cause == "EnemyHit" || cause == "PlayerHit") && !flag)
			{
				cause = "Generico";
			}
			if (string.IsNullOrEmpty(cause) || cause == "Undefined" || !Lines.ContainsKey(cause))
			{
				cause = "Generico";
			}
			string[] array = (from s in Lines[cause].Value.Split(new char[1] { '|' })
				select s.Trim() into s
				where s.Length > 0
				select s).ToArray();
			if (array.Length == 0)
			{
				array = new string[1] { "%PLAYER_NAME% morreu." };
			}
			string text;
			lock (Rng)
			{
				text = array[Rng.Next(array.Length)];
			}
			return text.Replace("%PLAYER_NAME%", player).Replace("%ENEMY%", flag ? enemy : "algo");
		}
	}
	[BepInPlugin("SAFADOS.Arauto", "Arauto", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		private sealed class ReadyListener : ILogListener, IDisposable
		{
			private readonly Plugin _p;

			public ReadyListener(Plugin p)
			{
				_p = p;
			}

			public void LogEvent(object sender, LogEventArgs e)
			{
				try
				{
					if (_p._ready || !_p._isDedicated)
					{
						return;
					}
					string text = e.Data?.ToString();
					if (text == null)
					{
						return;
					}
					if (text.Contains("Opened Steam server"))
					{
						_p._openedSteam = true;
						_p._openedAt = Time.realtimeSinceStartup;
						if (!Chainloader.PluginInfos.ContainsKey("com.bogey.voxheim"))
						{
							_p.MarkReady("Opened Steam server");
						}
					}
					else if (text.Contains("terrain authority") && (text.Contains("is ready") || text.Contains("remains blocked")))
					{
						_p.MarkReady("Voxheim: " + (text.Contains("is ready") ? "terrain authority is ready" : "terrain authority blocked"));
					}
				}
				catch
				{
				}
			}

			public void Dispose()
			{
			}
		}

		public const string Guid = "SAFADOS.Arauto";

		public const string Name = "Arauto";

		public const string Version = "1.0.0";

		internal static ManualLogSource Log;

		internal static Plugin Instance;

		private Webhook _webhook;

		private ConfigEntry<string> _url;

		private ConfigEntry<string> _username;

		private readonly Dictionary<string, ConfigEntry<bool>> _on = new Dictionary<string, ConfigEntry<bool>>();

		private readonly Dictionary<string, ConfigEntry<string>> _msg = new Dictionary<string, ConfigEntry<string>>();

		private ConfigEntry<bool> _pingPos;

		private ConfigEntry<bool> _eventPos;

		private ConfigEntry<int> _readyTimeout;

		private bool _isDedicated;

		private bool _ready;

		private bool _openedSteam;

		private float _openedAt;

		private float _nextPoll;

		private ZRoutedRpc _rpcRegistered;

		private readonly HashSet<string> _joinedBefore = new HashSet<string>(StringComparer.Ordinal);

		private readonly HashSet<string> _diedBefore = new HashSet<string>(StringComparer.Ordinal);

		private string PlayersFile => Path.Combine(Paths.ConfigPath, "SAFADOS.Arauto.jogadores.txt");

		private void Awake()
		{
			//IL_02e9: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			Instance = this;
			string[] commandLineArgs = Environment.GetCommandLineArgs();
			_isDedicated = commandLineArgs.Any((string a) => a.Equals("-batchmode", StringComparison.OrdinalIgnoreCase) || a.Equals("-nographics", StringComparison.OrdinalIgnoreCase));
			_url = ((BaseUnityPlugin)this).Config.Bind<string>("Webhook", "URL", "", "URL do webhook do canal do Discord (Configurações do canal > Integrações > Webhooks). Vazio = nada é enviado. Só o servidor usa.");
			_username = ((BaseUnityPlugin)this).Config.Bind<string>("Webhook", "Nome", "", "Nome exibido nas mensagens. Vazio = o nome do próprio webhook.");
			Msg("Servidor", "Iniciando", "## Servidor iniciando... ⏳", "Processo do servidor começou.");
			Msg("Servidor", "Iniciado", "## Servidor iniciado ✅", "Mundo pronto para jogar (com o Voxheim: quando ele termina de carregar).");
			Msg("Servidor", "Parando", "## Servidor está parando... \ud83e\udd1a", "Desligamento começou.");
			Msg("Servidor", "Parado", "## Servidor está parado \ud83d\udd34", "Desligamento terminou (mundo já salvo).");
			Msg("Servidor", "Salvamento", "-# \ud83d\udcbe Último salvamento às %SAVE_TIME%", "Mundo salvo. %SAVE_TIME% = horário no fuso de quem lê. Se a última mensagem do Arauto foi esta, ela é editada em vez de mandar outra.");
			Msg("Servidor", "NovoDia", "## \ud83c\udf05 %DAY_NUMBER%", "Começo de um novo dia no jogo. %DAY_NUMBER% = número do dia.");
			Msg("Jogadores", "Entrada", "### \ud83d\udc4b %PLAYER_NAME% CHEGOU!", "Jogador entrou no mundo.");
			Msg("Jogadores", "Saida", "### \ud83d\udca4 %PLAYER_NAME% PARTIU!", "Jogador saiu.");
			Msg("Jogadores", "Morte", "### \ud83d\udc80 %DEATH_TEXT%", "Jogador morreu. %DEATH_TEXT% = frase da causa (seção Mortes).");
			Msg("Jogadores", "Grito", "### \ud83d\udce2 %PLAYER_NAME%: **%SHOUT%**.", "Jogador gritou no chat.");
			Msg("Jogadores", "Ping", "### \ud83d\udccc %PLAYER_NAME% marcou um local no mapa.", "Jogador marcou um ponto no mapa.");
			Msg("Primeiras vezes", "PrimeiraEntrada", "Boas vindas a %PLAYER_NAME%, entrando no servidor pela primeira vez!!", "Enviada logo depois da entrada, só na primeira vez de cada jogador.");
			Msg("Primeiras vezes", "PrimeiraMorte", "%PLAYER_NAME% morreu pela primeira vez.", "Enviada logo depois da morte, só na primeira vez de cada jogador.");
			Msg("Eventos", "EventoInicio", "**Evento**: %EVENT_MSG%", "Um ataque/evento começou. %EVENT_MSG% = mensagem de início do jogo.");
			Msg("Eventos", "EventoFim", "**Evento**: %EVENT_MSG%", "O evento terminou. %EVENT_MSG% = mensagem de fim do jogo.");
			Msg("Eventos", "EventoPausa", "**Evento**: %EVENT_END_MSG% — for now! (Currently paused due to no players in the event area.)", "Ninguém na área do evento.");
			Msg("Eventos", "EventoRetomada", "**Evento**: %EVENT_START_MSG%", "Alguém voltou à área do evento.");
			_pingPos = ((BaseUnityPlugin)this).Config.Bind<bool>("Jogadores", "PingComPosicao", true, "Acrescenta a posição ao ping.");
			_eventPos = ((BaseUnityPlugin)this).Config.Bind<bool>("Eventos", "EventoComPosicao", true, "Acrescenta a posição aos eventos.");
			_readyTimeout = ((BaseUnityPlugin)this).Config.Bind<int>("Servidor", "EsperaMaximaVoxheimMinutos", 20, "Com o Voxheim instalado, espera até ele ficar pronto para anunciar \"Iniciado\"; passado este tempo depois do \"Opened Steam server\", anuncia mesmo assim.");
			Deaths.Bind(((BaseUnityPlugin)this).Config);
			_webhook = new Webhook(((BaseUnityPlugin)this).Logger, () => _url.Value, () => _username.Value);
			LoadPlayers();
			new Harmony("SAFADOS.Arauto").PatchAll(typeof(Plugin).Assembly);
			Logger.Listeners.Add((ILogListener)(object)new ReadyListener(this));
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Arauto 1.0.0 carregado (" + (_isDedicated ? "servidor dedicado" : "cliente") + "; webhook " + (_webhook.Configured ? "configurado" : "vazio") + ")."));
			if (_isDedicated)
			{
				Announce("Iniciando");
			}
		}

		private void Msg(string section, string key, string def, string desc)
		{
			_on[key] = ((BaseUnityPlugin)this).Config.Bind<bool>("Ligar", key, true, "Enviar a mensagem \"" + key + "\".");
			_msg[key] = ((BaseUnityPlugin)this).Config.Bind<string>(section, key, def, desc);
		}

		private string Text(string key)
		{
			if (!_on.TryGetValue(key, out var value) || !value.Value)
			{
				return null;
			}
			return _msg[key].Value;
		}

		private void Announce(string key, params (string Name, string Value)[] vars)
		{
			string text = Text(key);
			if (text != null)
			{
				for (int i = 0; i < vars.Length; i++)
				{
					(string, string) tuple = vars[i];
					text = text.Replace(tuple.Item1, tuple.Item2 ?? "");
				}
				_webhook.Send(text);
			}
		}

		private static string Pos(Vector3 p)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			return string.Format(CultureInfo.InvariantCulture, "\n-# \ud83d\udccd {0:0}, {1:0}", p.x, p.z);
		}

		internal void PlayerJoined(string name)
		{
			Announce("Entrada", ("%PLAYER_NAME%", name));
			if (_joinedBefore.Add(name))
			{
				Announce("PrimeiraEntrada", ("%PLAYER_NAME%", name));
				SavePlayers();
			}
		}

		internal void PlayerLeft(string name)
		{
			Announce("Saida", ("%PLAYER_NAME%", name));
		}

		internal void PlayerDied(string name, string cause, string enemy)
		{
			Announce("Morte", ("%DEATH_TEXT%", Deaths.Text(cause, name, enemy)), ("%PLAYER_NAME%", name));
			if (_diedBefore.Add(name))
			{
				Announce("PrimeiraMorte", ("%PLAYER_NAME%", name));
				SavePlayers();
			}
		}

		internal void PlayerShout(string name, string text)
		{
			Announce("Grito", ("%PLAYER_NAME%", name), ("%SHOUT%", text));
		}

		internal void PlayerPing(string name, Vector3 pos)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			string text = Text("Ping");
			if (text != null)
			{
				_webhook.Send(text.Replace("%PLAYER_NAME%", name) + (_pingPos.Value ? Pos(pos) : ""));
			}
		}

		internal void WorldSaved()
		{
			string text = Text("Salvamento");
			if (text != null)
			{
				long num = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
				_webhook.SendSave(text.Replace("%SAVE_TIME%", $"<t:{num}:t>"));
			}
		}

		internal void NewDay(int day)
		{
			Announce("NovoDia", ("%DAY_NUMBER%", day.ToString(CultureInfo.InvariantCulture)));
		}

		internal void ServerStopping()
		{
			string text = Text("Parando");
			if (text != null)
			{
				_webhook.SendNow(text);
			}
		}

		internal void ServerStopped()
		{
			string text = Text("Parado");
			if (text != null)
			{
				_webhook.SendNow(text);
			}
		}

		private void Event(string key, RandomEvent ev)
		{
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			string text = Text(key);
			if (text != null && ev != null)
			{
				string text2 = Localize(ev.m_startMessage);
				string text3 = Localize(ev.m_endMessage);
				string text4 = ((key == "EventoFim") ? text3 : text2);
				if (string.IsNullOrWhiteSpace(text4))
				{
					text4 = ev.m_name;
				}
				text = text.Replace("%EVENT_MSG%", text4).Replace("%EVENT_START_MSG%", text2).Replace("%EVENT_END_MSG%", text3);
				_webhook.Send(text + (_eventPos.Value ? Pos(ev.m_pos) : ""));
			}
		}

		internal void EventStarted(RandomEvent ev)
		{
			Event("EventoInicio", ev);
		}

		internal void EventStopped(RandomEvent ev)
		{
			Event("EventoFim", ev);
		}

		internal void EventPaused(RandomEvent ev)
		{
			Event("EventoPausa", ev);
		}

		internal void EventResumed(RandomEvent ev)
		{
			Event("EventoRetomada", ev);
		}

		private static string Localize(string token)
		{
			if (string.IsNullOrEmpty(token))
			{
				return "";
			}
			try
			{
				return (Localization.instance != null) ? Localization.instance.Localize(token) : token;
			}
			catch
			{
				return token;
			}
		}

		private void MarkReady(string why)
		{
			if (!_ready && _isDedicated)
			{
				_ready = true;
				((BaseUnityPlugin)this).Logger.LogInfo((object)("servidor pronto (" + why + "); anunciando."));
				Announce("Iniciado");
				if (Environment.GetEnvironmentVariable("ARAUTO_TESTE") == "1")
				{
					Teste.Run(this);
				}
			}
		}

		private void Update()
		{
			if (Time.realtimeSinceStartup < _nextPoll)
			{
				return;
			}
			_nextPoll = Time.realtimeSinceStartup + 2f;
			try
			{
				if (ZRoutedRpc.instance != null && _rpcRegistered != ZRoutedRpc.instance && (Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer())
				{
					ZRoutedRpc.instance.Register<string, string, string>("SAFADOS_Arauto_Morte", (Action<long, string, string, string>)Server.OnDeathRpc);
					_rpcRegistered = ZRoutedRpc.instance;
				}
				if (_openedSteam && !_ready && Time.realtimeSinceStartup - _openedAt > (float)_readyTimeout.Value * 60f)
				{
					MarkReady($"{_readyTimeout.Value} min depois do Opened Steam server, sem resposta do Voxheim");
				}
				if (_ready)
				{
					Server.PollEvent();
					Server.PollDay();
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogDebug((object)("update: " + ex.Message));
			}
		}

		private void LoadPlayers()
		{
			try
			{
				if (!File.Exists(PlayersFile))
				{
					return;
				}
				string[] array = File.ReadAllLines(PlayersFile);
				foreach (string text in array)
				{
					int num = text.IndexOf(':');
					if (num <= 0)
					{
						continue;
					}
					string text2 = text.Substring(0, num).Trim();
					string text3 = text.Substring(num + 1).Trim();
					if (text3.Length != 0)
					{
						if (text2 == "entrou")
						{
							_joinedBefore.Add(text3);
						}
						else if (text2 == "morreu")
						{
							_diedBefore.Add(text3);
						}
					}
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("lista de jogadores: " + ex.Message));
			}
		}

		private void SavePlayers()
		{
			try
			{
				List<string> list = new List<string> { "# Arauto: jogadores que já entraram / já morreram (para as mensagens de primeira vez). Uma linha por jogador." };
				list.AddRange(from n in _joinedBefore
					orderby n
					select "entrou: " + n);
				list.AddRange(from n in _diedBefore
					orderby n
					select "morreu: " + n);
				File.WriteAllLines(PlayersFile, list);
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("lista de jogadores: " + ex.Message));
			}
		}
	}
	internal static class Server
	{
		[HarmonyPatch(typeof(ZNet), "RPC_CharacterID")]
		private static class CharacterIdPatch
		{
			private static void Postfix(ZNet __instance, ZRpc rpc, ZDOID characterID)
			{
				//IL_007c: Unknown result type (might be due to invalid IL or missing references)
				//IL_007d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0061: Unknown result type (might be due to invalid IL or missing references)
				//IL_0095: Unknown result type (might be due to invalid IL or missing references)
				try
				{
					if (!IsServer || ((ZDOID)(ref characterID)).IsNone())
					{
						return;
					}
					ZNetPeer val = ((IEnumerable<ZNetPeer>)__instance.GetPeers()).FirstOrDefault((Func<ZNetPeer, bool>)((ZNetPeer p) => p.m_rpc == rpc));
					if (val == null)
					{
						return;
					}
					if (!LastCharacter.TryGetValue(val.m_uid, out var value))
					{
						LastCharacter[val.m_uid] = characterID;
						Plugin.Instance.PlayerJoined(val.m_playerName);
					}
					else if (!(value == characterID))
					{
						LastCharacter[val.m_uid] = characterID;
						float value2;
						bool num = DeathReported.TryGetValue(val.m_uid, out value2) && Time.time - value2 < 600f;
						DeathReported.Remove(val.m_uid);
						if (!num)
						{
							Plugin.Instance.PlayerDied(val.m_playerName, "", "");
						}
					}
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("entrada/morte: " + ex.Message));
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "Disconnect")]
		private static class DisconnectPatch
		{
			private static void Prefix(ZNetPeer peer)
			{
				try
				{
					if (IsServer && peer != null)
					{
						if (LastCharacter.Remove(peer.m_uid))
						{
							Plugin.Instance.PlayerLeft(peer.m_playerName);
						}
						DeathReported.Remove(peer.m_uid);
					}
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("saída: " + ex.Message));
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "SaveWorld")]
		private static class SaveWorldPatch
		{
			private static void Postfix()
			{
				if (IsServer && !_stopping)
				{
					Plugin.Instance.WorldSaved();
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "Shutdown")]
		private static class ShutdownPatch
		{
			private static void Prefix()
			{
				if (IsServer && !_stopping)
				{
					_stopping = true;
					Plugin.Instance.ServerStopping();
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "OnDestroy")]
		private static class OnDestroyPatch
		{
			private static void Postfix(ZNet __instance)
			{
				if (_stopping)
				{
					Plugin.Instance.ServerStopped();
				}
			}
		}

		[HarmonyPatch(typeof(ZRoutedRpc), "RouteRPC")]
		private static class RoutePatch
		{
			private static void Prefix(RoutedRPCData rpcData)
			{
				Chat(rpcData);
			}
		}

		[HarmonyPatch(typeof(ZRoutedRpc), "HandleRoutedRPC")]
		private static class HandlePatch
		{
			private static void Prefix(RoutedRPCData data)
			{
				Chat(data);
			}
		}

		[HarmonyPatch(typeof(RandEventSystem), "SetRandomEvent")]
		private static class SetRandomEventPatch
		{
			private static void Prefix(RandEventSystem __instance)
			{
				try
				{
					if (IsServer)
					{
						RandomEvent currentRandomEvent = __instance.GetCurrentRandomEvent();
						if (currentRandomEvent != null)
						{
							Plugin.Instance.EventStopped(currentRandomEvent);
						}
						_event = null;
					}
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("evento (fim): " + ex.Message));
				}
			}

			private static void Postfix(RandEventSystem __instance, RandomEvent ev)
			{
				try
				{
					if (IsServer && ev != null)
					{
						_event = __instance.GetCurrentRandomEvent();
						_eventPaused = false;
						if (_event != null)
						{
							Plugin.Instance.EventStarted(_event);
						}
					}
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("evento (início): " + ex.Message));
				}
			}
		}

		private static readonly Dictionary<long, ZDOID> LastCharacter = new Dictionary<long, ZDOID>();

		private static readonly Dictionary<long, float> DeathReported = new Dictionary<long, float>();

		private static bool _stopping;

		private static readonly int ChatHash = StringExtensionMethods.GetStableHashCode("ChatMessage");

		private static readonly Dictionary<string, float> RecentChat = new Dictionary<string, float>();

		private static readonly MethodInfo AnyPlayerInArea = AccessTools.Method(typeof(RandEventSystem), "IsAnyPlayerInEventArea", (Type[])null, (Type[])null);

		private static RandomEvent _event;

		private static bool _eventPaused;

		private static int _day = -1;

		private static bool IsServer
		{
			get
			{
				if ((Object)(object)ZNet.instance != (Object)null)
				{
					return ZNet.instance.IsServer();
				}
				return false;
			}
		}

		internal static void OnDeathRpc(long sender, string cause, string enemy, string playerName)
		{
			try
			{
				if (IsServer)
				{
					string text = ZNet.instance.GetPeer(sender)?.m_playerName;
					if (string.IsNullOrEmpty(text))
					{
						text = playerName;
					}
					if (!string.IsNullOrEmpty(text))
					{
						DeathReported[sender] = Time.time;
						Plugin.Instance.PlayerDied(text, cause ?? "", enemy ?? "");
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("aviso de morte: " + ex.Message));
			}
		}

		private static void Chat(RoutedRPCData data)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: 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)
			//IL_0035: 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_003c: 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_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Invalid comparison between Unknown and I4
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Expected I4, but got Unknown
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Invalid comparison between Unknown and I4
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Invalid comparison between Unknown and I4
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			if (data == null || data.m_methodHash != ChatHash || !IsServer)
			{
				return;
			}
			try
			{
				ZPackage val = new ZPackage(data.m_parameters.GetArray());
				Vector3 pos = val.ReadVector3();
				Type val2 = (Type)val.ReadInt();
				string text = val.ReadString();
				val.ReadString();
				string text2 = val.ReadString();
				if ((int)val2 != 2 && (int)val2 != 3)
				{
					return;
				}
				string key = $"{data.m_senderPeerID}|{(int)val2}|{text2}";
				float now = Time.time;
				if (RecentChat.TryGetValue(key, out var value) && now - value < 3f)
				{
					return;
				}
				RecentChat[key] = now;
				if (RecentChat.Count > 200)
				{
					foreach (string item in (from kv in RecentChat
						where now - kv.Value > 10f
						select kv.Key).ToList())
					{
						RecentChat.Remove(item);
					}
				}
				string name = ZNet.instance.GetPeer(data.m_senderPeerID)?.m_playerName ?? text;
				if ((int)val2 == 2)
				{
					Plugin.Instance.PlayerShout(name, text2);
				}
				else
				{
					Plugin.Instance.PlayerPing(name, pos);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogDebug((object)("chat: " + ex.Message));
			}
		}

		internal static void PollEvent()
		{
			try
			{
				if (!IsServer || (Object)(object)RandEventSystem.instance == (Object)null || AnyPlayerInArea == null)
				{
					return;
				}
				RandomEvent currentRandomEvent = RandEventSystem.instance.GetCurrentRandomEvent();
				if (currentRandomEvent == null || currentRandomEvent != _event)
				{
					return;
				}
				bool flag = (bool)AnyPlayerInArea.Invoke(RandEventSystem.instance, new object[1] { currentRandomEvent });
				if (flag != !_eventPaused)
				{
					_eventPaused = !flag;
					if (_eventPaused)
					{
						Plugin.Instance.EventPaused(currentRandomEvent);
					}
					else
					{
						Plugin.Instance.EventResumed(currentRandomEvent);
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogDebug((object)("evento (pausa): " + ex.Message));
			}
		}

		internal static void PollDay()
		{
			if (IsServer && !((Object)(object)EnvMan.instance == (Object)null))
			{
				int day = EnvMan.instance.GetDay();
				if (_day >= 0 && day > _day)
				{
					Plugin.Instance.NewDay(day);
				}
				_day = day;
			}
		}
	}
	internal static class Teste
	{
		internal static void Run(Plugin p)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: 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_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Expected O, but got Unknown
			Plugin.Log.LogWarning((object)"ARAUTO_TESTE=1: enviando mensagens de teste.");
			p.PlayerJoined("Teste");
			p.PlayerShout("Teste", "olá @everyone, isto não deve marcar ninguém");
			p.PlayerPing("Teste", new Vector3(1234.6f, 30f, -567.4f));
			string[] array = new string[24]
			{
				"Fall", "Drowning", "Smoke", "Burning", "CinderFire", "AshlandsLava", "AshlandsOcean", "Freezing", "Poisoned", "Water",
				"EdgeOfWorld", "Tree", "Structural", "Stalagtite", "Impact", "Cart", "Boat", "Turret", "Catapult", "Incinerator",
				"DrawBridge", "Self", "Undefined", ""
			};
			foreach (string cause in array)
			{
				p.PlayerDied("Teste", cause, "");
			}
			p.PlayerDied("Teste", "EnemyHit", "Troll");
			p.PlayerDied("Teste", "EnemyHit", "Moder");
			p.PlayerDied("Teste", "EnemyHit", "");
			p.PlayerDied("Teste", "PlayerHit", "Outro Viking");
			RandomEvent ev = new RandomEvent
			{
				m_name = "army_eikthyr",
				m_startMessage = "$event_eikthyrarmy_start",
				m_endMessage = "$event_eikthyrarmy_end",
				m_pos = new Vector3(100f, 0f, 200f)
			};
			p.EventStarted(ev);
			p.EventPaused(ev);
			p.EventResumed(ev);
			p.EventStopped(ev);
			p.WorldSaved();
			p.WorldSaved();
			p.WorldSaved();
			p.NewDay(123);
			p.WorldSaved();
			p.WorldSaved();
			p.PlayerLeft("Teste");
		}
	}
	internal sealed class Webhook
	{
		private sealed class Job
		{
			public string Content;

			public bool IsSave;

			public bool Edit;
		}

		private readonly ManualLogSource _log;

		private readonly Func<string> _url;

		private readonly Func<string> _username;

		private readonly Queue<Job> _queue = new Queue<Job>();

		private readonly object _gate = new object();

		private readonly AutoResetEvent _signal = new AutoResetEvent(initialState: false);

		private Thread _thread;

		private volatile bool _busy;

		private bool _lastWasSave;

		private string _saveMessageId;

		public bool Configured => !string.IsNullOrWhiteSpace(_url());

		public Webhook(ManualLogSource log, Func<string> url, Func<string> username)
		{
			_log = log;
			_url = url;
			_username = username;
			try
			{
				ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
			}
			catch
			{
			}
		}

		public void Send(string content)
		{
			if (Configured && !string.IsNullOrWhiteSpace(content))
			{
				lock (_gate)
				{
					_lastWasSave = false;
					_queue.Enqueue(new Job
					{
						Content = content
					});
				}
				Start();
			}
		}

		public void SendSave(string content)
		{
			if (Configured && !string.IsNullOrWhiteSpace(content))
			{
				lock (_gate)
				{
					bool lastWasSave = _lastWasSave;
					_lastWasSave = true;
					_queue.Enqueue(new Job
					{
						Content = content,
						IsSave = true,
						Edit = lastWasSave
					});
				}
				Start();
			}
		}

		public void SendNow(string content, int timeoutMs = 5000)
		{
			if (!Configured || string.IsNullOrWhiteSpace(content))
			{
				return;
			}
			DateTime dateTime = DateTime.UtcNow.AddMilliseconds(timeoutMs);
			DateTime dateTime2 = DateTime.UtcNow.AddMilliseconds(Math.Min(3000, timeoutMs));
			while (DateTime.UtcNow < dateTime2)
			{
				bool flag;
				lock (_gate)
				{
					flag = _queue.Count == 0;
				}
				if (flag && !_busy)
				{
					break;
				}
				Thread.Sleep(50);
			}
			lock (_gate)
			{
				_lastWasSave = false;
			}
			Post(content, wait: false, Math.Max(2000, (int)(dateTime - DateTime.UtcNow).TotalMilliseconds));
		}

		private void Start()
		{
			_signal.Set();
			if (_thread == null)
			{
				_thread = new Thread(Loop)
				{
					IsBackground = true,
					Name = "Arauto.Webhook"
				};
				_thread.Start();
			}
		}

		private void Loop()
		{
			while (true)
			{
				Job job = null;
				lock (_gate)
				{
					if (_queue.Count > 0)
					{
						job = _queue.Dequeue();
					}
				}
				if (job == null)
				{
					_busy = false;
					_signal.WaitOne(5000);
					continue;
				}
				_busy = true;
				try
				{
					string text = null;
					if (job.Edit)
					{
						lock (_gate)
						{
							text = _saveMessageId;
						}
					}
					if (text != null && Patch(text, job.Content))
					{
						continue;
					}
					string saveMessageId = Post(job.Content, job.IsSave, 15000);
					if (job.IsSave)
					{
						lock (_gate)
						{
							_saveMessageId = saveMessageId;
						}
					}
				}
				catch (ThreadAbortException)
				{
					break;
				}
				catch (Exception ex2)
				{
					_log.LogWarning((object)("webhook: " + ex2.Message));
				}
			}
		}

		private string BaseUrl()
		{
			string text = _url().Trim();
			int num = text.IndexOf('?');
			if (num < 0)
			{
				return text;
			}
			return text.Substring(0, num);
		}

		private string Json(string content)
		{
			StringBuilder stringBuilder = new StringBuilder("{\"content\":").Append(Escape(content));
			string text = _username();
			if (!string.IsNullOrWhiteSpace(text))
			{
				stringBuilder.Append(",\"username\":").Append(Escape(text.Trim()));
			}
			stringBuilder.Append(",\"allowed_mentions\":{\"parse\":[]}}");
			return stringBuilder.ToString();
		}

		private string Post(string content, bool wait, int timeoutMs)
		{
			string text = Request("POST", BaseUrl() + (wait ? "?wait=true" : ""), Json(content), timeoutMs);
			if (text == null || !wait)
			{
				return null;
			}
			Match match = Regex.Match(text, "\"id\"\\s*:\\s*\"(\\d+)\"");
			if (!match.Success)
			{
				return null;
			}
			return match.Groups[1].Value;
		}

		private bool Patch(string id, string content)
		{
			return Request("PATCH", BaseUrl() + "/messages/" + id, Json(content), 15000) != null;
		}

		private string Request(string method, string url, string json, int timeoutMs)
		{
			HttpWebResponse httpWebResponse2 = default(HttpWebResponse);
			HttpWebResponse httpWebResponse3 = default(HttpWebResponse);
			for (int i = 0; i < 4; i++)
			{
				try
				{
					HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
					httpWebRequest.Method = method;
					httpWebRequest.ContentType = "application/json";
					httpWebRequest.UserAgent = "Arauto (Valheim server)";
					httpWebRequest.Timeout = timeoutMs;
					httpWebRequest.ReadWriteTimeout = timeoutMs;
					byte[] bytes = Encoding.UTF8.GetBytes(json);
					httpWebRequest.ContentLength = bytes.Length;
					using (Stream stream = httpWebRequest.GetRequestStream())
					{
						stream.Write(bytes, 0, bytes.Length);
					}
					using HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
					using StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
					return streamReader.ReadToEnd();
				}
				catch (WebException ex) when (((Func<bool>)delegate
				{
					// Could not convert BlockContainer to single expression
					httpWebResponse2 = ex.Response as HttpWebResponse;
					return httpWebResponse2 != null && httpWebResponse2.StatusCode == HttpStatusCode.TooManyRequests && i < 3;
				}).Invoke())
				{
					double result = 1.0;
					try
					{
						using StreamReader streamReader2 = new StreamReader(httpWebResponse2.GetResponseStream(), Encoding.UTF8);
						Match match = Regex.Match(streamReader2.ReadToEnd(), "\"retry_after\"\\s*:\\s*([0-9.]+)");
						if (match.Success)
						{
							double.TryParse(match.Groups[1].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out result);
						}
					}
					catch
					{
					}
					Thread.Sleep((int)(Math.Min(Math.Max(result, 0.5), 10.0) * 1000.0));
				}
				catch (WebException ex2) when (((Func<bool>)delegate
				{
					// Could not convert BlockContainer to single expression
					httpWebResponse3 = ex2.Response as HttpWebResponse;
					return httpWebResponse3 != null;
				}).Invoke())
				{
					string s = "";
					try
					{
						using StreamReader streamReader3 = new StreamReader(httpWebResponse3.GetResponseStream(), Encoding.UTF8);
						s = streamReader3.ReadToEnd();
					}
					catch
					{
					}
					_log.LogWarning((object)$"webhook: {method} recusado ({(int)httpWebResponse3.StatusCode} {httpWebResponse3.StatusDescription}) {Trim(s)}");
					return null;
				}
				catch (ThreadAbortException)
				{
					throw;
				}
				catch (Exception ex4)
				{
					if (ex4 is WebException ex5 && ex5.InnerException is ThreadAbortException)
					{
						throw ex5.InnerException;
					}
					_log.LogWarning((object)("webhook: " + method + " falhou: " + ex4.GetType().Name + ": " + ex4.Message));
					return null;
				}
			}
			return null;
		}

		private static string Trim(string s)
		{
			if (s != null)
			{
				if (s.Length <= 200)
				{
					return s;
				}
				return s.Substring(0, 200) + "…";
			}
			return "";
		}

		internal static string Escape(string s)
		{
			StringBuilder stringBuilder = new StringBuilder("\"");
			string text = s ?? "";
			foreach (char c in text)
			{
				switch (c)
				{
				case '"':
					stringBuilder.Append("\\\"");
					continue;
				case '\\':
					stringBuilder.Append("\\\\");
					continue;
				case '\n':
					stringBuilder.Append("\\n");
					continue;
				case '\t':
					stringBuilder.Append("\\t");
					continue;
				case '\r':
					continue;
				}
				if (c < ' ')
				{
					StringBuilder stringBuilder2 = stringBuilder.Append("\\u");
					int num = c;
					stringBuilder2.Append(num.ToString("x4"));
				}
				else
				{
					stringBuilder.Append(c);
				}
			}
			return stringBuilder.Append('"').ToString();
		}
	}
}