Decompiled source of LethalOpenShock v0.1.2

OpenShock.Integrations.LethalCompany.dll

Decompiled 7 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using OpenShock.Integrations.LethalCompany.OpenShockApi;
using OpenShock.Integrations.LethalCompany.OpenShockApi.Models;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("OpenShock.Integrations.LethalCompany")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.2")]
[assembly: AssemblyInformationalVersion("0.1.2+05fdbc5c294c8e59ecc1eb041855a6ad8c4708bf")]
[assembly: AssemblyProduct("OpenShock.Integrations.LethalCompany")]
[assembly: AssemblyTitle("OpenShock.Integrations.LethalCompany")]
[assembly: AssemblyVersion("0.1.2.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 OpenShock.Integrations.LethalCompany
{
	[BepInPlugin("OpenShock.Integrations.LethalCompany", "OpenShock.Integrations.LethalCompany", "0.1.2")]
	public class LethalCompanyOpenShock : BaseUnityPlugin
	{
		private OpenShock.Integrations.LethalCompany.OpenShockApi.OpenShockApi _openShockApi;

		private readonly Harmony _harmony = new Harmony("OpenShock.Integrations.LethalCompany");

		private ConfigEntry<string> _openShockServer;

		private ConfigEntry<string> _openShockApiToken;

		private ConfigEntry<string> _shockers;

		private ConfigEntry<byte> _settingOnDeathIntensity;

		private ConfigEntry<ushort> _settingOnDeathDuration;

		private ConfigEntry<ushort> _settingOnDamageDuration;

		private ConfigEntry<byte> _settingOnDamageIntensityLimit;

		private IList<Guid> _shockersList;

		public static LethalCompanyOpenShock Instance { get; private set; }

		public static ManualLogSource ModLogger { get; private set; }

		private void Awake()
		{
			ModLogger = ((BaseUnityPlugin)this).Logger;
			Instance = this;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Starting OpenShock.Integrations.LethalCompany");
			_openShockServer = ((BaseUnityPlugin)this).Config.Bind<string>("OpenShock", "Server", "https://api.shocklink.net", "The URL of the OpenShock backend");
			_openShockApiToken = ((BaseUnityPlugin)this).Config.Bind<string>("OpenShock", "ApiToken", "", "API token for authentication, can be found under API Tokens on the OpenShock dashboard (https://shocklink.net/#/dashboard/tokens)");
			_shockers = ((BaseUnityPlugin)this).Config.Bind<string>("Shockers", "Shockers", "comma,seperated,list,of,shocker,ids", "A list of shocker IDs to use within the mod. Comma seperated.");
			_settingOnDeathIntensity = ((BaseUnityPlugin)this).Config.Bind<byte>("OnDeath", "Intensity", (byte)100, "The intensity of the shocker when the player dies");
			_settingOnDeathDuration = ((BaseUnityPlugin)this).Config.Bind<ushort>("OnDeath", "Duration", (ushort)5000, "The duration of the shocker when the player dies");
			_settingOnDamageDuration = ((BaseUnityPlugin)this).Config.Bind<ushort>("OnDamage", "Duration", (ushort)5000, "The duration of the shocker when the player takes damage");
			_settingOnDamageIntensityLimit = ((BaseUnityPlugin)this).Config.Bind<byte>("OnDamage", "IntensityLimit", (byte)100, "Intensity limit for the shocker when the player takes damage");
			((BaseUnityPlugin)this).Logger.LogDebug((object)"Patching PlayerController");
			_harmony.PatchAll(typeof(PlayerControllerPatches));
			_openShockServer.SettingChanged += delegate
			{
				SetupApi();
			};
			_openShockApiToken.SettingChanged += delegate
			{
				SetupApi();
			};
			_shockers.SettingChanged += delegate
			{
				ShockersSetup();
			};
			SetupApi();
			ShockersSetup();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Started OpenShock.Integrations.LethalCompany");
		}

		private void ShockersSetup()
		{
			List<Guid> list = new List<Guid>();
			string[] array = _shockers.Value.Split(new char[1] { ',' });
			foreach (string text in array)
			{
				if (Guid.TryParse(text, out var result))
				{
					ManualLogSource logger = ((BaseUnityPlugin)this).Logger;
					Guid guid = result;
					logger.LogInfo((object)("Found shocker ID " + guid));
					list.Add(result);
				}
				else
				{
					((BaseUnityPlugin)this).Logger.LogError((object)("Failed to parse shocker ID " + text));
				}
			}
			_shockersList = list;
		}

		private void SetupApi()
		{
			_openShockApi = new OpenShock.Integrations.LethalCompany.OpenShockApi.OpenShockApi(new Uri(_openShockServer.Value), _openShockApiToken.Value);
		}

		public void OnDamage(int health, int damageNumber)
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)$"Received damage, health is {health}, damage is {damageNumber}");
			FireAndForgetControl(_settingOnDamageDuration.Value, (byte)Mathf.Clamp(damageNumber, 1, (int)_settingOnDamageIntensityLimit.Value), ControlType.Shock);
		}

		private void FireAndForgetControl(ushort duration, byte intensity, ControlType type)
		{
			LucTask.Run(() => SendControlToAll(duration, intensity, type), default(CancellationToken), "F:\\Dev\\Git\\ShockLink\\Integrations.LethalCompany\\Integrations.LethalCompany\\LethalCompanyOpenShock.cs", "FireAndForgetControl", 116);
		}

		private Task SendControlToAll(ushort duration, byte intensity, ControlType type)
		{
			IEnumerable<Control> shocks = _shockersList.Select((Guid shocker) => new Control
			{
				Id = shocker,
				Duration = duration,
				Intensity = intensity,
				Type = type
			});
			return _openShockApi.Control(shocks);
		}

		public void OnDeath()
		{
			FireAndForgetControl(_settingOnDeathDuration.Value, _settingOnDeathIntensity.Value, ControlType.Shock);
		}
	}
	public static class LucTask
	{
		public static Task Run(Func<Task?> function, CancellationToken token = default(CancellationToken), [CallerFilePath] string file = "", [CallerMemberName] string member = "", [CallerLineNumber] int line = -1)
		{
			string file2 = file;
			string member2 = member;
			return Task.Run(function, token).ContinueWith(delegate(Task t)
			{
				if (t.IsFaulted)
				{
					int num = file2.LastIndexOf('\\');
					if (num == -1)
					{
						num = file2.LastIndexOf('/');
					}
					LethalCompanyOpenShock.ModLogger.LogError((object)$"Error during task execution. {file2.Substring(num + 1, file2.Length - num - 1)}::{member2}:{line} {t.Exception}");
				}
			}, TaskContinuationOptions.OnlyOnFaulted);
		}
	}
	public static class PlayerControllerPatches
	{
		[HarmonyPatch(typeof(PlayerControllerB), "KillPlayer")]
		[HarmonyPostfix]
		public static void OnDeath(PlayerControllerB __instance)
		{
			if (((NetworkBehaviour)__instance).IsOwner && __instance.AllowPlayerDeath())
			{
				LethalCompanyOpenShock.Instance.OnDeath();
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "DamagePlayer")]
		[HarmonyPostfix]
		private static void DamagePatch(PlayerControllerB __instance, int damageNumber)
		{
			if (((NetworkBehaviour)__instance).IsOwner && !__instance.isPlayerDead && __instance.AllowPlayerDeath())
			{
				LethalCompanyOpenShock.Instance.OnDamage(__instance.health, damageNumber);
			}
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "OpenShock.Integrations.LethalCompany";

		public const string PLUGIN_NAME = "OpenShock.Integrations.LethalCompany";

		public const string PLUGIN_VERSION = "0.1.2";
	}
}
namespace OpenShock.Integrations.LethalCompany.OpenShockApi
{
	public class OpenShockApi
	{
		private static readonly ManualLogSource Logger = Logger.CreateLogSource("OpenShockApi");

