diff --git a/src/Attributes/RegisterInIl2Cpp.cs b/src/Attributes/RegisterInIl2Cpp.cs index 3d854d8..e2b42e3 100644 --- a/src/Attributes/RegisterInIl2Cpp.cs +++ b/src/Attributes/RegisterInIl2Cpp.cs @@ -1,5 +1,4 @@ -using BetterAmongUs.Modules; -using Il2CppInterop.Runtime.Injection; +using Il2CppInterop.Runtime.Injection; using System.Reflection; namespace BetterAmongUs.Attributes; @@ -37,7 +36,7 @@ internal class RegisterInIl2Cpp(params Type[] interfaces) : Attribute } catch (Exception ex) { - Logger_.Error($"Failed to register {type.Name}: {ex.Message}"); + BAUPlugin.Logger.Error($"Failed to register {type.Name}: {ex.Message}"); } } } diff --git a/src/BAUPlugin.Constants.cs b/src/BAUPlugin.Constants.cs index 3cd98a2..7ba00ef 100644 --- a/src/BAUPlugin.Constants.cs +++ b/src/BAUPlugin.Constants.cs @@ -68,6 +68,8 @@ internal partial class BAUPlugin // **Cheat** """; + internal const char ENCRYPTED_LOG_PREFIX = '\u2063'; + internal const char ENCRYPTED_LOG_POSTFIX = '\u2064'; internal const int MAX_CHAT_TEXT = 120; internal const string BAU_CUSTOM_RPC_FLAG = "bau:rpc"; internal const string BAU_MODDED_PROTOCOL_FLAG = "bau:flags"; diff --git a/src/BAUPlugin.cs b/src/BAUPlugin.cs index 87db49c..4cd968a 100644 --- a/src/BAUPlugin.cs +++ b/src/BAUPlugin.cs @@ -70,10 +70,15 @@ internal partial class BAUPlugin : BasePlugin /// internal static Vent[] AllVents => UnityEngine.Object.FindObjectsOfType(); + /// + /// Gets the BAU logger instance. + /// + internal static BAULogger Logger { get; private set; } = null!; + /// /// Gets the BepInEx logger instance. /// - internal static ManualLogSource? Logger; + private static ManualLogSource? _manualLogSource; public override void Load() { @@ -100,7 +105,7 @@ internal partial class BAUPlugin : BasePlugin } catch (Exception ex) { - Logger_.Error(ex); + Logger.Error(ex); } } @@ -125,14 +130,10 @@ internal partial class BAUPlugin : BasePlugin OutfitData.Initialize(); SceneManager.add_sceneLoaded((Action)OnSceneLoaded); - if (File.Exists(BetterDataManager.Files.logFilePath)) - File.WriteAllText(BetterDataManager.Files.previousLogFilePath, File.ReadAllText(BetterDataManager.Files.logFilePath)); - - File.WriteAllText(BetterDataManager.Files.logFilePath, ""); - Logger_.Log("Better Among Us successfully loaded!"); + Logger.Log("Better Among Us successfully loaded!"); string SupportedVersions = string.Join(" ", ModInfo.SupportedAmongUsVersions); - Logger_.Log($"BetterAmongUs {ModInfo.VERSION_STRING}-{ModInfo.BuildDate} - [{AppVersion} --> {SupportedVersions}] {Utils.GetPlatformName(PlatformData.Platform)}"); + Logger.Log($"BetterAmongUs {ModInfo.VERSION_STRING}-{ModInfo.BuildDate} - [{AppVersion} --> {SupportedVersions}] {Utils.GetPlatformName(PlatformData.Platform)}"); } /// @@ -164,13 +165,15 @@ internal partial class BAUPlugin : BasePlugin /// private static void SetupConsole() { + Encryptor.Initialize(); ConsoleManager.CreateConsole(); ConsoleManager.ConfigPreventClose.Value = true; if (ConsoleManager.ConfigConsoleEnabled.Value) ConsoleManager.DetachConsole(); ConsoleManager.ConfigConsoleEnabled.Value = false; ConsoleManager.SetConsoleTitle("Among Us - BAU Console"); - Logger = BepInEx.Logging.Logger.CreateLogSource(ModInfo.PLUGIN_GUID); - var customLogListener = new CustomLogListener(); + _manualLogSource = BepInEx.Logging.Logger.CreateLogSource(ModInfo.PLUGIN_GUID); + Logger = new BAULogger(_manualLogSource); + var customLogListener = new CustomLogListener(Logger); BepInEx.Logging.Logger.Listeners.Add(customLogListener); ConsoleManager.SetConsoleColor(ConsoleColor.Green); ConsoleManager.ConsoleStream.WriteLine($".--------------------------------------------------------------------------------.\r\n| ____ _ _ _ _ _ |\r\n| | __ ) ___| |_| |_ ___ _ __ / \\ _ __ ___ ___ _ __ __ _ | | | |___ |\r\n| | _ \\ / _ \\ __| __/ _ \\ '__| / _ \\ | '_ ` _ \\ / _ \\| '_ \\ / _` | | | | / __||\r\n| | |_) | __/ |_| || __/ | / ___ \\| | | | | | (_) | | | | (_| | | |_| \\__ \\|\r\n| |____/ \\___|\\__|\\__\\___|_| /_/ \\_\\_| |_| |_|\\___/|_| |_|\\__, | \\___/|___/|\r\n| |___/ |\r\n'--------------------------------------------------------------------------------'"); diff --git a/src/Commands/DumpCommand.cs b/src/Commands/DumpCommand.cs index f34c933..d2bd7ad 100644 --- a/src/Commands/DumpCommand.cs +++ b/src/Commands/DumpCommand.cs @@ -22,56 +22,38 @@ internal sealed class DumpCommand : BaseCommand return base.CanRunCommand(out reason); } - private static string DecryptLog(string log) - { - string newLog = string.Empty; - string[] logArray = log.Split([Environment.NewLine], StringSplitOptions.None); - foreach (string text in logArray) - { - if (text.Contains("[PrivateLog]")) - { - newLog += text.Split(':')[0] + ":" + text.Split(':')[1].Replace("[PrivateLog]", "") + ": " + Encryptor.Decrypt(text.Split(':')[2][1..]) + "\n"; - } - else - { - newLog += text + "\n"; - } - } - return newLog; - } - internal override void Run() { - string logFilePath = BetterDataManager.Files.logFilePath; - if (!File.Exists(logFilePath)) + string bepInExLog = Path.Combine(Paths.BepInExRootPath, "LogOutput.log"); + if (!File.Exists(bepInExLog)) { - CommandErrorText("Log file not found!"); + CommandErrorText("BepInEx log file not found!"); return; } if (!BAUPlugin.ModInfo.Starlight) { - string log = File.ReadAllText(logFilePath); - string newLog = DecryptLog(log); - string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); - string logFolderPath = Path.Combine(desktopPath, "BetterLogDumps"); + string logFolderPath = Path.Combine(desktopPath, "BAULogDumps"); + if (!Directory.Exists(logFolderPath)) { Directory.CreateDirectory(logFolderPath); } - string logFileName = "log-" + BAUPlugin.ModInfo.VERSION_STRING + "-" + DateTime.Now.ToString("yyyy.MM.dd-HH.mm.ss") + "-bau" + ".log"; - string logFile = Path.Combine(logFolderPath, logFileName); - File.WriteAllText(logFile, newLog); - string bepInExLog = Path.Combine(Paths.BepInExRootPath, "LogOutput.log"); - if (File.Exists(bepInExLog)) + string log; + using (FileStream fileStream = new(bepInExLog, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + using (StreamReader reader = new(fileStream)) { - string logFileBepInExeName = "log-" + BAUPlugin.ModInfo.VERSION_STRING + "-" + DateTime.Now.ToString("yyyy.MM.dd-HH.mm.ss") + "-bepinex" + ".log"; - string logFileBepInExe = Path.Combine(logFolderPath, logFileBepInExeName); - File.Copy(bepInExLog, logFileBepInExe); + log = reader.ReadToEnd(); } + string decryptedLog = BAULogger.DecryptLogs(log); + + string logFileName = "log-" + BAUPlugin.ModInfo.VERSION_STRING + "-" + DateTime.Now.ToString("yyyy.MM.dd-HH.mm.ss") + "-bepinex" + ".log"; + string logFilePath_New = Path.Combine(logFolderPath, logFileName); + File.WriteAllText(logFilePath_New, decryptedLog); + System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo() { FileName = logFolderPath, @@ -84,27 +66,25 @@ internal sealed class DumpCommand : BaseCommand else { string dataPath = BetterDataManager.Folders.fileFolderPath; - string logFolderPath = Path.Combine(dataPath, "BetterLogDumps"); + string logFolderPath = Path.Combine(dataPath, "BAULogDumps"); if (!Directory.Exists(logFolderPath)) { Directory.CreateDirectory(logFolderPath); } - string androidLogContent = File.ReadAllText(logFilePath); - string androidNewLog = DecryptLog(androidLogContent); - - string androidLogFileName = "log-" + BAUPlugin.ModInfo.VERSION_STRING + "-" + DateTime.Now.ToString("yyyy.MM.dd-HH.mm.ss") + "-bau" + ".log"; - string androidNewLogFilePath = Path.Combine(logFolderPath, androidLogFileName); - File.WriteAllText(androidNewLogFilePath, androidNewLog); - - string bepInExLog = Path.Combine(Paths.BepInExRootPath, "LogOutput.log"); - if (File.Exists(bepInExLog)) + string log; + using (FileStream fileStream = new(bepInExLog, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + using (StreamReader reader = new(fileStream)) { - string logFileBepInExeName = "log-" + BAUPlugin.ModInfo.VERSION_STRING + "-" + DateTime.Now.ToString("yyyy.MM.dd-HH.mm.ss") + "-bepinex" + ".log"; - string logFileBepInExe = Path.Combine(logFolderPath, logFileBepInExeName); - File.Copy(bepInExLog, logFileBepInExe); + log = reader.ReadToEnd(); } + string decryptedLog = BAULogger.DecryptLogs(log); + + string logFileName = "log-" + BAUPlugin.ModInfo.VERSION_STRING + "-" + DateTime.Now.ToString("yyyy.MM.dd-HH.mm.ss") + "-bepinex" + ".log"; + string logFilePath_New = Path.Combine(logFolderPath, logFileName); + File.WriteAllText(logFilePath_New, decryptedLog); + CommandResultText($"Dump logs at '{logFolderPath}'"); } } diff --git a/src/Data/BetterDataManager.cs b/src/Data/BetterDataManager.cs index c31bb7b..702f0aa 100644 --- a/src/Data/BetterDataManager.cs +++ b/src/Data/BetterDataManager.cs @@ -65,12 +65,12 @@ internal static class BetterDataManager /// /// The log file path. /// - internal static readonly string logFilePath = Path.Combine(Folders.fileFolderPath, "better-log.txt"); + internal static readonly string logFilePath_Legacy = Path.Combine(Folders.fileFolderPath, "better-log.txt"); /// /// The previous log file path. /// - internal static readonly string previousLogFilePath = Path.Combine(Folders.fileFolderPath, "better-previous-log.txt"); + internal static readonly string previousLogFilePath_Legacy = Path.Combine(Folders.fileFolderPath, "better-previous-log.txt"); /// /// Legacy data file path (BetterData.json). @@ -204,6 +204,16 @@ internal static class BetterDataManager /// private static void LoadLegacyData() { + if (File.Exists(Files.logFilePath_Legacy)) + { + File.Delete(Files.logFilePath_Legacy); + } + + if (File.Exists(Files.previousLogFilePath_Legacy)) + { + File.Delete(Files.previousLogFilePath_Legacy); + } + if (File.Exists(Files.settingsFilePath_Legacy)) { if (File.Exists(Files.SettingsFilePath)) diff --git a/src/Data/Json/AbstractJsonFile.cs b/src/Data/Json/AbstractJsonFile.cs index f14bcb0..fd40e2b 100644 --- a/src/Data/Json/AbstractJsonFile.cs +++ b/src/Data/Json/AbstractJsonFile.cs @@ -80,7 +80,7 @@ internal abstract class AbstractJsonFile } catch (Exception ex) { - Logger_.Error(ex); + BAUPlugin.Logger.Error(ex); return false; } } @@ -101,7 +101,7 @@ internal abstract class AbstractJsonFile } catch (Exception ex) { - Logger_.Error(ex); + BAUPlugin.Logger.Error(ex); return false; } } diff --git a/src/Data/Json/BetterGameSettingsFile.cs b/src/Data/Json/BetterGameSettingsFile.cs index 856a833..96a9491 100644 --- a/src/Data/Json/BetterGameSettingsFile.cs +++ b/src/Data/Json/BetterGameSettingsFile.cs @@ -62,7 +62,7 @@ internal sealed class BetterGameSettingsFile : AbstractJsonFile } catch (Exception ex) { - Logger_.Error($"Failed to convert JSON element for key {kvp.Key}: {ex.Message}"); + BAUPlugin.Logger.Error($"Failed to convert JSON element for key {kvp.Key}: {ex.Message}"); } } } diff --git a/src/Data/SharedSecretExchange.cs b/src/Data/SharedSecretExchange.cs index a5099bc..cff3e55 100644 --- a/src/Data/SharedSecretExchange.cs +++ b/src/Data/SharedSecretExchange.cs @@ -39,7 +39,7 @@ internal sealed class SharedSecretExchange } catch (Exception ex) { - Logger_.Error("ECDH unavailable, using fallback handshake: " + ex.Message, logConsole: false); + BAUPlugin.Logger.Error("ECDH unavailable, using fallback handshake: " + ex.Message, logConsole: false); cryptoDisabled = true; dh = null; publicKey = []; @@ -129,7 +129,7 @@ internal sealed class SharedSecretExchange } catch (Exception ex) { - Logger_.Error("Error generating shared secret: " + ex.Message, logConsole: false); + BAUPlugin.Logger.Error("Error generating shared secret: " + ex.Message, logConsole: false); return []; } } diff --git a/src/Managers/BetterNotificationManager.cs b/src/Managers/BetterNotificationManager.cs index 33b7f3a..212ea0d 100644 --- a/src/Managers/BetterNotificationManager.cs +++ b/src/Managers/BetterNotificationManager.cs @@ -172,8 +172,8 @@ internal static class BetterNotificationManager Notify(text, time: 8f); } - Logger_.LogCheat($"{player.cosmetics.nameText.text} Info: {player.Data.PlayerName} - {player.Data.FriendCode} - {player.GetHashPuid()}"); - Logger_.LogCheat(Utils.RemoveHtmlText(rawText)); + BAUPlugin.Logger.LogCheat($"{player.cosmetics.nameText.text} Info: {player.Data.PlayerName} - {player.Data.FriendCode} - {player.GetHashPuid()}"); + BAUPlugin.Logger.LogCheat(Utils.RemoveHtmlText(rawText)); if (GameState.IsHost && kickPlayer) { diff --git a/src/Managers/NetworkManager.cs b/src/Managers/NetworkManager.cs index 3a9e9e9..e2dcc0c 100644 --- a/src/Managers/NetworkManager.cs +++ b/src/Managers/NetworkManager.cs @@ -41,7 +41,7 @@ internal static class NetworkManager } catch (Exception ex) { - Logger_.Error(ex, "NetworkManager"); + BAUPlugin.Logger.Error(ex, "NetworkManager"); } finally { @@ -414,7 +414,7 @@ internal static class NetworkManager /// private static void HandleInvalidTag(MessageReader reader) { - Logger_.Warning($"Bad tag {reader.Tag} at {reader.Offset}+{reader.Position}={reader.Length}: " + string.Join(" ", reader.Buffer.Take(128)), "NetworkManager"); + BAUPlugin.Logger.Warning($"Bad tag {reader.Tag} at {reader.Offset}+{reader.Position}={reader.Length}: " + string.Join(" ", reader.Buffer.Take(128)), "NetworkManager"); reader.Recycle(); } @@ -477,7 +477,7 @@ internal static class NetworkManager if (BetterAntiCheat.CheckCancelRPC(player, callId, reader) == false) { - if (!player.IsLocalPlayer()) Logger_.LogCheat($"RPC canceled by Anti-Cheat: {Enum.GetName((RpcCalls)callId)}{Enum.GetName((CustomRPC)callId)} - {callId}"); + if (!player.IsLocalPlayer()) BAUPlugin.Logger.LogCheat($"RPC canceled by Anti-Cheat: {Enum.GetName((RpcCalls)callId)}{Enum.GetName((CustomRPC)callId)} - {callId}"); return false; } diff --git a/src/Modules/AntiCheat/BetterAntiCheat.cs b/src/Modules/AntiCheat/BetterAntiCheat.cs index 374619e..09cf7bf 100644 --- a/src/Modules/AntiCheat/BetterAntiCheat.cs +++ b/src/Modules/AntiCheat/BetterAntiCheat.cs @@ -164,7 +164,7 @@ internal static class BetterAntiCheat { if (BetterNotificationManager.NotifyCheat(player, TranslationStrings.AntiCheat_InvalidHostRPC.Format(Enum.GetName((RpcCalls)callId)))) { - Logger_.LogCheat($"{player.ExtendedData().RealName} {Enum.GetName((RpcCalls)callId)}: {!player.IsHost()}"); + BAUPlugin.Logger.LogCheat($"{player.ExtendedData().RealName} {Enum.GetName((RpcCalls)callId)}: {!player.IsHost()}"); } reader.Recycle(); @@ -183,7 +183,7 @@ internal static class BetterAntiCheat { if (BetterNotificationManager.NotifyCheat(player, TranslationStrings.AntiCheat_InvalidSetRPC.Format(Enum.GetName((RpcCalls)callId)))) { - Logger_.LogCheat($"{player.ExtendedData().RealName} {Enum.GetName((RpcCalls)callId)}: {GameState.IsInGamePlay}"); + BAUPlugin.Logger.LogCheat($"{player.ExtendedData().RealName} {Enum.GetName((RpcCalls)callId)}: {GameState.IsInGamePlay}"); } reader.Recycle(); @@ -223,7 +223,7 @@ internal static class BetterAntiCheat { if (BetterNotificationManager.NotifyCheat(player, TranslationStrings.AntiCheat_InvalidLobbyRPC.Format(Enum.GetName((RpcCalls)callId)))) { - Logger_.LogCheat($"{player.ExtendedData().RealName} {Enum.GetName((RpcCalls)callId)}: {GameState.IsInGame} && {GameState.IsLobby}"); + BAUPlugin.Logger.LogCheat($"{player.ExtendedData().RealName} {Enum.GetName((RpcCalls)callId)}: {GameState.IsInGame} && {GameState.IsLobby}"); } reader.Recycle(); @@ -237,7 +237,7 @@ internal static class BetterAntiCheat } catch (Exception ex) { - Logger_.Error(ex); + BAUPlugin.Logger.Error(ex); return true; } } diff --git a/src/Modules/AntiCheat/RPCHandler.cs b/src/Modules/AntiCheat/RPCHandler.cs index 5fe8644..f62dc01 100644 --- a/src/Modules/AntiCheat/RPCHandler.cs +++ b/src/Modules/AntiCheat/RPCHandler.cs @@ -164,7 +164,7 @@ internal abstract class RPCHandler } catch (Exception ex) { - Logger_.Error(ex); + BAUPlugin.Logger.Error(ex); } } } @@ -181,7 +181,7 @@ internal abstract class RPCHandler { string Name = Enum.GetName((RpcCalls)CallId) ?? Enum.GetName((CustomRPC)CallId) ?? $"Unregistered({CallId})"; Name = $"[{Enum.GetName(catchedHandlerFlag)}] > " + Name; - Logger_.LogCheat($"{catchedSender?.ExtendedData()?.RealName ?? player.ExtendedData()?.RealName ?? string.Empty} {Name}: {info}"); + BAUPlugin.Logger.LogCheat($"{catchedSender?.ExtendedData()?.RealName ?? player.ExtendedData()?.RealName ?? string.Empty} {Name}: {info}"); } /// diff --git a/src/Modules/AntiCheat/RPCHandlers/Cheats/AUMChatHandler.cs b/src/Modules/AntiCheat/RPCHandlers/Cheats/AUMChatHandler.cs index d1c9125..ca09c2f 100644 --- a/src/Modules/AntiCheat/RPCHandlers/Cheats/AUMChatHandler.cs +++ b/src/Modules/AntiCheat/RPCHandlers/Cheats/AUMChatHandler.cs @@ -34,7 +34,7 @@ internal sealed class AUMChatHandler : RPCHandler betterData.AntiCheatInfo.AUMChats.Add(msgString); } - Logger_.Log($"{sender.Data.PlayerName} -> {msgString}", "AUMChatLog"); + BAUPlugin.Logger.Log($"{sender.Data.PlayerName} -> {msgString}", "AUMChatLog"); if (BAUModdedSupportFlags.HasFlag(BAUModdedSupportFlags.Disable_Anticheat)) return; diff --git a/src/Modules/AntiCheat/RPCHandlers/CheckNameHandler.cs b/src/Modules/AntiCheat/RPCHandlers/CheckNameHandler.cs index d6d631b..7dc8206 100644 --- a/src/Modules/AntiCheat/RPCHandlers/CheckNameHandler.cs +++ b/src/Modules/AntiCheat/RPCHandlers/CheckNameHandler.cs @@ -25,7 +25,7 @@ internal sealed class CheckNameHandler : RPCHandler if (BetterNotificationManager.NotifyCheat(sender, GetFormatSetText())) { Utils.AddChatPrivate($"{sender.GetPlayerNameAndColor()} Has tried to change their name to '{name}' but has been undone!"); - Logger_.LogCheat($"{sender.ExtendedData().RealName} Has tried to change their name to '{name}' but has been undone!"); + BAUPlugin.Logger.LogCheat($"{sender.ExtendedData().RealName} Has tried to change their name to '{name}' but has been undone!"); LogRpcInfo($"{sender.DataIsCollected() == true} && {!GameState.IsLocalGame} && {GameState.IsVanillaServer}"); } diff --git a/src/Modules/AntiCheat/RPCHandlers/SetNameHandler.cs b/src/Modules/AntiCheat/RPCHandlers/SetNameHandler.cs index fed8924..d32d295 100644 --- a/src/Modules/AntiCheat/RPCHandlers/SetNameHandler.cs +++ b/src/Modules/AntiCheat/RPCHandlers/SetNameHandler.cs @@ -23,7 +23,7 @@ internal sealed class SetNameHandler : RPCHandler if (BetterNotificationManager.NotifyCheat(sender, GetFormatSetText())) { Utils.AddChatPrivate($"{sender.GetPlayerNameAndColor()} Has tried to change their name to '{name}' but has been undone!"); - Logger_.LogCheat($"{sender.ExtendedData().RealName} Has tried to change their name to '{name}' but has been undone!"); + BAUPlugin.Logger.LogCheat($"{sender.ExtendedData().RealName} Has tried to change their name to '{name}' but has been undone!"); LogRpcInfo($"Player attempted to change name multiple times: '{name}'"); } diff --git a/src/Modules/BAULogger.cs b/src/Modules/BAULogger.cs new file mode 100644 index 0000000..3b180ae --- /dev/null +++ b/src/Modules/BAULogger.cs @@ -0,0 +1,214 @@ +using BepInEx; +using BepInEx.Logging; +using BetterAmongUs.Utilities; + +namespace BetterAmongUs.Modules; + +/// +/// Provides logging for BetterAmongUs with various log levels and destinations. +/// +internal sealed class BAULogger(ManualLogSource manualLogSource) +{ + private readonly ManualLogSource _manualLogSource = manualLogSource; + + /// + /// Logs a message with specified parameters. + /// + /// The message to log. + /// The log tag/category. + /// Whether to output to console. + /// The console color for the message. + /// Whether to log only when the client is host. + internal void Log(string info, string tag = "Log", bool logConsole = true, ConsoleColor color = ConsoleColor.White, bool hostOnly = false) + { + try + { + if (hostOnly && !GameState.IsHost) + return; + + _manualLogSource.LogInfo($"[{tag}] {info}"); + if (logConsole) + { + ConsoleManager.SetConsoleColor(color); + ConsoleManager.ConsoleStream.WriteLine($"{DateTime.Now:HH:mm} BetterAmongUs[{tag}]: {Utils.RemoveHtmlText(info)}"); + } + } + catch { } + } + + /// + /// Logs a header message with visual formatting. + /// + /// The header text. + /// The log tag/category. + /// Whether to log only when the client is host. + /// Whether to output to console. + internal void LogHeader(string info, string tag = "LogHeader", bool hostOnly = false, bool logConsole = true) => Log($" >-------------- {info} --------------<", tag, hostOnly: hostOnly, logConsole: logConsole); + + /// + /// Logs cheat detection messages with green console color. + /// + /// The cheat detection message. + /// The log tag/category. + /// Whether to log only when the client is host. + /// Whether to output to console. + internal void LogCheat(string info, string tag = "AntiCheat", bool hostOnly = false, bool logConsole = true) => Log(info, tag, color: ConsoleColor.Green, hostOnly: hostOnly, logConsole: logConsole); + + /// + /// Logs error messages with red console color. + /// + /// The error message. + /// The log tag/category. + /// Whether to log only when the client is host. + /// Whether to output to console. + internal void Error(string info, string tag = "Error", bool hostOnly = false, bool logConsole = true) => Log(info, tag, color: ConsoleColor.Red, hostOnly: hostOnly, logConsole: logConsole); + + /// + /// Logs exception details with red console color. + /// + /// The exception to log. + /// The log tag/category. + /// Whether to log only when the client is host. + /// Whether to output to console. + internal void Error(Exception ex, string tag = "Error", bool hostOnly = false, bool logConsole = true) => Log(ex.ToString(), tag, color: ConsoleColor.Red, hostOnly: hostOnly, logConsole: logConsole); + + /// + /// Logs warning messages with yellow console color. + /// + /// The warning message. + /// The log tag/category. + /// Whether to log only when the client is host. + /// Whether to output to console. + internal void Warning(string info, string tag = "Warning", bool hostOnly = false, bool logConsole = true) => Log(info, tag, color: ConsoleColor.Yellow, hostOnly: hostOnly, logConsole: logConsole); + + /// + /// Logs a test message for debugging purposes. + /// + internal void Test() + { + Log("------------------> TEST <------------------", "TEST"); + InGame("TEST"); + } + + /// + /// Logs a message in-game via the disconnect message notifier. + /// + /// The message to display in-game. + /// Whether to log only when the client is host. + internal void InGame(string info, bool hostOnly = false) + { + if (hostOnly && !GameState.IsHost) + return; + + if (HudManager.InstanceExists) HudManager.Instance.Notifier.AddDisconnectMessage(info); + Log(info, "InGame", hostOnly: hostOnly); + } + + /// + /// Logs a private message with encryption for sensitive data. + /// + /// The sensitive message to log. + /// The log tag/category. + /// Whether to log only when the client is host. + internal void LogPrivate(string info, string tag = "Log", bool hostOnly = false) + { + try + { + if (hostOnly && !GameState.IsHost) + return; + + string encrypted = Encryptor.Encrypt(info); + Log(BAUPlugin.Constants.ENCRYPTED_LOG_PREFIX + encrypted + BAUPlugin.Constants.ENCRYPTED_LOG_POSTFIX, tag, false); + } + catch { } + } + + /// + /// Decrypts all encrypted sections within a log file text. + /// + /// The raw log file content containing encrypted sections marked with prefix and postfix characters. + /// The log text with all encrypted sections decrypted and markers removed. + internal static string DecryptLogs(string logText) + { + string newLog = string.Empty; + string[] logArray = logText.Split([Environment.NewLine], StringSplitOptions.None); + + foreach (string text in logArray) + { + if (text.Contains(BAUPlugin.Constants.ENCRYPTED_LOG_PREFIX) && + text.Contains(BAUPlugin.Constants.ENCRYPTED_LOG_POSTFIX)) + { + int start = text.IndexOf(BAUPlugin.Constants.ENCRYPTED_LOG_PREFIX); + int end = text.IndexOf(BAUPlugin.Constants.ENCRYPTED_LOG_POSTFIX); + + string before = text[..start]; + string encrypted = text.Substring(start + 1, end - start - 1); + string after = text[(end + 1)..]; + + try + { + string decrypted = Encryptor.Decrypt(encrypted); + newLog += before + decrypted + after + "\n"; + } + catch + { + newLog += text + "\n"; + } + } + else + { + newLog += text + "\n"; + } + } + + return newLog; + } +} + +/// +/// Custom log listener for BepInEx that forwards logs to the BetterAmongUs logging system. +/// +internal class CustomLogListener(BAULogger bauLogger) : ILogListener +{ + private readonly BAULogger _bauLogger = bauLogger; + + /// + /// Gets or sets the log levels to filter. + /// + public LogLevel LogLevelFilter { get; set; } = LogLevel.Info | LogLevel.Warning | LogLevel.Error; + + /// + /// Handles log events from BepInEx. + /// + /// The event sender. + /// The log event arguments. + public void LogEvent(object sender, LogEventArgs eventArgs) + { + if (eventArgs.Source.SourceName.ToLower().Contains("unity") + || eventArgs.Source.SourceName.ToLower().Contains("betteramongus")) + return; + + if (eventArgs.Level is LogLevel.None or LogLevel.Info) + { + _bauLogger.Log(eventArgs.Data.ToString(), "BepInEx." + eventArgs.Source.SourceName, logConsole: false); + } + else if (eventArgs.Level is LogLevel.Warning) + { + _bauLogger.Warning(eventArgs.Data.ToString(), "BepInEx." + eventArgs.Source.SourceName, logConsole: false); + } + else if (eventArgs.Level is LogLevel.Error or LogLevel.Fatal) + { + _bauLogger.Error(eventArgs.Data.ToString(), "BepInEx." + eventArgs.Source.SourceName, logConsole: false); + } + } + + /// + /// Disposes the log listener. + /// + public void Dispose() { } + + /// + /// Flushes the log listener. + /// + public void Flush() { } +} \ No newline at end of file diff --git a/src/Modules/Encryptor.cs b/src/Modules/Encryptor.cs index ea241e9..94d4844 100644 --- a/src/Modules/Encryptor.cs +++ b/src/Modules/Encryptor.cs @@ -1,5 +1,5 @@ using System.Security.Cryptography; -using System.Text; +using UnityEngine; namespace BetterAmongUs.Modules; @@ -8,16 +8,82 @@ namespace BetterAmongUs.Modules; /// internal static class Encryptor { - private static readonly byte[] Key = Encoding.UTF8.GetBytes("0123456789ABCDEF0123456789ABCDEF"); - private static readonly byte[] IV = Encoding.UTF8.GetBytes("ABCDEF0123456789"); + private static byte[] Key = []; + private static byte[] IV = []; + + /// + /// Initializes the encryption system by loading or generating AES keys. + /// + internal static void Initialize() + { + try + { + if (PlayerPrefs.HasKey("BAUEncryptionKey") && PlayerPrefs.HasKey("BAUEncryptionIV")) + { + string keyString = PlayerPrefs.GetString("BAUEncryptionKey"); + string ivString = PlayerPrefs.GetString("BAUEncryptionIV"); + + if (string.IsNullOrEmpty(keyString) || string.IsNullOrEmpty(ivString)) + { + throw new Exception("Keys are empty"); + } + + Key = Convert.FromBase64String(keyString); + IV = Convert.FromBase64String(ivString); + + if (Key.Length != 32 || IV.Length != 16) + { + throw new Exception("Invalid key length"); + } + } + else + { + GenerateAndSaveKeys(); + } + } + catch + { + PlayerPrefs.DeleteKey("BAUEncryptionKey"); + PlayerPrefs.DeleteKey("BAUEncryptionIV"); + PlayerPrefs.Save(); + GenerateAndSaveKeys(); + } + } + + /// + /// Generates a new 256-bit AES key and 128-bit initialization vector (IV), + /// then saves them to PlayerPrefs as Base64 strings. + /// + private static void GenerateAndSaveKeys() + { + using (Aes aes = Aes.Create()) + { + aes.KeySize = 256; + aes.BlockSize = 128; + aes.GenerateKey(); + aes.GenerateIV(); + Key = aes.Key; + IV = aes.IV; + } + + PlayerPrefs.SetString("BAUEncryptionKey", Convert.ToBase64String(Key)); + PlayerPrefs.SetString("BAUEncryptionIV", Convert.ToBase64String(IV)); + PlayerPrefs.Save(); + } /// /// Encrypts a plain text string using AES encryption. /// /// The plain text string to encrypt. /// A base64-encoded string containing the encrypted data. + /// Thrown if encryption is not initialized. internal static string Encrypt(string input) { + if (Key == null || Key.Length == 0 || IV == null || IV.Length == 0) + { + throw new InvalidOperationException("Encryption not initialized. Call InitializeEncryption() first."); + } + using Aes aes = Aes.Create(); aes.Key = Key; aes.IV = IV; @@ -36,8 +102,16 @@ internal static class Encryptor /// /// The base64-encoded encrypted string. /// The decrypted plain text string. + /// Thrown if encryption is not initialized. + /// Thrown if the input is not valid Base64. + /// Thrown if decryption fails due to invalid key or corrupted data. internal static string Decrypt(string input) { + if (Key == null || Key.Length == 0 || IV == null || IV.Length == 0) + { + throw new InvalidOperationException("Encryption not initialized. Call InitializeEncryption() first."); + } + using Aes aes = Aes.Create(); aes.Key = Key; aes.IV = IV; diff --git a/src/Modules/Logger.cs b/src/Modules/Logger.cs deleted file mode 100644 index 5d3c722..0000000 --- a/src/Modules/Logger.cs +++ /dev/null @@ -1,240 +0,0 @@ -using BepInEx; -using BepInEx.Logging; -using BetterAmongUs.Data; -using BetterAmongUs.Utilities; -using System.Diagnostics; -using System.Runtime.CompilerServices; - -namespace BetterAmongUs.Modules; - -/// -/// Provides logging utilities for BetterAmongUs with various log levels and destinations. -/// -internal static class Logger_ -{ - /// - /// Logs a message with specified parameters. - /// - /// The message to log. - /// The log tag/category. - /// Whether to output to console. - /// The console color for the message. - /// Whether to log only when the client is host. - internal static void Log(string info, string tag = "Log", bool logConsole = true, ConsoleColor color = ConsoleColor.White, bool hostOnly = false) - { - try - { - if (hostOnly && !GameState.IsHost) - return; - - string mark = $"{DateTime.Now:HH:mm} [BetterLog][{tag}]"; - string logFilePath = BetterDataManager.Files.logFilePath; - string newLine = $"{mark}: {Utils.RemoveHtmlText(info)}"; - File.AppendAllText(logFilePath, newLine + Environment.NewLine); - BAUPlugin.Logger.LogInfo($"[{tag}] {info}"); - if (logConsole) - { - ConsoleManager.SetConsoleColor(color); - ConsoleManager.ConsoleStream.WriteLine($"{DateTime.Now:HH:mm} BetterAmongUs[{tag}]: {Utils.RemoveHtmlText(info)}"); - } - } - catch { } - } - - /// - /// Logs method calls with detailed information about the caller. - /// - /// Additional information about the method call. - /// The type containing the method (optional). - /// Whether to log only when the client is host. - /// Automatically populated: path of the file containing the caller. - /// Automatically populated: line number of the caller. - /// Automatically populated: name of the calling member. - internal static void LogMethod( - string info = "", - Type? runtimeType = null, - bool hostOnly = false, - [CallerFilePath] string callerFilePath = "", - [CallerLineNumber] int callerLineNumber = 0, - [CallerMemberName] string callerMemberName = "") - { - var loggedMethodFrame = new StackFrame(1, true); - - var loggedMethod = loggedMethodFrame.GetMethod(); - string loggedMethodName = loggedMethod.Name; - string? loggedClassFullName = runtimeType?.FullName ?? loggedMethod.DeclaringType?.FullName; - string? loggedClassName = runtimeType?.Name ?? loggedMethod.DeclaringType?.Name; - - string logMessage = string.IsNullOrEmpty(info) - ? $"{loggedClassFullName}.{loggedMethodName} was called from {Path.GetFileName(callerFilePath)}({callerLineNumber}) in {callerMemberName}." - : $"{loggedClassFullName}.{loggedMethodName} was called from {Path.GetFileName(callerFilePath)}({callerLineNumber}) in {callerMemberName}. Info: {info}."; - - Log(logMessage, "MethodLog", hostOnly); - } - - /// - /// Logs private method calls with detailed information, using encrypted storage. - /// - /// Additional information about the method call. - /// The type containing the method (optional). - /// Whether to log only when the client is host. - /// Automatically populated: path of the file containing the caller. - /// Automatically populated: line number of the caller. - /// Automatically populated: name of the calling member. - internal static void LogMethodPrivate( - string info = "", - Type? runtimeType = null, - bool hostOnly = false, - [CallerFilePath] string callerFilePath = "", - [CallerLineNumber] int callerLineNumber = 0, - [CallerMemberName] string callerMemberName = "") - { - var loggedMethodFrame = new StackFrame(1, true); - - var loggedMethod = loggedMethodFrame.GetMethod(); - string loggedMethodName = loggedMethod.Name; - string? loggedClassFullName = runtimeType?.FullName ?? loggedMethod.DeclaringType?.FullName; - string? loggedClassName = runtimeType?.Name ?? loggedMethod.DeclaringType?.Name; - - string logMessage = string.IsNullOrEmpty(info) - ? $"{loggedClassFullName}.{loggedMethodName} was called from {Path.GetFileName(callerFilePath)}({callerLineNumber}) in {callerMemberName}." - : $"{loggedClassFullName}.{loggedMethodName} was called from {Path.GetFileName(callerFilePath)}({callerLineNumber}) in {callerMemberName}. Info: {info}."; - - LogPrivate(logMessage, "MethodLog", hostOnly); - } - - /// - /// Logs a header message with visual formatting. - /// - /// The header text. - /// The log tag/category. - /// Whether to log only when the client is host. - /// Whether to output to console. - internal static void LogHeader(string info, string tag = "LogHeader", bool hostOnly = false, bool logConsole = true) => Log($" >-------------- {info} --------------<", tag, hostOnly: hostOnly, logConsole: logConsole); - - /// - /// Logs cheat detection messages with green console color. - /// - /// The cheat detection message. - /// The log tag/category. - /// Whether to log only when the client is host. - /// Whether to output to console. - internal static void LogCheat(string info, string tag = "AntiCheat", bool hostOnly = false, bool logConsole = true) => Log(info, tag, color: ConsoleColor.Green, hostOnly: hostOnly, logConsole: logConsole); - - /// - /// Logs error messages with red console color. - /// - /// The error message. - /// The log tag/category. - /// Whether to log only when the client is host. - /// Whether to output to console. - internal static void Error(string info, string tag = "Error", bool hostOnly = false, bool logConsole = true) => Log(info, tag, color: ConsoleColor.Red, hostOnly: hostOnly, logConsole: logConsole); - - /// - /// Logs exception details with red console color. - /// - /// The exception to log. - /// The log tag/category. - /// Whether to log only when the client is host. - /// Whether to output to console. - internal static void Error(Exception ex, string tag = "Error", bool hostOnly = false, bool logConsole = true) => Log(ex.ToString(), tag, color: ConsoleColor.Red, hostOnly: hostOnly, logConsole: logConsole); - - /// - /// Logs warning messages with yellow console color. - /// - /// The warning message. - /// The log tag/category. - /// Whether to log only when the client is host. - /// Whether to output to console. - internal static void Warning(string info, string tag = "Warning", bool hostOnly = false, bool logConsole = true) => Log(info, tag, color: ConsoleColor.Yellow, hostOnly: hostOnly, logConsole: logConsole); - - /// - /// Logs a test message for debugging purposes. - /// - internal static void Test() - { - Log("------------------> TEST <------------------", "TEST"); - InGame("TEST"); - } - - /// - /// Logs a message in-game via the disconnect message notifier. - /// - /// The message to display in-game. - /// Whether to log only when the client is host. - internal static void InGame(string info, bool hostOnly = false) - { - if (hostOnly && !GameState.IsHost) - return; - - if (HudManager.InstanceExists) HudManager.Instance.Notifier.AddDisconnectMessage(info); - Log(info, "InGame", hostOnly: hostOnly); - } - - /// - /// Logs a private message with encryption for sensitive data. - /// - /// The sensitive message to log. - /// The log tag/category. - /// Whether to log only when the client is host. - internal static void LogPrivate(string info, string tag = "Log", bool hostOnly = false) - { - try - { - if (hostOnly && !GameState.IsHost) - return; - - string mark = $"{DateTime.Now:HH:mm} [BetterLog][PrivateLog][{tag}]"; - string logFilePath = BetterDataManager.Files.logFilePath; - string newLine = $"{mark}: " + Encryptor.Encrypt($"{info}"); - File.AppendAllText(logFilePath, newLine + Environment.NewLine); - } - catch { } - } -} - -/// -/// Custom log listener for BepInEx that forwards logs to the BetterAmongUs logging system. -/// -internal class CustomLogListener : ILogListener -{ - /// - /// Gets or sets the log levels to filter. - /// - public LogLevel LogLevelFilter { get; set; } = LogLevel.Info | LogLevel.Warning | LogLevel.Error; - - /// - /// Handles log events from BepInEx. - /// - /// The event sender. - /// The log event arguments. - public void LogEvent(object sender, LogEventArgs eventArgs) - { - if (eventArgs.Source.SourceName.ToLower().Contains("unity") - || eventArgs.Source.SourceName.ToLower().Contains("betteramongus")) - return; - - if (eventArgs.Level is LogLevel.None or LogLevel.Info) - { - Logger_.Log(eventArgs.Data.ToString(), "BepInEx." + eventArgs.Source.SourceName, logConsole: false); - } - else if (eventArgs.Level is LogLevel.Warning) - { - Logger_.Warning(eventArgs.Data.ToString(), "BepInEx." + eventArgs.Source.SourceName, logConsole: false); - } - else if (eventArgs.Level is LogLevel.Error or LogLevel.Fatal) - { - Logger_.Error(eventArgs.Data.ToString(), "BepInEx." + eventArgs.Source.SourceName, logConsole: false); - } - } - - /// - /// Disposes the log listener. - /// - public void Dispose() { } - - /// - /// Flushes the log listener. - /// - public void Flush() { } -} \ No newline at end of file diff --git a/src/Modules/Support/BAUSupportEvent.cs b/src/Modules/Support/BAUSupportEvent.cs index ab9b462..5a09816 100644 --- a/src/Modules/Support/BAUSupportEvent.cs +++ b/src/Modules/Support/BAUSupportEvent.cs @@ -80,7 +80,7 @@ internal abstract class BAUSupportEvent(string attributeFlag) } catch (Exception ex) { - Logger_.Error($"Invoking event '{_attributeFlag}' for {pluginInfo.GetType().Name}: {ex}"); + BAUPlugin.Logger.Error($"Invoking event '{_attributeFlag}' for {pluginInfo.GetType().Name}: {ex}"); return default; } } diff --git a/src/Modules/Translator.cs b/src/Modules/Translator.cs index 063706a..d69ef04 100644 --- a/src/Modules/Translator.cs +++ b/src/Modules/Translator.cs @@ -22,9 +22,9 @@ internal static class Translator /// internal static void Initialize() { - Logger_.Log("Loading language files...", "Translator"); + BAUPlugin.Logger.Log("Loading language files...", "Translator"); LoadLanguages(); - Logger_.Log("Language files loaded successfully", "Translator"); + BAUPlugin.Logger.Log("Language files loaded successfully", "Translator"); } /// @@ -41,7 +41,7 @@ internal static class Translator if (jsonFileNames.Length == 0) { - Logger_.Error("JSON translation files do not exist.", "Translator"); + BAUPlugin.Logger.Error("JSON translation files do not exist.", "Translator"); return; } @@ -54,7 +54,7 @@ internal static class Translator } catch (Exception ex) { - Logger_.Error($"Error loading languages: {ex}", "Translator"); + BAUPlugin.Logger.Error($"Error loading languages: {ex}", "Translator"); } } @@ -89,7 +89,7 @@ internal static class Translator if (jsonDictionary == null) { - Logger_.Error($"Failed to deserialize JSON from {resourceName}", "Translator"); + BAUPlugin.Logger.Error($"Failed to deserialize JSON from {resourceName}", "Translator"); return; } @@ -103,12 +103,12 @@ internal static class Translator } else { - Logger_.Error($"Invalid JSON format in {resourceName}: Missing or invalid 'LanguageID' field.", "Translator"); + BAUPlugin.Logger.Error($"Invalid JSON format in {resourceName}: Missing or invalid 'LanguageID' field.", "Translator"); } } catch (Exception ex) { - Logger_.Error($"Error loading language file {resourceName}: {ex}", "Translator"); + BAUPlugin.Logger.Error($"Error loading language file {resourceName}: {ex}", "Translator"); } } @@ -176,7 +176,7 @@ internal static class Translator } catch (Exception ex) { - Logger_.Error($"Error retrieving string [{translationString}]: {ex}", "Translator"); + BAUPlugin.Logger.Error($"Error retrieving string [{translationString}]: {ex}", "Translator"); return fallbackText; } } diff --git a/src/MonoScripts/BetterPingTracker.cs b/src/MonoScripts/BetterPingTracker.cs index aeace0b..2b8c23c 100644 --- a/src/MonoScripts/BetterPingTracker.cs +++ b/src/MonoScripts/BetterPingTracker.cs @@ -39,7 +39,7 @@ internal sealed class BetterPingTracker : MonoBehaviour if (pingText == null || pingAspectPosition == null) { - Logger_.Error("BetterPingTracker.SetUp() called with null parameters!"); + BAUPlugin.Logger.Error("BetterPingTracker.SetUp() called with null parameters!"); return; } diff --git a/src/MonoScripts/Extended/ExtendedPlayerInfo.cs b/src/MonoScripts/Extended/ExtendedPlayerInfo.cs index a9a55f3..5d33535 100644 --- a/src/MonoScripts/Extended/ExtendedPlayerInfo.cs +++ b/src/MonoScripts/Extended/ExtendedPlayerInfo.cs @@ -29,7 +29,7 @@ internal sealed class ExtendedPlayerInfo : MonoBehaviour, IMonoExtension(<#FFFFFF>{currentVotes}<#6F6F6F>/<#FFFFFF>{maxVotes}<#6F6F6F>)" diff --git a/src/Patches/Gameplay/LobbyPatch.cs b/src/Patches/Gameplay/LobbyPatch.cs index 5d44588..d9b352a 100644 --- a/src/Patches/Gameplay/LobbyPatch.cs +++ b/src/Patches/Gameplay/LobbyPatch.cs @@ -160,6 +160,6 @@ internal static class LobbyPatch [HarmonyPrefix] private static void GameStartManager_FinallyBegin_Prefix(/*GameStartManager __instance*/) { - Logger_.LogHeader($"Game Has Started - {Enum.GetName(typeof(MapNames), GameState.GetActiveMapId)}/{GameState.GetActiveMapId}", "GamePlayManager"); + BAUPlugin.Logger.LogHeader($"Game Has Started - {Enum.GetName(typeof(MapNames), GameState.GetActiveMapId)}/{GameState.GetActiveMapId}", "GamePlayManager"); } } \ No newline at end of file diff --git a/src/Patches/Gameplay/Player/PlayerControlPatch.cs b/src/Patches/Gameplay/Player/PlayerControlPatch.cs index 825489a..74fb2db 100644 --- a/src/Patches/Gameplay/Player/PlayerControlPatch.cs +++ b/src/Patches/Gameplay/Player/PlayerControlPatch.cs @@ -88,7 +88,7 @@ internal static class PlayerControlPatch return; // Log kill event with player names and roles - Logger_.LogPrivate($"{__instance.Data.PlayerName} Has killed {target.Data.PlayerName} as {__instance.Data.RoleType.GetRoleName()}", "EventLog"); + BAUPlugin.Logger.LogPrivate($"{__instance.Data.PlayerName} Has killed {target.Data.PlayerName} as {__instance.Data.RoleType.GetRoleName()}", "EventLog"); // Track kill count in player's BetterData if (resultFlags.HasFlag(MurderResultFlags.Succeeded) || resultFlags.HasFlag(MurderResultFlags.DecisionByHost)) @@ -118,9 +118,9 @@ internal static class PlayerControlPatch // Log shapeshift events (both shifting and unshifting) if (__instance != targetPlayer) - Logger_.LogPrivate($"{__instance.Data.PlayerName} Has Shapeshifted into {targetPlayer.Data.PlayerName}, did animate: {animate}", "EventLog"); + BAUPlugin.Logger.LogPrivate($"{__instance.Data.PlayerName} Has Shapeshifted into {targetPlayer.Data.PlayerName}, did animate: {animate}", "EventLog"); else - Logger_.LogPrivate($"{__instance.Data.PlayerName} Has Un-Shapeshifted, did animate: {animate}", "EventLog"); + BAUPlugin.Logger.LogPrivate($"{__instance.Data.PlayerName} Has Un-Shapeshifted, did animate: {animate}", "EventLog"); } private static IEnumerator CoSetColorEarly(PlayerControl __instance) @@ -135,9 +135,9 @@ internal static class PlayerControlPatch { // Log Phantom role visibility changes if (isActive) - Logger_.LogPrivate($"{__instance.Data.PlayerName} Has Vanished as Phantom, did animate: {shouldAnimate}", "EventLog"); + BAUPlugin.Logger.LogPrivate($"{__instance.Data.PlayerName} Has Vanished as Phantom, did animate: {shouldAnimate}", "EventLog"); else - Logger_.LogPrivate($"{__instance.Data.PlayerName} Has Appeared as Phantom, did animate: {shouldAnimate}", "EventLog"); + BAUPlugin.Logger.LogPrivate($"{__instance.Data.PlayerName} Has Appeared as Phantom, did animate: {shouldAnimate}", "EventLog"); } [HarmonyPatch(typeof(PlayerControl), nameof(PlayerControl.SetName))] @@ -163,7 +163,7 @@ internal static class PlayerControlPatch private static void PlayerPhysics_BootFromVent_Postfix(PlayerPhysics __instance, int ventId) { // Log vent boot events (when engineer boots someone) - Logger_.LogPrivate($"{__instance.myPlayer.Data.PlayerName} Has been booted from vent: {ventId}, as {__instance.myPlayer.Data.RoleType.GetRoleName()}", "EventLog"); + BAUPlugin.Logger.LogPrivate($"{__instance.myPlayer.Data.PlayerName} Has been booted from vent: {ventId}, as {__instance.myPlayer.Data.RoleType.GetRoleName()}", "EventLog"); } [HarmonyPatch(typeof(PlayerPhysics), nameof(PlayerPhysics.CoEnterVent))] @@ -171,7 +171,7 @@ internal static class PlayerControlPatch private static void PlayerPhysics_CoEnterVent_Postfix(PlayerPhysics __instance, int id) { // Log vent entry events - Logger_.LogPrivate($"{__instance.myPlayer.Data.PlayerName} Has entered vent: {id}, as {__instance.myPlayer.Data.RoleType.GetRoleName()}", "EventLog"); + BAUPlugin.Logger.LogPrivate($"{__instance.myPlayer.Data.PlayerName} Has entered vent: {id}, as {__instance.myPlayer.Data.RoleType.GetRoleName()}", "EventLog"); } [HarmonyPatch(typeof(PlayerPhysics), nameof(PlayerPhysics.CoExitVent))] @@ -179,6 +179,6 @@ internal static class PlayerControlPatch private static void PlayerPhysics_CoExitVent_Postfix(PlayerPhysics __instance, int id) { // Log vent exit events - Logger_.LogPrivate($"{__instance.myPlayer.Data.PlayerName} Has exit vent: {id}, as {__instance.myPlayer.Data.RoleType.GetRoleName()}", "EventLog"); + BAUPlugin.Logger.LogPrivate($"{__instance.myPlayer.Data.PlayerName} Has exit vent: {id}, as {__instance.myPlayer.Data.RoleType.GetRoleName()}", "EventLog"); } } \ No newline at end of file diff --git a/src/Patches/Gameplay/Player/PlayerJoinAndLeftPatch.cs b/src/Patches/Gameplay/Player/PlayerJoinAndLeftPatch.cs index f8ed100..f316025 100644 --- a/src/Patches/Gameplay/Player/PlayerJoinAndLeftPatch.cs +++ b/src/Patches/Gameplay/Player/PlayerJoinAndLeftPatch.cs @@ -30,7 +30,7 @@ internal static class PlayerJoinAndLeftPatch host?.SetColor(host.CurrentOutfit.ColorId); } - Logger_.Log($"Successfully joined {GameCode.IntToGameName(AmongUsClient.Instance.GameId)}", "OnGameJoinedPatch"); + BAUPlugin.Logger.Log($"Successfully joined {GameCode.IntToGameName(AmongUsClient.Instance.GameId)}", "OnGameJoinedPatch"); } [HarmonyPatch(typeof(AmongUsClient), nameof(AmongUsClient.OnPlayerJoined))] @@ -153,7 +153,7 @@ internal static class PlayerJoinAndLeftPatch { var ReasonText = $"{playerData.ExtendedData().RealName} {forceReasonText}"; - Logger_.Log(ReasonText); + BAUPlugin.Logger.Log(ReasonText); HudManager.Instance.Notifier.AddDisconnectMessage(ReasonText); } @@ -190,7 +190,7 @@ internal static class PlayerJoinAndLeftPatch break; } - Logger_.Log(ReasonText); + BAUPlugin.Logger.Log(ReasonText); // Add formatted disconnect message to game UI HudManager.Instance.Notifier.AddDisconnectMessage(ReasonText); diff --git a/src/Patches/Gameplay/UI/Chat/ChatPatch.cs b/src/Patches/Gameplay/UI/Chat/ChatPatch.cs index 713a1fa..ddd7dd9 100644 --- a/src/Patches/Gameplay/UI/Chat/ChatPatch.cs +++ b/src/Patches/Gameplay/UI/Chat/ChatPatch.cs @@ -217,7 +217,7 @@ internal static class ChatPatch private static void ChatController_AddChat_Postfix(ChatController __instance, PlayerControl sourcePlayer, string chatText) { // Log chat publicly if player is alive, privately if dead - Logger_.LogPrivate($"{sourcePlayer.Data.PlayerName} -> {chatText}", "ChatLog"); + BAUPlugin.Logger.LogPrivate($"{sourcePlayer.Data.PlayerName} -> {chatText}", "ChatLog"); } [HarmonyPatch(typeof(ChatController), nameof(ChatController.SetChatBubbleName))] diff --git a/src/Patches/Gameplay/UI/GameSummaryPatch.cs b/src/Patches/Gameplay/UI/GameSummaryPatch.cs index b6c258b..09b8874 100644 --- a/src/Patches/Gameplay/UI/GameSummaryPatch.cs +++ b/src/Patches/Gameplay/UI/GameSummaryPatch.cs @@ -35,8 +35,8 @@ internal static class GameSummaryPatch // Log game end info to console private static void LogGameEnd() { - Logger_.LogHeader($"Game Has Ended - {Enum.GetName(typeof(MapNames), GameState.GetActiveMapId)}/{GameState.GetActiveMapId}", "GamePlayManager"); - Logger_.LogHeader("Game Summary Start", "GameSummary"); + BAUPlugin.Logger.LogHeader($"Game Has Ended - {Enum.GetName(typeof(MapNames), GameState.GetActiveMapId)}/{GameState.GetActiveMapId}", "GamePlayManager"); + BAUPlugin.Logger.LogHeader("Game Summary Start", "GameSummary"); } // Creates the visual game summary on screen @@ -52,14 +52,14 @@ internal static class GameSummaryPatch // Get win condition info var (winTeam, winTag, winColor) = GetWinInfo(); - Logger_.Log($"{winTeam}: {winTag}", "GameSummary"); + BAUPlugin.Logger.Log($"{winTeam}: {winTag}", "GameSummary"); // Build and display summary text var summaryHeader = BuildSummaryHeader(winTeam, winTag, winColor); var playerList = BuildPlayerList(); summaryText.text = $"{summaryHeader}\n\n{playerList}"; - Logger_.LogHeader("Game Summary End", "GameSummary"); + BAUPlugin.Logger.LogHeader("Game Summary End", "GameSummary"); } // Creates the text object for the summary @@ -191,7 +191,7 @@ internal static class GameSummaryPatch var playerLine = BuildPlayerLine(playerData); stringBuilder.AppendLine($"- {playerLine}\n"); - Logger_.Log(Utils.RemoveHtmlText(playerLine).Replace("\n", " "), "GameSummary"); + BAUPlugin.Logger.Log(Utils.RemoveHtmlText(playerLine).Replace("\n", " "), "GameSummary"); } return stringBuilder; diff --git a/src/Patches/Gameplay/UI/MeetingHudPatch.cs b/src/Patches/Gameplay/UI/MeetingHudPatch.cs index 60274e3..e5e353e 100644 --- a/src/Patches/Gameplay/UI/MeetingHudPatch.cs +++ b/src/Patches/Gameplay/UI/MeetingHudPatch.cs @@ -54,7 +54,7 @@ internal static class MeetingHudPatch MeetingHud.Instance.ProceedButton.DestroyTextTranslators(); } - Logger_.LogHeader("Meeting Has Started"); + BAUPlugin.Logger.LogHeader("Meeting Has Started"); } // Updates host icon with current host info @@ -134,6 +134,6 @@ internal static class MeetingHudPatch } timeOpen = 0f; - Logger_.LogHeader("Meeting Has Ended"); + BAUPlugin.Logger.LogHeader("Meeting Has Ended"); } } \ No newline at end of file diff --git a/src/Patches/Unity/UnityWebRequestPatch.cs b/src/Patches/Unity/UnityWebRequestPatch.cs index deabc9d..24d7a09 100644 --- a/src/Patches/Unity/UnityWebRequestPatch.cs +++ b/src/Patches/Unity/UnityWebRequestPatch.cs @@ -79,7 +79,7 @@ internal static class UnityWebRequestPatch if (responseHeader != null) { - Logger_.Log("Connected to a supported Better Among Us matchmaking server"); + BAUPlugin.Logger.Log("Connected to a supported Better Among Us matchmaking server"); } })); } diff --git a/src/Utilities/Utils.cs b/src/Utilities/Utils.cs index 759d89a..92fd053 100644 --- a/src/Utilities/Utils.cs +++ b/src/Utilities/Utils.cs @@ -431,7 +431,7 @@ internal static class Utils } catch (Exception ex) { - Logger_.Error(ex); + BAUPlugin.Logger.Error(ex); return null; } } @@ -461,7 +461,7 @@ internal static class Utils } catch (Exception ex) { - Logger_.Error(ex); + BAUPlugin.Logger.Error(ex); return null; } } @@ -475,13 +475,13 @@ internal static class Utils { if (!File.Exists(filePath)) { - Logger_.Error($"File not found: {filePath}"); + BAUPlugin.Logger.Error($"File not found: {filePath}"); return null; } if (Path.GetExtension(filePath).ToLower() != ".wav") { - Logger_.Error("Only .wav files are supported."); + BAUPlugin.Logger.Error("Only .wav files are supported."); return null; } @@ -497,7 +497,7 @@ internal static class Utils } catch (Exception ex) { - Logger_.Error($"Failed to load WAV: {ex}"); + BAUPlugin.Logger.Error($"Failed to load WAV: {ex}"); return null; } }