diff --git a/CringeLauncher/CringeLauncher.csproj b/CringeLauncher/CringeLauncher.csproj index 9fdfac7..b04d0e7 100644 --- a/CringeLauncher/CringeLauncher.csproj +++ b/CringeLauncher/CringeLauncher.csproj @@ -13,11 +13,16 @@ win-x64 https://nuget.storage.yandexcloud.net/index.json + + + + - - - + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/CringeLauncher/Launcher.cs b/CringeLauncher/Launcher.cs index 7875eea..37518ad 100644 --- a/CringeLauncher/Launcher.cs +++ b/CringeLauncher/Launcher.cs @@ -33,15 +33,22 @@ public class Launcher : IDisposable public void Initialize(string[] args) { + // early init for plugin loader + ProtoBuf.Meta.RuntimeTypeModel.Create(true); _harmony.PatchAll(typeof(Launcher).Assembly); + MyPlugins.LoadPlugins([typeof(PluginLoader.Main).Assembly]); + PluginLoader.Main.Instance.Splash?.SetText("Initializing game..."); + PluginLoader.Main.Instance.Splash?.SetBarValue(0); InitTexts(); SpaceEngineersGame.SetupBasicGameInfo(); MyFinalBuildConstants.APP_VERSION = MyPerGameSettings.BasicGameInfo.GameVersion.GetValueOrDefault(); MyShaderCompiler.Init(MyShaderCompiler.TargetPlatform.PC, false); + PluginLoader.Main.Instance.Splash?.SetBarValue(.25f); MyVRageWindows.Init(MyPerGameSettings.BasicGameInfo.ApplicationName, MySandboxGame.Log, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), MyPerGameSettings.BasicGameInfo.ApplicationName), false, false); + PluginLoader.Main.Instance.Splash?.SetBarValue(.35f); MyPlatformGameSettings.SAVE_TO_CLOUD_OPTION_AVAILABLE = true; MyXAudio2.DEVICE_DETAILS_SUPPORTED = false; @@ -56,24 +63,32 @@ public class Launcher : IDisposable MyFakes.VOICE_CHAT_MIC_SENSITIVITY = MySandboxGame.Config.MicSensitivity; MyPlatformGameSettings.VOICE_CHAT_AUTOMATIC_ACTIVATION = MySandboxGame.Config.AutomaticVoiceChatActivation; }); + PluginLoader.Main.Instance.Splash?.SetBarValue(.55f); MyVRage.Platform.Init(); + PluginLoader.Main.Instance.Splash?.SetBarValue(.65f); InitUgc(); + PluginLoader.Main.Instance.Splash?.SetBarValue(.75f); SpaceEngineersGame.SetupPerGameSettings(); + ConfigureSettings(); MySandboxGame.InitMultithreading(); + PluginLoader.Main.Instance.Splash?.SetBarValue(.85f); MyVRage.Platform.System.OnThreadpoolInitialized(); InitRender(); + PluginLoader.Main.Instance.Splash?.SetBarValue(.95f); MyFileSystem.InitUserSpecific(MyGameService.UserId.ToString()); - AccessTools.MethodDelegate>>(AccessTools.Method(typeof(MyPlugins), "LoadPlugins"))(new() - { - typeof(PluginLoader.Main).Assembly - }); _game = new(args); + PluginLoader.Main.Instance.Splash?.SetText("Launching..."); } public void Run() => _game?.Run(); #region Keen shit +private static void ConfigureSettings() +{ + MyPlatformGameSettings.ENABLE_LOGOS = false; +} + private static void InitTexts() { //MyLanguage.Instance.ObtainCurrentOSCulture(); diff --git a/CringeLauncher/packages.lock.json b/CringeLauncher/packages.lock.json index 8f40e31..6b2776f 100644 --- a/CringeLauncher/packages.lock.json +++ b/CringeLauncher/packages.lock.json @@ -2,30 +2,11 @@ "version": 1, "dependencies": { "net8.0-windows10.0.19041": { - "Microsoft.CodeAnalysis.CSharp": { + "Krafs.Publicizer": { "type": "Direct", - "requested": "[4.8.0, )", - "resolved": "4.8.0", - "contentHash": "+3+qfdb/aaGD8PZRCrsdobbzGs1m9u119SkkJt8e/mk3xLJz/udLtS2T6nY27OTXxBBw10HzAbC8Z9w08VyP/g==", - "dependencies": { - "Microsoft.CodeAnalysis.Common": "[4.8.0]" - } - }, - "NLog": { - "type": "Direct", - "requested": "[5.2.8, )", - "resolved": "5.2.8", - "contentHash": "jAIELkWBs1CXFPp986KSGpDFQZHCFccO+LMbKBTTNm42KifaI1mYzFMFQQfuGmGMTrCx0TFPhDjHDE4cLAZWiQ==" - }, - "SpaceEngineersDedicated.ReferenceAssemblies": { - "type": "Direct", - "requested": "[1.204.18, )", - "resolved": "1.204.18", - "contentHash": "GT7/9CBMx4jjor41zLOOl87YYM/JdJD8xp9ccXyuhP2oUaz25H3ZmCQuGeAuZNENKru1a/7hZrId4PwlMDGoew==", - "dependencies": { - "SharpDX": "4.2.0-keen-cringe", - "protobuf-net": "1.0.0" - } + "requested": "[2.2.1, )", + "resolved": "2.2.1", + "contentHash": "QGI4nMGQbKsuFUUboixVHu4mv3lHB5RejIa7toIlzTmwLkuCYYEpUBJjmy3OpXYyj5dVSZAXVbr4oeMSloE67Q==" }, "System.Diagnostics.PerformanceCounter": { "type": "Direct", @@ -69,11 +50,12 @@ "System.Runtime.CompilerServices.Unsafe": "4.5.1" } }, - "Lib.Harmony": { + "Lib.Harmony.Thin": { "type": "Transitive", - "resolved": "2.3.1.1", - "contentHash": "tydjMTa88RB7MjdP6TzYgclwVRv6KqvvsprinCf0xPuHgemj2k0ZMJnC2b8YwwyGr7+sAG3e4P0ii09uwwRBMA==", + "resolved": "2.3.3", + "contentHash": "jsaFv7XnWJnyfyvFbkgIkZtV6tWMteNUcDK3idq+3LwPqpTFNxsOv2eKmj4qqP8QR8UynG1Y9AUaC/+dVruMHg==", "dependencies": { + "MonoMod.Core": "1.1.0", "System.Text.Json": "8.0.1" } }, @@ -98,11 +80,63 @@ "System.Runtime.CompilerServices.Unsafe": "6.0.0" } }, + "Microsoft.CodeAnalysis.CSharp": { + "type": "Transitive", + "resolved": "4.8.0", + "contentHash": "+3+qfdb/aaGD8PZRCrsdobbzGs1m9u119SkkJt8e/mk3xLJz/udLtS2T6nY27OTXxBBw10HzAbC8Z9w08VyP/g==", + "dependencies": { + "Microsoft.CodeAnalysis.Common": "[4.8.0]" + } + }, "Microsoft.Extensions.ObjectPool": { "type": "Transitive", "resolved": "5.0.10", "contentHash": "pp9tbGqIhdEXL6Q1yJl+zevAJSq4BsxqhS1GXzBvEsEz9DDNu9GLNzgUy2xyFc4YjB4m4Ff2YEWTnvQvVYdkvQ==" }, + "Mono.Cecil": { + "type": "Transitive", + "resolved": "0.11.5", + "contentHash": "fxfX+0JGTZ8YQeu1MYjbBiK2CYTSzDyEeIixt+yqKKTn7FW8rv7JMY70qevup4ZJfD7Kk/VG/jDzQQTpfch87g==" + }, + "MonoMod.Backports": { + "type": "Transitive", + "resolved": "1.1.0", + "contentHash": "GUAjCrCZEddqHKHFA7Lh61PgTzoKY7gfBShFe0hQe0p8iynHhBK3TWGyRi+QIw/PGfaRPwx6c33CPGFURBVM6g==", + "dependencies": { + "MonoMod.ILHelpers": "1.0.1" + } + }, + "MonoMod.Core": { + "type": "Transitive", + "resolved": "1.1.0", + "contentHash": "Ks8RntZGVcktr2QF/AovTEbuOkrgXz6omjrvT5LRveOIQJuy+IFuEQPBVWu+cSKVIoZD5XkpRFvlVrItgPIrXw==", + "dependencies": { + "Mono.Cecil": "0.11.5", + "MonoMod.Backports": "1.1.0", + "MonoMod.ILHelpers": "1.0.1", + "MonoMod.Utils": "25.0.4" + } + }, + "MonoMod.ILHelpers": { + "type": "Transitive", + "resolved": "1.0.1", + "contentHash": "6djj/Hz+/eTomo1H/sJEJNxBz2ZdhXjvH0MOmyU2xRtbjaIfBQuyVV0zNUbJhMY/8qoWrz7WXfskfFhdaY0afA==" + }, + "MonoMod.Utils": { + "type": "Transitive", + "resolved": "25.0.4", + "contentHash": "cB94MaZtFD9u4clYEFTwM4jGXnJnzXsxYF3yBpMZKHhXOas66tMF2frbdYte023i0MH4C5iRJbDjxHmA4x5VgA==", + "dependencies": { + "Mono.Cecil": "0.11.5", + "MonoMod.Backports": "1.1.0", + "MonoMod.ILHelpers": "1.0.1" + } + }, + "NLog": { + "type": "Transitive", + "resolved": "5.2.8", + "contentHash": "jAIELkWBs1CXFPp986KSGpDFQZHCFccO+LMbKBTTNm42KifaI1mYzFMFQQfuGmGMTrCx0TFPhDjHDE4cLAZWiQ==" + }, "protobuf-net": { "type": "Transitive", "resolved": "1.0.0", @@ -121,6 +155,15 @@ "System.Runtime.CompilerServices.Unsafe": "4.5.1" } }, + "SpaceEngineersDedicated.ReferenceAssemblies": { + "type": "Transitive", + "resolved": "1.204.18", + "contentHash": "GT7/9CBMx4jjor41zLOOl87YYM/JdJD8xp9ccXyuhP2oUaz25H3ZmCQuGeAuZNENKru1a/7hZrId4PwlMDGoew==", + "dependencies": { + "SharpDX": "4.2.0-keen-cringe", + "protobuf-net": "1.0.0" + } + }, "Steamworks.NET": { "type": "Transitive", "resolved": "20.1.0", @@ -226,7 +269,10 @@ "pluginloader": { "type": "Project", "dependencies": { - "Lib.Harmony": "[2.3.1.1, )", + "Lib.Harmony.Thin": "[2.3.3, )", + "Microsoft.CodeAnalysis.CSharp": "[4.8.0, )", + "NLog": "[5.2.8, )", + "SpaceEngineersDedicated.ReferenceAssemblies": "[1.*, )", "Steamworks.NET": "[20.1.0, )" } } diff --git a/PluginLoader/Compiler/RoslynCompiler.cs b/PluginLoader/Compiler/RoslynCompiler.cs index 78ad4c4..6983acd 100644 --- a/PluginLoader/Compiler/RoslynCompiler.cs +++ b/PluginLoader/Compiler/RoslynCompiler.cs @@ -61,7 +61,7 @@ public class RoslynCompiler { var location = diagnostic.Location; var source = this.source.FirstOrDefault(x => x.Tree == location.SourceTree); - LogFile.WriteLine( + LogFile.Log.Debug( $"{diagnostic.Id}: {diagnostic.GetMessage()} in file:\n{source?.Name ?? "null"} ({location.GetLineSpan().StartLinePosition})"); } diff --git a/PluginLoader/Compiler/RoslynReferences.cs b/PluginLoader/Compiler/RoslynReferences.cs index 1983534..0d8ebfa 100644 --- a/PluginLoader/Compiler/RoslynReferences.cs +++ b/PluginLoader/Compiler/RoslynReferences.cs @@ -35,7 +35,7 @@ public static class RoslynReferences var name = a.GetName(); if (name.Name == harmonyInfo.Name && name.Version != harmonyInfo.Version) { - LogFile.WriteLine( + LogFile.Log.Debug( $"WARNING: Multiple Harmony assemblies are loaded. Plugin Loader is using {harmonyInfo} but found {name}"); continue; } @@ -60,7 +60,7 @@ public static class RoslynReferences // Prevent other Harmony versions from being loaded if (name.Name == harmonyInfo.Name && name.Version != harmonyInfo.Version) { - LogFile.WriteLine( + LogFile.Log.Debug( $"WARNING: Multiple Harmony assemblies are loaded. Plugin Loader is using {harmonyInfo} but found {name}"); continue; } @@ -81,7 +81,7 @@ public static class RoslynReferences sb.Append("Error: ").Append(e).AppendLine(); } - LogFile.WriteLine(sb.ToString(), false); + LogFile.Log.Debug(sb.ToString(), false); } /// @@ -136,14 +136,14 @@ public static class RoslynReferences if (!allReferences.ContainsKey(aName.Name)) { var a = Assembly.Load(aName); - LogFile.WriteLine("Reference added at runtime: " + a.FullName); + LogFile.Log.Debug("Reference added at runtime: " + a.FullName); MetadataReference aRef = MetadataReference.CreateFromFile(a.Location); allReferences[a.GetName().Name] = aRef; } } catch (IOException) { - LogFile.WriteLine("WARNING: Unable to find the assembly '" + name + "'!"); + LogFile.Log.Debug("WARNING: Unable to find the assembly '" + name + "'!"); } } } \ No newline at end of file diff --git a/PluginLoader/Data/GitHubPlugin.cs b/PluginLoader/Data/GitHubPlugin.cs index 1715364..e36f040 100644 --- a/PluginLoader/Data/GitHubPlugin.cs +++ b/PluginLoader/Data/GitHubPlugin.cs @@ -96,7 +96,7 @@ public class GitHubPlugin : PluginData } catch { - LogFile.WriteLine($"Error loading {dllFile}, deleting file"); + LogFile.Log.Debug($"Error loading {dllFile}, deleting file"); File.Delete(dllFile); throw; } diff --git a/PluginLoader/Data/LocalFolderPlugin.cs b/PluginLoader/Data/LocalFolderPlugin.cs index 13bbdb1..3067312 100644 --- a/PluginLoader/Data/LocalFolderPlugin.cs +++ b/PluginLoader/Data/LocalFolderPlugin.cs @@ -58,7 +58,7 @@ public class LocalFolderPlugin : PluginData if (hasFile) { sb.Length -= 2; - LogFile.WriteLine(sb.ToString()); + LogFile.Log.Debug(sb.ToString()); } else { @@ -109,27 +109,11 @@ public class LocalFolderPlugin : PluginData .Where(x => File.Exists(x)); } - var sb = new StringBuilder("An error occurred while checking git for project files.").AppendLine(); - if (!string.IsNullOrWhiteSpace(gitError)) - { - sb.AppendLine("Git output: "); - sb.Append(gitError).AppendLine(); - } - - LogFile.WriteLine(sb.ToString()); + LogFile.Log.Error("An error occurred while checking git for project files. Git output: {GitOutput}", gitError); } catch (Exception e) { - var sb = new StringBuilder("An error occurred while checking git for project files.").AppendLine(); - if (!string.IsNullOrWhiteSpace(gitError)) - { - sb.AppendLine(" Git output: "); - sb.Append(gitError).AppendLine(); - } - - sb.AppendLine("Exception: "); - sb.Append(e).AppendLine(); - LogFile.WriteLine(sb.ToString()); + LogFile.Log.Error(e, "An error occurred while checking git for project files. Git output: {GitOutput}", gitError); } @@ -223,7 +207,7 @@ public class LocalFolderPlugin : PluginData } catch (Exception e) { - LogFile.WriteLine("Error while reading the xml file: " + e); + LogFile.Log.Error(e, "Error while reading the xml file"); } } diff --git a/PluginLoader/Data/LocalPlugin.cs b/PluginLoader/Data/LocalPlugin.cs index 3fb0958..47a1b51 100644 --- a/PluginLoader/Data/LocalPlugin.cs +++ b/PluginLoader/Data/LocalPlugin.cs @@ -46,7 +46,7 @@ public class LocalPlugin : PluginData } catch (IOException) { - LogFile.WriteLine($"Waiting to load {Id} because it's being used by another process"); + LogFile.Log.Debug($"Waiting to load {Id} because it's being used by another process"); Thread.Sleep(250); maxRetries--; } @@ -88,7 +88,7 @@ public class LocalPlugin : PluginData return null; var assembly = Assembly.LoadFile(assemblyPath); - LogFile.WriteLine("Resolving " + assembly.GetName().Name + " for " + args.RequestingAssembly?.FullName, false); + LogFile.Log.Debug("Resolving " + assembly.GetName().Name + " for " + args.RequestingAssembly?.FullName, false); var main = Main.Instance; if (!main.Config.IsEnabled(assemblyPath)) diff --git a/PluginLoader/Data/PluginData.cs b/PluginLoader/Data/PluginData.cs index 246266f..bf87c40 100644 --- a/PluginLoader/Data/PluginData.cs +++ b/PluginLoader/Data/PluginData.cs @@ -91,7 +91,7 @@ public abstract class PluginData : IEquatable if (a == null) { - LogFile.WriteLine("Failed to load " + ToString()); + LogFile.Log.Debug("Failed to load " + ToString()); Error(); return false; } @@ -101,9 +101,9 @@ public abstract class PluginData : IEquatable catch (Exception e) { var name = ToString(); - LogFile.WriteLine($"Failed to load {name} because of an error: " + e); + LogFile.Log.Debug($"Failed to load {name} because of an error: " + e); if (e is MissingMemberException) - LogFile.WriteLine($"Is {name} up to date?"); + LogFile.Log.Debug($"Is {name} up to date?"); if (e is NotSupportedException && e.Message.Contains("loadFromRemoteSources")) Error($"The plugin {name} was blocked by windows. Please unblock the file in the dll file properties."); @@ -168,7 +168,7 @@ public abstract class PluginData : IEquatable Status = PluginStatus.Blocked; LoaderTools.ShowMessageBox($"Unable to load the plugin {this} because it is not whitelisted!", "Plugin Loader", MessageBoxButtons.OK, MessageBoxIcon.Error); - LogFile.WriteLine("Error: " + this + " with an sha256 of " + hash + " is not on the whitelist!"); + LogFile.Log.Debug("Error: " + this + " with an sha256 of " + hash + " is not on the whitelist!"); } public abstract void Show(); diff --git a/PluginLoader/Data/SteamPlugin.cs b/PluginLoader/Data/SteamPlugin.cs index 6cdf2b5..e3572fd 100644 --- a/PluginLoader/Data/SteamPlugin.cs +++ b/PluginLoader/Data/SteamPlugin.cs @@ -57,7 +57,7 @@ public abstract class SteamPlugin : PluginData, ISteamItem { if (Status == PluginStatus.PendingUpdate) { - LogFile.WriteLine("Updating " + this); + LogFile.Log.Debug("Updating " + this); ApplyUpdate(); if (Status == PluginStatus.PendingUpdate) { diff --git a/PluginLoader/GUI/MyGuiScreenPluginConfig.cs b/PluginLoader/GUI/MyGuiScreenPluginConfig.cs index 49f4b3f..2df4de0 100644 --- a/PluginLoader/GUI/MyGuiScreenPluginConfig.cs +++ b/PluginLoader/GUI/MyGuiScreenPluginConfig.cs @@ -122,7 +122,7 @@ public class MyGuiScreenPluginConfig : MyGuiScreenBase private void DownloadStats() { - LogFile.WriteLine("Downloading user statistics", false); + LogFile.Log.Debug("Downloading user statistics", false); Parallel.Start(() => { PluginStats = StatsClient.DownloadStats(); }, OnDownloadedStats); } diff --git a/PluginLoader/GUI/PlayerConsent.cs b/PluginLoader/GUI/PlayerConsent.cs index 7e7eb16..6086712 100644 --- a/PluginLoader/GUI/PlayerConsent.cs +++ b/PluginLoader/GUI/PlayerConsent.cs @@ -71,7 +71,7 @@ public static class PlayerConsent if (!StatsClient.Consent(consent)) { - LogFile.WriteLine("Failed to register player consent on statistics server"); + LogFile.Log.Debug("Failed to register player consent on statistics server"); return; } diff --git a/PluginLoader/GUI/SplashScreen.cs b/PluginLoader/GUI/SplashScreen.cs index b03bebc..472ed49 100644 --- a/PluginLoader/GUI/SplashScreen.cs +++ b/PluginLoader/GUI/SplashScreen.cs @@ -1,10 +1,9 @@ using System.Reflection; -using Sandbox.Game; using VRage; namespace PluginLoader.GUI; -public class SplashScreen : Form +public sealed class SplashScreen : Form { private const float barWidth = 0.98f; // 98% of width private const float barHeight = 0.06f; // 6% of height @@ -18,21 +17,20 @@ public class SplashScreen : Form public SplashScreen() { - Image gif; - if (Application.OpenForms.Count == 0 || !TryLoadImage(out gif)) + CheckForIllegalCrossThreadCalls = false; + if (!TryLoadImage(out var gif)) { invalid = true; return; } - var defaultSplash = Application.OpenForms[0]; - Size = defaultSplash.Size; - ClientSize = defaultSplash.ClientSize; - MyVRage.Platform.Windows.HideSplashScreen(); - Name = "SplashScreenPluginLoader"; TopMost = true; FormBorderStyle = FormBorderStyle.None; + Size = new((int)(gif.Width * 1.65), (int)(gif.Height * 1.25)); + BackColor = Color.Black; + UseWaitCursor = true; + ShowInTaskbar = false; var barSize = new SizeF(Size.Width * barWidth, Size.Height * barHeight); var padding = (1 - barWidth) * Size.Width * 0.5f; @@ -59,15 +57,13 @@ public class SplashScreen : Form Image = gif, Size = Size, AutoSize = false, - SizeMode = PictureBoxSizeMode.StretchImage + SizeMode = PictureBoxSizeMode.CenterImage }; Controls.Add(gifBox); gifBox.Paint += OnPictureBoxDraw; CenterToScreen(); - Show(); - ForceUpdate(); } public object GameInfo { get; private set; } @@ -77,7 +73,7 @@ public class SplashScreen : Form try { var myAssembly = Assembly.GetExecutingAssembly(); - var myStream = myAssembly.GetManifestResourceStream("PluginLoader.splash.gif"); + var myStream = myAssembly.GetManifestResourceStream("PluginLoader.splash.gif")!; img = new Bitmap(myStream); return true; } @@ -95,8 +91,6 @@ public class SplashScreen : Form lbl.Text = msg; barValue = float.NaN; - gifBox.Invalidate(); - ForceUpdate(); } public void SetBarValue(float percent = float.NaN) @@ -105,13 +99,6 @@ public class SplashScreen : Form return; barValue = percent; - gifBox.Invalidate(); - ForceUpdate(); - } - - private void ForceUpdate() - { - Application.DoEvents(); } private void OnPictureBoxDraw(object sender, PaintEventArgs e) @@ -132,7 +119,6 @@ public class SplashScreen : Form gifBox.Paint -= OnPictureBoxDraw; Close(); Dispose(); - ForceUpdate(); - MyVRage.Platform.Windows.ShowSplashScreen(MyPerGameSettings.BasicGameInfo.SplashScreenImage, new(0.7f, 0.7f)); + MyVRage.Platform.Windows.Window.ShowAndFocus(); } } \ No newline at end of file diff --git a/PluginLoader/LoaderTools.cs b/PluginLoader/LoaderTools.cs index 827ed22..72c6611 100644 --- a/PluginLoader/LoaderTools.cs +++ b/PluginLoader/LoaderTools.cs @@ -5,6 +5,7 @@ using System.Security.Cryptography; using System.Text; using Windows.UI.Popups; using HarmonyLib; +using NLog; using PluginLoader.SEPM; using Sandbox; using Sandbox.Game.World; @@ -94,12 +95,12 @@ public static class LoaderTools public static void UnloadAndRestart() { - LogFile.Dispose(); MySessionLoader.Unload(); MySandboxGame.Config.ControllerDefaultOnStart = MyInput.Static.IsJoystickLastUsed; MySandboxGame.Config.Save(); MyScreenManager.CloseAllScreensNowExcept(null); MyPlugins.Unload(); + LogManager.Flush(); Restart(); } @@ -176,7 +177,7 @@ public static class LoaderTools } catch (Exception e) { - LogFile.WriteGameLog("Error while opening file dialog: " + e); + LogFile.Log.Error(e, "Error while opening file dialog"); } } @@ -207,7 +208,7 @@ public static class LoaderTools } catch (Exception e) { - LogFile.WriteGameLog("Error while opening file dialog: " + e); + LogFile.Log.Error(e, "Error while opening file dialog"); } } } \ No newline at end of file diff --git a/PluginLoader/LogFile.cs b/PluginLoader/LogFile.cs index 2cde982..662b0c9 100644 --- a/PluginLoader/LogFile.cs +++ b/PluginLoader/LogFile.cs @@ -1,77 +1,37 @@ -using VRage.Utils; +using System.Runtime.CompilerServices; +using NLog; +using NLog.Layouts; +using NLog.Targets; +using NLog.Targets.Wrappers; namespace PluginLoader; public static class LogFile { - private const string fileName = "loader.log"; - private static StreamWriter writer; + private const string FileName = "loader.log"; + private const string LoggerName = "PluginLoader"; + + public static readonly Logger Log = LogManager.GetLogger(LoggerName); public static void Init(string mainPath) { - var file = Path.Combine(mainPath, fileName); - try + RuntimeHelpers.RunClassConstructor( + Type.GetType("GameAnalyticsSDK.Net.Logging.GALogger, GameAnalytics.Mono", true)!.TypeHandle); + + var target = new AsyncTargetWrapper(new FileTarget { - writer = File.CreateText(file); - } - catch + Name = "pluginLog", + Layout = Layout.FromString("${longdate:universaltime=true} ${level} ${message:withexception=true}"), + FileName = Layout.FromString(Path.Combine(mainPath, FileName)), + FileNameKind = FilePathKind.Absolute, + EnableFileDelete = true, + DeleteOldFileOnStartup = true, + }); + LogManager.Configuration.AddTarget(target); + LogManager.Configuration.LoggingRules.Insert(0, new(LoggerName, LogLevel.Trace, target) { - writer = null; - } - } - - /// - /// Writes the specifed text to the log file. - /// WARNING: Not thread safe! - /// - public static void WriteLine(string text, bool gameLog = true) - { - try - { - writer?.WriteLine($"{DateTime.UtcNow:O} {text}"); - if (gameLog) - WriteGameLog(text); - writer?.Flush(); - } - catch - { - Dispose(); - } - } - - /// - /// Writes the specifed text to the game log file. - /// This function is thread safe. - /// - public static void WriteGameLog(string text) - { - MyLog.Default.WriteLine($"[PluginLoader] {text}"); - } - - public static void WriteTrace(string text, bool gameLog = true) - { -#if DEBUG - writer?.WriteLine($"{DateTime.UtcNow:O} {text}"); - if (gameLog) - WriteGameLog($"[PluginLoader] {text}"); - writer?.Flush(); -#endif - } - - public static void Dispose() - { - if (writer == null) - return; - - try - { - writer.Flush(); - writer.Close(); - } - catch - { - } - - writer = null; + FinalMinLevel = LogLevel.Info + }); + LogManager.ReconfigExistingLoggers(); } } \ No newline at end of file diff --git a/PluginLoader/Main.cs b/PluginLoader/Main.cs index 480d4d0..bf27af7 100644 --- a/PluginLoader/Main.cs +++ b/PluginLoader/Main.cs @@ -24,7 +24,7 @@ public class Main : IHandleInputPlugin { var sw = Stopwatch.StartNew(); - Splash = new(); + RunSplash(); Instance = this; @@ -32,10 +32,9 @@ public class Main : IHandleInputPlugin Cursor.Current = Cursors.AppStarting; var pluginsDir = LoaderTools.PluginsDir; - Directory.CreateDirectory(pluginsDir); - LogFile.Init(pluginsDir); - LogFile.WriteLine("Starting - v" + Assembly.GetExecutingAssembly().GetName().Version.ToString(3)); + LogFile.Init(Directory.CreateDirectory(pluginsDir).FullName); + LogFile.Log.Debug("Starting - v{Version}", Assembly.GetExecutingAssembly().GetName().Version.ToString(3)); // Fix tls 1.2 not supported on Windows 7 - github.com is tls 1.2 only try @@ -44,10 +43,10 @@ public class Main : IHandleInputPlugin } catch (NotSupportedException e) { - LogFile.WriteLine("An error occurred while setting up networking, web requests will probably fail: " + e); + LogFile.Log.Warn(e, "An error occurred while setting up networking, web requests will probably fail"); } - Splash.SetText("Finding references..."); + Splash?.SetText("Finding references..."); RoslynReferences.GenerateAssemblyList(); AppDomain.CurrentDomain.AssemblyResolve += ResolveDependencies; @@ -59,13 +58,13 @@ public class Main : IHandleInputPlugin StatsClient.OverrideBaseUrl(Config.StatsServerBaseUrl); - Splash.SetText("Patching..."); - LogFile.WriteLine("Patching"); + Splash?.SetText("Patching..."); + LogFile.Log.Debug("Patching"); new Harmony("avaness.PluginLoader").PatchAll(Assembly.GetExecutingAssembly()); - Splash.SetText("Instantiating plugins..."); - LogFile.WriteLine("Instantiating plugins"); + Splash?.SetText("Instantiating plugins..."); + LogFile.Log.Debug("Instantiating plugins"); foreach (var id in Config) { var data = List[id]; @@ -84,17 +83,14 @@ public class Main : IHandleInputPlugin // FIXME: It can potentially run in the background speeding up the game's startup //ReportEnabledPlugins(); - LogFile.WriteLine($"Finished startup. Took {sw.ElapsedMilliseconds}ms"); + LogFile.Log.Debug("Finished startup. Took {Time}ms", sw.ElapsedMilliseconds); Cursor.Current = temp; - - Splash.Delete(); - Splash = null; } public PluginList List { get; } public PluginConfig Config { get; } - public SplashScreen Splash { get; } + public SplashScreen? Splash { get; set; } /// /// True if a local plugin was loaded @@ -106,7 +102,7 @@ public class Main : IHandleInputPlugin public void Init(object gameInstance) { - LogFile.WriteLine($"Initializing {plugins.Count} plugins"); + LogFile.Log.Debug("Initializing {PluginsCount} plugins", plugins.Count); for (var i = plugins.Count - 1; i >= 0; i--) { var p = plugins[i]; @@ -146,7 +142,6 @@ public class Main : IHandleInputPlugin plugins.Clear(); AppDomain.CurrentDomain.AssemblyResolve -= ResolveDependencies; - LogFile.Dispose(); Instance = null; } @@ -166,25 +161,47 @@ public class Main : IHandleInputPlugin return false; } + private void RunSplash() + { + var resetEvent = new ManualResetEventSlim(); + var thread = new Thread(() => + { + Application.EnableVisualStyles(); + Application.SetHighDpiMode(HighDpiMode.PerMonitorV2); + Splash = new(); + resetEvent.Set(); + Task.Run(() => + { + Sandbox.MySandboxGame.m_windowCreatedEvent.WaitOne(); + Splash.Invoke(() => Splash.Delete()); + }); + Application.Run(Splash); + }); + + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + resetEvent.Wait(); + } + private void ReportEnabledPlugins() { if (!PlayerConsent.ConsentGiven) return; - Splash.SetText("Reporting plugin usage..."); - LogFile.WriteLine("Reporting plugin usage"); + Splash?.SetText("Reporting plugin usage..."); + LogFile.Log.Debug("Reporting plugin usage"); // Config has already been validated at this point so all enabled plugins will have list items // FIXME: Move into a background thread if (StatsClient.Track(TrackablePluginIds)) - LogFile.WriteLine("List of enabled plugins has been sent to the statistics server"); + LogFile.Log.Debug("List of enabled plugins has been sent to the statistics server"); else - LogFile.WriteLine("Failed to send the list of enabled plugins to the statistics server"); + LogFile.Log.Debug("Failed to send the list of enabled plugins to the statistics server"); } public void RegisterComponents() { - LogFile.WriteLine($"Registering {plugins.Count} components"); + LogFile.Log.Debug("Registering {PluginsCount} components", plugins.Count); foreach (var plugin in plugins) plugin.RegisterSession(MySession.Static); } @@ -193,12 +210,12 @@ public class Main : IHandleInputPlugin { Config.Disable(); plugins.Clear(); - LogFile.WriteLine("Disabled all plugins"); + LogFile.Log.Debug("Disabled all plugins"); } public void InstantiatePlugins() { - LogFile.WriteLine($"Loading {plugins.Count} plugins"); + LogFile.Log.Debug($"Loading {plugins.Count} plugins"); for (var i = plugins.Count - 1; i >= 0; i--) { var p = plugins[i]; @@ -208,27 +225,30 @@ public class Main : IHandleInputPlugin } - private Assembly ResolveDependencies(object sender, ResolveEventArgs args) + private Assembly? ResolveDependencies(object? sender, ResolveEventArgs args) { var assembly = args.RequestingAssembly?.GetName().ToString(); - if (args.Name.Contains("0Harmony")) + var requestedName = new AssemblyName(args.Name); + switch (requestedName.Name) { - if (assembly != null) - LogFile.WriteLine("Resolving 0Harmony for " + assembly); - else - LogFile.WriteLine("Resolving 0Harmony"); - return typeof(Harmony).Assembly; + case "0Harmony": + { + if (assembly != null) + LogFile.Log.Debug("Resolving 0Harmony for {AssemblyName}", assembly); + else + LogFile.Log.Debug("Resolving 0Harmony"); + return typeof(Harmony).Assembly; + } + case "SEPluginManager": + { + if (assembly != null) + LogFile.Log.Debug("Resolving SEPluginManager for {AssemblyName}", assembly); + else + LogFile.Log.Debug("Resolving SEPluginManager"); + return typeof(SEPMPlugin).Assembly; + } + default: + return null; } - - if (args.Name.Contains("SEPluginManager")) - { - if (assembly != null) - LogFile.WriteLine("Resolving SEPluginManager for " + assembly); - else - LogFile.WriteLine("Resolving SEPluginManager"); - return typeof(SEPMPlugin).Assembly; - } - - return null; } } \ No newline at end of file diff --git a/PluginLoader/Network/GitHub.cs b/PluginLoader/Network/GitHub.cs index 3e53473..b6b7442 100644 --- a/PluginLoader/Network/GitHub.cs +++ b/PluginLoader/Network/GitHub.cs @@ -11,38 +11,27 @@ public static class GitHub private const string repoZipUrl = "https://github.com/{0}/archive/{1}.zip"; private const string rawUrl = "https://raw.githubusercontent.com/{0}/{1}/"; - public static Stream DownloadRepo(string name, string commit, out string fileName) + private static readonly HttpClient Client = new(); + + public static Stream DownloadRepo(string name, string commit, out string? fileName) { var uri = new Uri(string.Format(repoZipUrl, name, commit), UriKind.Absolute); - LogFile.WriteLine("Downloading " + uri); - var request = WebRequest.CreateHttp(uri); - request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; - request.Timeout = Main.Instance.Config.NetworkTimeout; + LogFile.Log.Debug("Downloading {Uri}", uri); + using var response = Client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead).Result; - var response = (HttpWebResponse)request.GetResponse(); - fileName = response.Headers["Content-Disposition"]; - if (fileName != null) - { - var index = fileName.IndexOf("filename="); - if (index >= 0) - { - index += "filename=".Length; - fileName = fileName.Substring(index).Trim('"'); - } - } + fileName = response.Content.Headers.ContentDisposition?.FileName; - return response.GetResponseStream(); + using var stream = response.Content.ReadAsStream(); + var mem = new MemoryStream(); + stream.CopyTo(mem); + mem.Position = 0; + return mem; } public static Stream DownloadFile(string name, string commit, string path) { var uri = new Uri(string.Format(rawUrl, name, commit) + path.TrimStart('/'), UriKind.Absolute); - LogFile.WriteLine("Downloading " + uri); - var request = WebRequest.CreateHttp(uri); - request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; - request.Timeout = Main.Instance.Config.NetworkTimeout; - - var response = (HttpWebResponse)request.GetResponse(); - return response.GetResponseStream(); + LogFile.Log.Debug("Downloading {Uri}", uri); + return Client.GetStreamAsync(uri).Result; } } \ No newline at end of file diff --git a/PluginLoader/Patch/Patch_MyDefinitionManager.cs b/PluginLoader/Patch/Patch_MyDefinitionManager.cs index 18a0754..92bc50c 100644 --- a/PluginLoader/Patch/Patch_MyDefinitionManager.cs +++ b/PluginLoader/Patch/Patch_MyDefinitionManager.cs @@ -21,7 +21,7 @@ public static class Patch_MyDefinitionManager var data = list[id]; if (data is ModPlugin mod && !currentMods.Contains(mod.WorkshopId) && mod.Exists) { - LogFile.WriteLine("Loading client mod definitions for " + mod.WorkshopId); + LogFile.Log.Debug("Loading client mod definitions for " + mod.WorkshopId); newMods.Add(mod.GetModItem()); } } @@ -30,7 +30,7 @@ public static class Patch_MyDefinitionManager } catch (Exception e) { - LogFile.WriteLine("An error occured while loading client mods: " + e); + LogFile.Log.Debug("An error occured while loading client mods: " + e); throw; } } diff --git a/PluginLoader/Patch/Patch_MyScriptManager.cs b/PluginLoader/Patch/Patch_MyScriptManager.cs index 4486c09..0b2bfa4 100644 --- a/PluginLoader/Patch/Patch_MyScriptManager.cs +++ b/PluginLoader/Patch/Patch_MyScriptManager.cs @@ -34,14 +34,14 @@ public static class Patch_MyScripManager var data = list[id]; if (data is ModPlugin mod && !currentMods.Contains(mod.WorkshopId) && mod.Exists) { - LogFile.WriteLine("Loading client mod scripts for " + mod.WorkshopId); + LogFile.Log.Debug("Loading client mod scripts for " + mod.WorkshopId); loadScripts(__instance, mod.ModLocation, mod.GetModContext()); } } } catch (Exception e) { - LogFile.WriteLine("An error occured while loading client mods: " + e); + LogFile.Log.Debug("An error occured while loading client mods: " + e); throw; } } diff --git a/PluginLoader/PluginConfig.cs b/PluginLoader/PluginConfig.cs index f0be733..c6ed64d 100644 --- a/PluginLoader/PluginConfig.cs +++ b/PluginLoader/PluginConfig.cs @@ -57,20 +57,6 @@ public class PluginConfig public bool DataHandlingConsent { get; set; } public string DataHandlingConsentDate { get; set; } - public int NetworkTimeout - { - get => networkTimeout; - set - { - if (value < 100) - networkTimeout = 100; - else if (value > 60000) - networkTimeout = 60000; - else - networkTimeout = value; - } - } - public int Count => EnabledPlugins.Count; public void Init(PluginList plugins) @@ -84,7 +70,7 @@ public class PluginConfig { if (!plugins.TryGetPlugin(id, out var plugin)) { - LogFile.WriteLine($"{id} was in the config but is no longer available", false); + LogFile.Log.Debug($"{id} was in the config but is no longer available", false); toRemove.Add(id); } else if (!plugin.IsLocal) @@ -102,13 +88,13 @@ public class PluginConfig sb.Length -= 2; else sb.Append("None"); - LogFile.WriteLine(sb.ToString()); + LogFile.Log.Debug(sb.ToString()); if (localPlugins.Length > 15) localPlugins.Length -= 2; else localPlugins.Append("None"); - LogFile.WriteLine(localPlugins.ToString(), false); + LogFile.Log.Debug(localPlugins.ToString(), false); foreach (var id in toRemove) EnabledPlugins.Remove(id); @@ -127,7 +113,7 @@ public class PluginConfig { try { - LogFile.WriteLine("Saving config"); + LogFile.Log.Debug("Saving config"); var serializer = new XmlSerializer(typeof(PluginConfig)); if (File.Exists(filePath)) File.Delete(filePath); @@ -138,7 +124,7 @@ public class PluginConfig } catch (Exception e) { - LogFile.WriteLine("An error occurred while saving plugin config: " + e); + LogFile.Log.Debug("An error occurred while saving plugin config: " + e); } } @@ -157,7 +143,7 @@ public class PluginConfig } catch (Exception e) { - LogFile.WriteLine("An error occurred while loading plugin config: " + e); + LogFile.Log.Debug("An error occurred while loading plugin config: " + e); } return new() diff --git a/PluginLoader/PluginInstance.cs b/PluginLoader/PluginInstance.cs index b6e7d67..c839feb 100644 --- a/PluginLoader/PluginInstance.cs +++ b/PluginLoader/PluginInstance.cs @@ -46,7 +46,7 @@ public class PluginInstance } catch (Exception e) { - LogFile.WriteLine($"Unable to find OpenConfigDialog() in {data} due to an error: {e}"); + LogFile.Log.Error(e, $"Unable to find OpenConfigDialog() in {data} due to an error"); openConfigDialog = null; } @@ -102,7 +102,7 @@ public class PluginInstance } if (count > 0) - LogFile.WriteLine($"Registered {count} session components from: {mainAssembly.FullName}", !data.IsLocal); + LogFile.Log.Debug($"Registered {count} session components from: {mainAssembly.FullName}", !data.IsLocal); } catch (Exception e) { @@ -140,13 +140,13 @@ public class PluginInstance catch (Exception e) { data.Status = PluginStatus.Error; - LogFile.WriteLine($"Failed to dispose {data} because of an error: {e}"); + LogFile.Log.Error(e, $"Failed to dispose {data} because of an error"); } } private void ThrowError(string error) { - LogFile.WriteLine(error); + LogFile.Log.Debug(error); data.Error(); Dispose(); } @@ -157,10 +157,10 @@ public class PluginInstance if (data.Status == PluginStatus.Error || !data.TryLoadAssembly(out var a)) return false; - var pluginType = a.GetTypes().FirstOrDefault(t => typeof(IPlugin).IsAssignableFrom(t)); + var pluginType = a.GetTypes().FirstOrDefault(t => t.IsAssignableTo(typeof(IPlugin))); if (pluginType == null) { - LogFile.WriteLine($"Failed to load {data} because it does not contain an IPlugin"); + LogFile.Log.Warn($"Failed to load {data} because it does not contain an IPlugin"); data.Error(); return false; } diff --git a/PluginLoader/PluginList.cs b/PluginLoader/PluginList.cs index dd795a7..bb64524 100644 --- a/PluginLoader/PluginList.cs +++ b/PluginLoader/PluginList.cs @@ -1,9 +1,11 @@ using System.Collections; +using System.Diagnostics.CodeAnalysis; using System.IO.Compression; using System.Xml.Serialization; using PluginLoader.Data; using PluginLoader.Network; using ProtoBuf; +using ProtoBuf.Meta; namespace PluginLoader; @@ -20,13 +22,13 @@ public class PluginList : IEnumerable if (plugins.Count == 0) { - LogFile.WriteLine("WARNING: No plugins in the plugin list. Plugin list will contain local plugins only."); + LogFile.Log.Warn("WARNING: No plugins in the plugin list. Plugin list will contain local plugins only."); HasError = true; } FindWorkshopPlugins(config); FindLocalPlugins(config, mainDirectory); - LogFile.WriteLine($"Found {plugins.Count} plugins"); + LogFile.Log.Debug($"Found {plugins.Count} plugins"); FindPluginGroups(); FindModDependencies(); } @@ -92,7 +94,7 @@ public class PluginList : IEnumerable } if (groups > 0) - LogFile.WriteLine($"Found {groups} plugin groups"); + LogFile.Log.Debug($"Found {groups} plugin groups"); } private void FindModDependencies() @@ -164,13 +166,13 @@ public class PluginList : IEnumerable plugins = list.ToDictionary(x => x.Id); } - private bool TryReadWhitelistFile(string file, out PluginData[] list) + private bool TryReadWhitelistFile(string file, [NotNullWhen(true)] out PluginData[]? list) { list = null; if (File.Exists(file) && new FileInfo(file).Length > 0) { - LogFile.WriteLine("Reading whitelist from cache"); + LogFile.Log.Debug("Reading whitelist from cache"); try { using (Stream binFile = File.OpenRead(file)) @@ -178,17 +180,17 @@ public class PluginList : IEnumerable list = Serializer.Deserialize(binFile); } - LogFile.WriteLine("Whitelist retrieved from disk"); + LogFile.Log.Debug("Whitelist retrieved from disk"); return true; } catch (Exception e) { - LogFile.WriteLine("Error while reading whitelist: " + e); + LogFile.Log.Warn(e, "Error while reading whitelist"); } } else { - LogFile.WriteLine("No whitelist cache exists"); + LogFile.Log.Debug("No whitelist cache exists"); } return false; @@ -196,7 +198,6 @@ public class PluginList : IEnumerable private bool TryDownloadWhitelistFile(string file, string hash, PluginConfig config, out PluginData[] list) { - list = null; var newPlugins = new Dictionary(); try @@ -210,19 +211,16 @@ public class PluginList : IEnumerable if (!entry.FullName.EndsWith("xml", StringComparison.OrdinalIgnoreCase)) continue; - using (var entryStream = entry.Open()) - using (var entryReader = new StreamReader(entryStream)) + using var entryStream = entry.Open(); + + try { - try - { - var data = (PluginData)xml.Deserialize(entryReader); - newPlugins[data.Id] = data; - } - catch (InvalidOperationException e) - { - LogFile.WriteLine("An error occurred while reading the plugin xml: " + - (e.InnerException ?? e)); - } + var data = (PluginData?)xml.Deserialize(entryStream) ?? throw new InvalidOperationException($"Deserialized data is null for {entry.FullName}"); + newPlugins[data.Id] = data; + } + catch (InvalidOperationException e) + { + LogFile.Log.Error(e, "An error occurred while reading the plugin xml"); } } } @@ -232,35 +230,30 @@ public class PluginList : IEnumerable } catch (Exception e) { - LogFile.WriteLine("Error while downloading whitelist: " + e); + LogFile.Log.Error(e, "Error while downloading whitelist"); + throw; } - - return false; } private bool TrySaveWhitelist(string file, PluginData[] list, string hash, PluginConfig config) { try { - LogFile.WriteLine("Saving whitelist to disk"); - using (var mem = new MemoryStream()) + LogFile.Log.Debug("Saving whitelist to disk"); + using (var binFile = File.Create(file)) { - Serializer.Serialize(mem, list); - using (Stream binFile = File.Create(file)) - { - mem.WriteTo(binFile); - } + Serializer.Serialize(binFile, list); } config.ListHash = hash; config.Save(); - LogFile.WriteLine("Whitelist updated"); + LogFile.Log.Debug("Whitelist updated"); return true; } catch (Exception e) { - LogFile.WriteLine("Error while saving whitelist: " + e); + LogFile.Log.Error(e, "Error while saving whitelist"); try { File.Delete(file); @@ -289,7 +282,7 @@ public class PluginList : IEnumerable } catch (Exception e) { - LogFile.WriteLine("Error while downloading whitelist hash: " + e); + LogFile.Log.Debug("Error while downloading whitelist hash: " + e); return false; } } @@ -318,7 +311,7 @@ public class PluginList : IEnumerable { var steamPlugins = new List(plugins.Values.Select(x => x as ISteamItem).Where(x => x != null)); - Main.Instance.Splash.SetText("Updating workshop items..."); + Main.Instance.Splash?.SetText("Updating workshop items..."); SteamAPI.Update(steamPlugins.Where(x => config.IsEnabled(x.Id)).Select(x => x.WorkshopId)); @@ -335,12 +328,12 @@ public class PluginList : IEnumerable else if (config.IsEnabled(steam.Id)) { ((PluginData)steam).Status = PluginStatus.Error; - LogFile.WriteLine($"The plugin '{steam}' is missing and cannot be loaded."); + LogFile.Log.Debug($"The plugin '{steam}' is missing and cannot be loaded."); } } catch (Exception e) { - LogFile.WriteLine($"An error occurred while searching for the workshop plugin {steam}: {e}"); + LogFile.Log.Debug($"An error occurred while searching for the workshop plugin {steam}: {e}"); } } diff --git a/PluginLoader/PluginLoader.csproj b/PluginLoader/PluginLoader.csproj index 0eaa475..400dd00 100644 --- a/PluginLoader/PluginLoader.csproj +++ b/PluginLoader/PluginLoader.csproj @@ -8,11 +8,20 @@ true https://nuget.storage.yandexcloud.net/index.json + + + + - - - + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + diff --git a/PluginLoader/Stats/StatsClient.cs b/PluginLoader/Stats/StatsClient.cs index 1e692ae..0c63ee1 100644 --- a/PluginLoader/Stats/StatsClient.cs +++ b/PluginLoader/Stats/StatsClient.cs @@ -34,9 +34,9 @@ public static class StatsClient public static bool Consent(bool consent) { if (consent) - LogFile.WriteLine("Registering player consent on the statistics server"); + LogFile.Log.Debug("Registering player consent on the statistics server"); else - LogFile.WriteLine("Withdrawing player consent, removing user data from the statistics server"); + LogFile.Log.Debug("Withdrawing player consent, removing user data from the statistics server"); var consentRequest = new ConsentRequest { @@ -52,12 +52,12 @@ public static class StatsClient { if (!PlayerConsent.ConsentGiven) { - LogFile.WriteGameLog("Downloading plugin statistics anonymously..."); + LogFile.Log.Info("Downloading plugin statistics anonymously..."); votingToken = null; return SimpleHttpClient.Get(StatsUri); } - LogFile.WriteGameLog("Downloading plugin statistics, ratings and votes for " + PlayerHash); + LogFile.Log.Info("Downloading plugin statistics, ratings and votes for " + PlayerHash); var parameters = new Dictionary { ["playerHash"] = PlayerHash }; var pluginStats = SimpleHttpClient.Get(StatsUri, parameters); @@ -82,11 +82,11 @@ public static class StatsClient { if (votingToken == null) { - LogFile.WriteLine("Voting token is not available, cannot vote"); + LogFile.Log.Debug("Voting token is not available, cannot vote"); return null; } - LogFile.WriteLine($"Voting {vote} on plugin {pluginId}"); + LogFile.Log.Debug($"Voting {vote} on plugin {pluginId}"); var voteRequest = new VoteRequest { PlayerHash = PlayerHash, diff --git a/PluginLoader/SteamAPI.cs b/PluginLoader/SteamAPI.cs index cc7b22d..d6af80a 100644 --- a/PluginLoader/SteamAPI.cs +++ b/PluginLoader/SteamAPI.cs @@ -34,7 +34,7 @@ public static class SteamAPI var modItems = new List( enumerable.Select(x => new MyObjectBuilder_Checkpoint.ModItem(x, "Steam"))); - LogFile.WriteLine($"Updating {modItems.Count} workshop items"); + LogFile.Log.Debug($"Updating {modItems.Count} workshop items"); // Source: MyWorkshop.DownloadWorldModsBlocking var result = new MyWorkshop.ResultData(); @@ -54,11 +54,11 @@ public static class SteamAPI sb.AppendLine("An error occurred while updating workshop items:"); foreach (var e in exceptions) sb.Append(e); - LogFile.WriteLine(sb.ToString()); + LogFile.Log.Debug(sb.ToString()); } else { - LogFile.WriteLine("Unable to update workshop items"); + LogFile.Log.Debug("Unable to update workshop items"); } } } diff --git a/PluginLoader/Tools/SimpleHttpClient.cs b/PluginLoader/Tools/SimpleHttpClient.cs index 9f0c0e7..a563b08 100644 --- a/PluginLoader/Tools/SimpleHttpClient.cs +++ b/PluginLoader/Tools/SimpleHttpClient.cs @@ -25,7 +25,7 @@ public static class SimpleHttpClient } catch (WebException e) { - LogFile.WriteGameLog($"REST API request failed: GET {url} [{e.Message}]"); + LogFile.Log.Info($"REST API request failed: GET {url} [{e.Message}]"); return null; } } @@ -50,7 +50,7 @@ public static class SimpleHttpClient } catch (WebException e) { - LogFile.WriteGameLog($"REST API request failed: GET {uri} [{e.Message}]"); + LogFile.Log.Info($"REST API request failed: GET {uri} [{e.Message}]"); return null; } } @@ -66,7 +66,7 @@ public static class SimpleHttpClient } catch (WebException e) { - LogFile.WriteGameLog($"REST API request failed: POST {url} [{e.Message}]"); + LogFile.Log.Info($"REST API request failed: POST {url} [{e.Message}]"); return null; } } @@ -87,7 +87,7 @@ public static class SimpleHttpClient } catch (WebException e) { - LogFile.WriteGameLog($"REST API request failed: POST {uri} [{e.Message}]"); + LogFile.Log.Info($"REST API request failed: POST {uri} [{e.Message}]"); return null; } } @@ -107,7 +107,7 @@ public static class SimpleHttpClient } catch (WebException e) { - LogFile.WriteGameLog($"REST API request failed: POST {url} [{e.Message}]"); + LogFile.Log.Info($"REST API request failed: POST {url} [{e.Message}]"); return null; } } @@ -126,7 +126,7 @@ public static class SimpleHttpClient } catch (WebException e) { - LogFile.WriteGameLog($"REST API request failed: POST {url} [{e.Message}]"); + LogFile.Log.Info($"REST API request failed: POST {url} [{e.Message}]"); return false; } } diff --git a/PluginLoader/packages.lock.json b/PluginLoader/packages.lock.json index 16d6aab..a14d556 100644 --- a/PluginLoader/packages.lock.json +++ b/PluginLoader/packages.lock.json @@ -2,12 +2,19 @@ "version": 1, "dependencies": { "net8.0-windows10.0.19041": { - "Lib.Harmony": { + "Krafs.Publicizer": { "type": "Direct", - "requested": "[2.3.1.1, )", - "resolved": "2.3.1.1", - "contentHash": "tydjMTa88RB7MjdP6TzYgclwVRv6KqvvsprinCf0xPuHgemj2k0ZMJnC2b8YwwyGr7+sAG3e4P0ii09uwwRBMA==", + "requested": "[2.2.1, )", + "resolved": "2.2.1", + "contentHash": "QGI4nMGQbKsuFUUboixVHu4mv3lHB5RejIa7toIlzTmwLkuCYYEpUBJjmy3OpXYyj5dVSZAXVbr4oeMSloE67Q==" + }, + "Lib.Harmony.Thin": { + "type": "Direct", + "requested": "[2.3.3, )", + "resolved": "2.3.3", + "contentHash": "jsaFv7XnWJnyfyvFbkgIkZtV6tWMteNUcDK3idq+3LwPqpTFNxsOv2eKmj4qqP8QR8UynG1Y9AUaC/+dVruMHg==", "dependencies": { + "MonoMod.Core": "1.1.0", "System.Text.Json": "8.0.1" } }, @@ -20,9 +27,15 @@ "Microsoft.CodeAnalysis.Common": "[4.8.0]" } }, + "NLog": { + "type": "Direct", + "requested": "[5.2.8, )", + "resolved": "5.2.8", + "contentHash": "jAIELkWBs1CXFPp986KSGpDFQZHCFccO+LMbKBTTNm42KifaI1mYzFMFQQfuGmGMTrCx0TFPhDjHDE4cLAZWiQ==" + }, "SpaceEngineersDedicated.ReferenceAssemblies": { "type": "Direct", - "requested": "[1.204.18, )", + "requested": "[1.*, )", "resolved": "1.204.18", "contentHash": "GT7/9CBMx4jjor41zLOOl87YYM/JdJD8xp9ccXyuhP2oUaz25H3ZmCQuGeAuZNENKru1a/7hZrId4PwlMDGoew==", "dependencies": { @@ -52,6 +65,45 @@ "System.Runtime.CompilerServices.Unsafe": "6.0.0" } }, + "Mono.Cecil": { + "type": "Transitive", + "resolved": "0.11.5", + "contentHash": "fxfX+0JGTZ8YQeu1MYjbBiK2CYTSzDyEeIixt+yqKKTn7FW8rv7JMY70qevup4ZJfD7Kk/VG/jDzQQTpfch87g==" + }, + "MonoMod.Backports": { + "type": "Transitive", + "resolved": "1.1.0", + "contentHash": "GUAjCrCZEddqHKHFA7Lh61PgTzoKY7gfBShFe0hQe0p8iynHhBK3TWGyRi+QIw/PGfaRPwx6c33CPGFURBVM6g==", + "dependencies": { + "MonoMod.ILHelpers": "1.0.1" + } + }, + "MonoMod.Core": { + "type": "Transitive", + "resolved": "1.1.0", + "contentHash": "Ks8RntZGVcktr2QF/AovTEbuOkrgXz6omjrvT5LRveOIQJuy+IFuEQPBVWu+cSKVIoZD5XkpRFvlVrItgPIrXw==", + "dependencies": { + "Mono.Cecil": "0.11.5", + "MonoMod.Backports": "1.1.0", + "MonoMod.ILHelpers": "1.0.1", + "MonoMod.Utils": "25.0.4" + } + }, + "MonoMod.ILHelpers": { + "type": "Transitive", + "resolved": "1.0.1", + "contentHash": "6djj/Hz+/eTomo1H/sJEJNxBz2ZdhXjvH0MOmyU2xRtbjaIfBQuyVV0zNUbJhMY/8qoWrz7WXfskfFhdaY0afA==" + }, + "MonoMod.Utils": { + "type": "Transitive", + "resolved": "25.0.4", + "contentHash": "cB94MaZtFD9u4clYEFTwM4jGXnJnzXsxYF3yBpMZKHhXOas66tMF2frbdYte023i0MH4C5iRJbDjxHmA4x5VgA==", + "dependencies": { + "Mono.Cecil": "0.11.5", + "MonoMod.Backports": "1.1.0", + "MonoMod.ILHelpers": "1.0.1" + } + }, "protobuf-net": { "type": "Transitive", "resolved": "1.0.0", diff --git a/PluginLoader/splash.gif b/PluginLoader/splash.gif index 4c66629..ad6fb35 100644 Binary files a/PluginLoader/splash.gif and b/PluginLoader/splash.gif differ