		private readonly HttpClient _httpClient;

		public OpenShockApi(Uri server, string apiToken)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			_httpClient = new HttpClient
			{
				BaseAddress = server
			};
			((HttpHeaders)_httpClient.DefaultRequestHeaders).Add("User-Agent", "OpenShock.Integrations.LethalCompany/0.1.2");
			((HttpHeaders)_httpClient.DefaultRequestHeaders).Add("OpenShockToken", apiToken);
		}

		public async Task Control(IEnumerable<Control> shocks)
		{
			Logger.LogInfo((object)"Sending control request to OpenShock API");
			HttpRequestMessage val = new HttpRequestMessage(HttpMethod.Post, "/2/shockers/control")
			{
				Content = (HttpContent)new StringContent(JsonConvert.SerializeObject((object)new ControlRequest
				{
					Shocks = shocks,
					CustomName = "Integrations.LethalCompany"
				}), Encoding.UTF8, "application/json")
			};
			HttpResponseMessage val2 = await _httpClient.SendAsync(val);
			if (!val2.IsSuccessStatusCode)
			{
				Logger.LogError((object)$"Failed to send control request to OpenShock API [{val2.StatusCode}]");
			}
		}
	}
}
namespace OpenShock.Integrations.LethalCompany.OpenShockApi.Models
{
	public class Control
	{
		public Guid Id { get; set; }

		public ControlType Type { get; set; }

		public byte Intensity { get; set; }

		public ushort Duration { get; set; }
	}
	public class ControlRequest
	{
		public IEnumerable<Control> Shocks { get; set; }

		public string? CustomName { get; set; }
	}
	public enum ControlType
	{
		Stop,
		Shock,
		Vibrate,
		Sound
	}
}