Decompiled source of ChatFX v1.0.0

Mods/ChatFx.dll

Decompiled 37 minutes ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using ChatFx;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppScheduleOne.EntityFramework;
using Il2CppScheduleOne.ItemFramework;
using Il2CppScheduleOne.Money;
using Il2CppScheduleOne.ObjectScripts;
using Il2CppScheduleOne.PlayerScripts;
using Il2CppScheduleOne.Product;
using Il2CppScheduleOne.Property;
using Il2CppScheduleOne.Storage;
using Il2CppSystem.Collections.Generic;
using MelonLoader;
using MelonLoader.Preferences;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(Core), "Chat FX", "1.0.0", "purplehaxttv", null)]
[assembly: MelonGame("TVGS", "Schedule I")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("ChatFx")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+a8c46318b008a3b5203ec051ce2209899becd57d")]
[assembly: AssemblyProduct("ChatFx")]
[assembly: AssemblyTitle("ChatFx")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[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 ChatFx
{
	public class Core : MelonMod
	{
		private static MelonPreferences_Category cfg;

		private static MelonPreferences_Entry<int> portEntry;

		public override void OnInitializeMelon()
		{
			cfg = MelonPreferences.CreateCategory("ChatFx");
			portEntry = cfg.CreateEntry<int>("Port", 7900, (string)null, "Local HTTP port Firebot hits to trigger in-game effects.", false, false, (ValueValidator)null, (string)null);
			FxServer.Start(portEntry.Value, ((MelonBase)this).LoggerInstance);
		}

		public override void OnUpdate()
		{
			FxServer.Pump();
		}

		public override void OnDeinitializeMelon()
		{
			FxServer.Stop();
		}
	}
	public static class FxServer
	{
		private static HttpListener listener;

		private static Thread thread;

		private static volatile bool running;

		private static Instance log;

		private static readonly ConcurrentQueue<Action> queue = new ConcurrentQueue<Action>();

		private static readonly Random rng = new Random();

		public static void Start(int port, Instance logger)
		{
			log = logger;
			try
			{
				listener = new HttpListener();
				listener.Prefixes.Add($"http://localhost:{port}/");
				listener.Start();
				running = true;
				thread = new Thread(Loop)
				{
					IsBackground = true,
					Name = "ChatFx-Listener"
				};
				thread.Start();
				log.Msg($"Chat FX listening on http://localhost:{port}/fx");
			}
			catch (Exception ex)
			{
				log.Error($"Chat FX failed to start on port {port}: {ex.Message}");
			}
		}

		public static void Stop()
		{
			running = false;
			try
			{
				listener?.Stop();
			}
			catch
			{
			}
			try
			{
				listener?.Close();
			}
			catch
			{
			}
		}

		public static void Pump()
		{
			Action result;
			while (queue.TryDequeue(out result))
			{
				try
				{
					result();
				}
				catch (Exception ex)
				{
					log.Warning("Chat FX effect error: " + ex.Message);
				}
			}
		}

		private static void Loop()
		{
			while (running)
			{
				HttpListenerContext context;
				try
				{
					context = listener.GetContext();
				}
				catch
				{
					break;
				}
				string text;
				try
				{
					string type = (context.Request.QueryString["type"] ?? "").ToLowerInvariant();
					string amountStr = context.Request.QueryString["amount"];
					string levelStr = (context.Request.QueryString["level"] ?? "").ToLowerInvariant();
					string propStr = (context.Request.QueryString["property"] ?? "").ToLowerInvariant();
					string targetStr = (context.Request.QueryString["target"] ?? "").ToLowerInvariant();
					text = Dispatch(type, amountStr, levelStr, propStr, targetStr);
				}
				catch (Exception ex)
				{
					text = "error: " + ex.Message;
				}
				try
				{
					byte[] bytes = Encoding.UTF8.GetBytes(text);
					context.Response.StatusCode = (text.StartsWith("error") ? 400 : 200);
					context.Response.ContentType = "text/plain";
					context.Response.OutputStream.Write(bytes, 0, bytes.Length);
					context.Response.OutputStream.Close();
				}
				catch
				{
				}
			}
		}

		private static string Dispatch(string type, string amountStr, string levelStr, string propStr, string targetStr)
		{
			switch (type)
			{
			case "help":
			case "bank":
			case "deposit":
			{
				float amount2 = 100f;
				if (!string.IsNullOrEmpty(amountStr) && float.TryParse(amountStr, out var result8))
				{
					amount2 = result8;
				}
				queue.Enqueue(delegate
				{
					FxAddBank(amount2);
				});
				return $"ok: +${amount2} bank queued";
			}
			case "cashgift":
			case "tip":
			{
				float amount = 100f;
				if (!string.IsNullOrEmpty(amountStr) && float.TryParse(amountStr, out var result5))
				{
					amount = result5;
				}
				queue.Enqueue(delegate
				{
					FxGiveCash(amount);
				});
				return $"ok: +${amount} cash queued";
			}
			case "pardon":
			case "clearwanted":
			{
				string t2 = targetStr;
				queue.Enqueue(delegate
				{
					FxClearWanted(t2);
				});
				return "ok: pardon on '" + (string.IsNullOrEmpty(t2) ? "self" : t2) + "' queued";
			}
			case "gift":
			case "resupply":
			{
				int count4 = 10;
				if (!string.IsNullOrEmpty(amountStr) && int.TryParse(amountStr, out var result7))
				{
					count4 = result7;
				}
				queue.Enqueue(delegate
				{
					FxGiveDrugs(count4);
				});
				return $"ok: gift {count4} product queued";
			}
			case "restock":
			case "supplydrop":
			{
				if (string.IsNullOrEmpty(propStr))
				{
					return "error: restock needs &property=<name>";
				}
				int count2 = 20;
				if (!string.IsNullOrEmpty(amountStr) && int.TryParse(amountStr, out var result3))
				{
					count2 = result3;
				}
				string p2 = propStr;
				queue.Enqueue(delegate
				{
					FxRestockProperty(p2, count2);
				});
				return $"ok: restock '{p2}' with {count2} product queued";
			}
			case "hurt":
			case "arrest":
			{
				string t = targetStr;
				queue.Enqueue(delegate
				{
					FxPursuit(levelStr, t);
				});
				return $"ok: pursuit '{(string.IsNullOrEmpty(levelStr) ? "arresting" : levelStr)}' on '{(string.IsNullOrEmpty(t) ? "self" : t)}' queued";
			}
			case "pickpocket":
			case "steal":
			{
				int cap2 = 100;
				if (!string.IsNullOrEmpty(amountStr) && int.TryParse(amountStr, out var result4))
				{
					cap2 = result4;
				}
				queue.Enqueue(delegate
				{
					FxStealCash(cap2);
				});
				return $"ok: pickpocket up to ${cap2} queued";
			}
			case "hack":
			case "hacker":
			{
				int cap = 500;
				if (!string.IsNullOrEmpty(amountStr) && int.TryParse(amountStr, out var result2))
				{
					cap = result2;
				}
				queue.Enqueue(delegate
				{
					FxDrainBank(cap);
				});
				return $"ok: hack up to ${cap} queued";
			}
			case "gang":
			case "rivalgang":
			{
				int count3 = 10;
				if (!string.IsNullOrEmpty(amountStr) && int.TryParse(amountStr, out var result6))
				{
					count3 = result6;
				}
				queue.Enqueue(delegate
				{
					FxRemoveDrugs(count3);
				});
				return $"ok: rival gang steals up to {count3} product queued";
			}
			case "raid":
			case "gangraid":
			{
				if (string.IsNullOrEmpty(propStr))
				{
					return "error: raid needs &property=<name>";
				}
				int count = 20;
				if (!string.IsNullOrEmpty(amountStr) && int.TryParse(amountStr, out var result))
				{
					count = result;
				}
				string p = propStr;
				queue.Enqueue(delegate
				{
					FxRaidProperty(p, count);
				});
				return $"ok: raid '{p}' for up to {count} product queued";
			}
			default:
				return "error: unknown fx type '" + type + "'";
			}
		}

		private static void FxAddBank(float amount)
		{
			MoneyManager val = Object.FindObjectOfType<MoneyManager>();
			if ((Object)(object)val == (Object)null)
			{
				log.Warning("FxAddBank: no MoneyManager (not in a game?)");
				return;
			}
			val.CreateOnlineTransaction("Chat Gift", amount, 1f, "Someone helped you out!");
			log.Msg($"Chat FX: added ${amount} to bank balance.");
		}

		private static List<Player> GetTargets(string target)
		{
			List<Player> list = new List<Player>();
			List<Player> playerList = Player.PlayerList;
			if (playerList == null)
			{
				return list;
			}
			for (int i = 0; i < playerList.Count; i++)
			{
				Player val = playerList[i];
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				if (!string.IsNullOrEmpty(target))
				{
					switch (target)
					{
					case "self":
					case "me":
						break;
					case "all":
					case "everyone":
						goto IL_0072;
					case "others":
						goto IL_0084;
					default:
						goto IL_0091;
					}
				}
				bool flag = val.IsLocalPlayer;
				goto IL_00ad;
				IL_00ad:
				if (flag)
				{
					list.Add(val);
				}
				continue;
				IL_0084:
				flag = !val.IsLocalPlayer;
				goto IL_00ad;
				IL_0072:
				flag = true;
				goto IL_00ad;
				IL_0091:
				flag = (val.PlayerName ?? "").ToLowerInvariant().Contains(target);
				goto IL_00ad;
			}
			return list;
		}

		private static void FxPursuit(string levelStr, string target)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			List<Player> targets = GetTargets(target);
			if (targets.Count == 0)
			{
				log.Warning("FxPursuit: no players matched target '" + target + "'");
				return;
			}
			EPursuitLevel val = (EPursuitLevel)(levelStr switch
			{
				"investigating" => 1, 
				"nonlethal" => 3, 
				"lethal" => 4, 
				_ => 2, 
			});
			foreach (Player item in targets)
			{
				if (!((Object)(object)item.CrimeData == (Object)null))
				{
					item.CrimeData.SetPursuitLevel(val);
					log.Msg($"Chat FX: set pursuit {val} on {item.PlayerName}.");
				}
			}
		}

		private static void FxStealCash(int cap)
		{
			MoneyManager val = Object.FindObjectOfType<MoneyManager>();
			if ((Object)(object)val == (Object)null)
			{
				log.Warning("FxStealCash: no MoneyManager");
				return;
			}
			float cashBalance = val.cashBalance;
			if (cashBalance <= 0f)
			{
				log.Msg("Chat FX: pickpocket found no cash on hand.");
				return;
			}
			float num = Math.Min(rng.Next(1, cap + 1), cashBalance);
			val.ChangeCashBalance(0f - num, true, false);
			log.Msg($"Chat FX: pickpocketed ${num} cash.");
		}

		private static void FxDrainBank(int cap)
		{
			MoneyManager val = Object.FindObjectOfType<MoneyManager>();
			if ((Object)(object)val == (Object)null)
			{
				log.Warning("FxDrainBank: no MoneyManager");
				return;
			}
			float onlineBalance = val.onlineBalance;
			if (onlineBalance <= 0f)
			{
				log.Msg("Chat FX: hacker found an empty account.");
				return;
			}
			float num = Math.Min(rng.Next(1, cap + 1), onlineBalance);
			val.CreateOnlineTransaction("Hacked!", 0f - num, 1f, "Someone drained your account!");
			log.Msg($"Chat FX: hacker drained ${num} from the bank.");
		}

		private static void FxRemoveDrugs(int count)
		{
			PlayerInventory val = Object.FindObjectOfType<PlayerInventory>();
			if ((Object)(object)val == (Object)null)
			{
				log.Warning("FxRemoveDrugs: no PlayerInventory");
				return;
			}
			List<ItemSlot> allInventorySlots = val.GetAllInventorySlots();
			if (allInventorySlots == null)
			{
				return;
			}
			List<ItemSlot> list = new List<ItemSlot>();
			for (int i = 0; i < allInventorySlots.Count; i++)
			{
				ItemSlot val2 = allInventorySlots[i];
				if (val2 != null)
				{
					ItemInstance itemInstance = val2.ItemInstance;
					if (itemInstance != null && ((Il2CppObjectBase)itemInstance).TryCast<ProductItemInstance>() != null && val2.Quantity > 0)
					{
						list.Add(val2);
					}
				}
			}
			if (list.Count == 0)
			{
				log.Msg("Chat FX: rival gang found no product to steal.");
				return;
			}
			ItemSlot val3 = list[rng.Next(list.Count)];
			int num = Math.Min(count, val3.Quantity);
			val3.ChangeQuantity(-num, false);
			log.Msg($"Chat FX: rival gang stole {num} units of product.");
		}

		private static void FxRaidProperty(string propName, int count)
		{
			List<Property> ownedProperties = Property.OwnedProperties;
			if (ownedProperties == null)
			{
				log.Warning("FxRaidProperty: no owned properties");
				return;
			}
			Property val = null;
			for (int i = 0; i < ownedProperties.Count; i++)
			{
				Property val2 = ownedProperties[i];
				if (!((Object)(object)val2 == (Object)null))
				{
					string text = (val2.PropertyName ?? "").ToLowerInvariant();
					string text2 = (val2.PropertyCode ?? "").ToLowerInvariant();
					if (text.Contains(propName) || text2.Contains(propName))
					{
						val = val2;
						break;
					}
				}
			}
			if ((Object)(object)val == (Object)null)
			{
				log.Warning("FxRaidProperty: no owned property matching '" + propName + "'");
				return;
			}
			List<ItemSlot> list = new List<ItemSlot>();
			List<BuildableItem> buildableItems = val.BuildableItems;
			if (buildableItems != null)
			{
				for (int j = 0; j < buildableItems.Count; j++)
				{
					BuildableItem val3 = buildableItems[j];
					if ((Object)(object)val3 == (Object)null)
					{
						continue;
					}
					PlaceableStorageEntity val4 = ((Il2CppObjectBase)val3).TryCast<PlaceableStorageEntity>();
					if ((Object)(object)val4 == (Object)null)
					{
						continue;
					}
					StorageEntity storageEntity = val4.StorageEntity;
					if ((Object)(object)storageEntity == (Object)null)
					{
						continue;
					}
					List<ItemSlot> itemSlots = storageEntity.ItemSlots;
					if (itemSlots == null)
					{
						continue;
					}
					for (int k = 0; k < itemSlots.Count; k++)
					{
						ItemSlot val5 = itemSlots[k];
						if (val5 != null)
						{
							ItemInstance itemInstance = val5.ItemInstance;
							if (itemInstance != null && ((Il2CppObjectBase)itemInstance).TryCast<ProductItemInstance>() != null && val5.Quantity > 0)
							{
								list.Add(val5);
							}
						}
					}
				}
			}
			if (list.Count == 0)
			{
				log.Msg("Chat FX: raid on '" + val.PropertyName + "' found no product.");
				return;
			}
			int num = count;
			int num2 = 0;
			while (num > 0 && list.Count > 0)
			{
				int index = rng.Next(list.Count);
				ItemSlot val6 = list[index];
				int num3 = Math.Min(num, val6.Quantity);
				val6.ChangeQuantity(-num3, false);
				num -= num3;
				num2 += num3;
				list.RemoveAt(index);
			}
			log.Msg($"Chat FX: rival gang raided '{val.PropertyName}' and stole {num2} product.");
		}

		private static void FxGiveCash(float amount)
		{
			MoneyManager val = Object.FindObjectOfType<MoneyManager>();
			if ((Object)(object)val == (Object)null)
			{
				log.Warning("FxGiveCash: no MoneyManager");
				return;
			}
			val.ChangeCashBalance(amount, true, true);
			log.Msg($"Chat FX: gifted ${amount} cash.");
		}

		private static void FxClearWanted(string target)
		{
			List<Player> targets = GetTargets(target);
			if (targets.Count == 0)
			{
				log.Warning("FxClearWanted: no players matched target '" + target + "'");
				return;
			}
			foreach (Player item in targets)
			{
				if (!((Object)(object)item.CrimeData == (Object)null))
				{
					item.CrimeData.SetPursuitLevel((EPursuitLevel)0);
					item.CrimeData.ClearCrimes();
					log.Msg("Chat FX: cleared wanted on " + item.PlayerName + ".");
				}
			}
		}

		private static void FxGiveDrugs(int count)
		{
			PlayerInventory val = Object.FindObjectOfType<PlayerInventory>();
			if ((Object)(object)val == (Object)null)
			{
				log.Warning("FxGiveDrugs: no PlayerInventory");
				return;
			}
			List<ItemSlot> allInventorySlots = val.GetAllInventorySlots();
			if (allInventorySlots == null)
			{
				return;
			}
			List<ProductItemInstance> list = new List<ProductItemInstance>();
			for (int i = 0; i < allInventorySlots.Count; i++)
			{
				ItemSlot val2 = allInventorySlots[i];
				if (val2 == null)
				{
					continue;
				}
				ItemInstance itemInstance = val2.ItemInstance;
				if (itemInstance != null)
				{
					ProductItemInstance val3 = ((Il2CppObjectBase)itemInstance).TryCast<ProductItemInstance>();
					if (val3 != null && val2.Quantity > 0)
					{
						list.Add(val3);
					}
				}
			}
			if (list.Count == 0)
			{
				log.Msg("Chat FX: gift found no product to copy (hold at least one).");
				return;
			}
			ProductItemInstance val4 = list[rng.Next(list.Count)];
			ItemInstance copy = ((ItemInstance)val4).GetCopy(count);
			val.AddItemToInventory(copy);
			string value = "?";
			try
			{
				value = ((Object)((ItemInstance)val4).Definition).name;
			}
			catch
			{
			}
			log.Msg($"Chat FX: gifted {count}x '{value}' to the player.");
		}

		private static void FxRestockProperty(string propName, int count)
		{
			List<Property> ownedProperties = Property.OwnedProperties;
			if (ownedProperties == null)
			{
				log.Warning("FxRestockProperty: no owned properties");
				return;
			}
			Property val = null;
			for (int i = 0; i < ownedProperties.Count; i++)
			{
				Property val2 = ownedProperties[i];
				if (!((Object)(object)val2 == (Object)null))
				{
					string text = (val2.PropertyName ?? "").ToLowerInvariant();
					string text2 = (val2.PropertyCode ?? "").ToLowerInvariant();
					if (text.Contains(propName) || text2.Contains(propName))
					{
						val = val2;
						break;
					}
				}
			}
			if ((Object)(object)val == (Object)null)
			{
				log.Warning("FxRestockProperty: no owned property matching '" + propName + "'");
				return;
			}
			List<(StorageEntity, ProductItemInstance)> list = new List<(StorageEntity, ProductItemInstance)>();
			List<BuildableItem> buildableItems = val.BuildableItems;
			if (buildableItems != null)
			{
				for (int j = 0; j < buildableItems.Count; j++)
				{
					BuildableItem val3 = buildableItems[j];
					if ((Object)(object)val3 == (Object)null)
					{
						continue;
					}
					PlaceableStorageEntity val4 = ((Il2CppObjectBase)val3).TryCast<PlaceableStorageEntity>();
					if ((Object)(object)val4 == (Object)null)
					{
						continue;
					}
					StorageEntity storageEntity = val4.StorageEntity;
					if ((Object)(object)storageEntity == (Object)null)
					{
						continue;
					}
					List<ItemSlot> itemSlots = storageEntity.ItemSlots;
					if (itemSlots == null)
					{
						continue;
					}
					for (int k = 0; k < itemSlots.Count; k++)
					{
						ItemSlot val5 = itemSlots[k];
						if (val5 == null)
						{
							continue;
						}
						ItemInstance itemInstance = val5.ItemInstance;
						if (itemInstance != null)
						{
							ProductItemInstance val6 = ((Il2CppObjectBase)itemInstance).TryCast<ProductItemInstance>();
							if (val6 != null && val5.Quantity > 0)
							{
								list.Add((storageEntity, val6));
							}
						}
					}
				}
			}
			if (list.Count == 0)
			{
				log.Msg("Chat FX: restock on '" + val.PropertyName + "' found no product to copy.");
				return;
			}
			(StorageEntity, ProductItemInstance) tuple = list[rng.Next(list.Count)];
			int num = StoreInto(tuple.Item1, (ItemInstance)(object)tuple.Item2, count);
			string value = "?";
			try
			{
				value = ((Object)((ItemInstance)tuple.Item2).Definition).name;
			}
			catch
			{
			}
			log.Msg($"Chat FX: restocked '{val.PropertyName}' with {num}x '{value}'" + ((num < count) ? $" (asked for {count}, the storage is full)." : "."));
		}

		private static int StoreInto(StorageEntity storage, ItemInstance item, int quantity)
		{
			int num = quantity;
			List<ItemSlot> itemSlots = storage.ItemSlots;
			if (itemSlots == null)
			{
				return 0;
			}
			for (int i = 0; i < 2; i++)
			{
				if (num <= 0)
				{
					break;
				}
				for (int j = 0; j < itemSlots.Count; j++)
				{
					if (num <= 0)
					{
						break;
					}
					ItemSlot val = itemSlots[j];
					if (val == null)
					{
						continue;
					}
					ItemInstance itemInstance = val.ItemInstance;
					int num2 = ((itemInstance != null) ? val.Quantity : 0);
					bool flag = itemInstance == null || num2 <= 0;
					if (flag != (i == 1) || (!flag && !itemInstance.CanStackWith(item, false)))
					{
						continue;
					}
					int num3;
					try
					{
						num3 = val.GetCapacityForItem(item, true);
					}
					catch
					{
						num3 = 0;
					}
					if (num3 > 0)
					{
						int num4 = Math.Min(num3, num);
						if (flag)
						{
							val.SetStoredItem(item.GetCopy(num4), false);
						}
						else
						{
							val.ChangeQuantity(num4, false);
						}
						int num5 = ((val.ItemInstance != null) ? val.Quantity : 0);
						num -= Math.Max(0, Math.Min(num4, num5 - num2));
					}
				}
			}
			return quantity - num;
		}
	}
}