diff --git a/Novetus/Novetus.Bootstrapper/LocalFuncs.cs b/Novetus/Novetus.Bootstrapper/LocalFuncs.cs index 8d05d5b..abcfe85 100644 --- a/Novetus/Novetus.Bootstrapper/LocalFuncs.cs +++ b/Novetus/Novetus.Bootstrapper/LocalFuncs.cs @@ -1,5 +1,6 @@ #region Usings using NLog; +using Novetus.Core; using System; using System.Diagnostics; using System.IO; diff --git a/Novetus/Novetus.Bootstrapper/LocalPaths.cs b/Novetus/Novetus.Bootstrapper/LocalPaths.cs index 771e596..3005387 100644 --- a/Novetus/Novetus.Bootstrapper/LocalPaths.cs +++ b/Novetus/Novetus.Bootstrapper/LocalPaths.cs @@ -1,4 +1,5 @@ #region Usings +using Novetus.Core; using System.IO; using System.Reflection; #endregion diff --git a/Novetus/Novetus.Bootstrapper/NovetusLaunchForm.cs b/Novetus/Novetus.Bootstrapper/NovetusLaunchForm.cs index 3c8e1bb..13c03be 100644 --- a/Novetus/Novetus.Bootstrapper/NovetusLaunchForm.cs +++ b/Novetus/Novetus.Bootstrapper/NovetusLaunchForm.cs @@ -1,4 +1,5 @@ using NLog; +using Novetus.Core; using System; using System.Drawing; using System.Drawing.Text; diff --git a/Novetus/NovetusCore/CharCustom/CharacterCustomizationShared.cs b/Novetus/NovetusCore/CharCustom/CharacterCustomizationShared.cs index f9680ff..a52f557 100644 --- a/Novetus/NovetusCore/CharCustom/CharacterCustomizationShared.cs +++ b/Novetus/NovetusCore/CharCustom/CharacterCustomizationShared.cs @@ -1,4 +1,5 @@ #region Usings +using Novetus.Core; using System; using System.Collections.Generic; using System.Diagnostics; diff --git a/Novetus/NovetusCore/CharCustom/Forms/Compact/CharacterCustomizationCompact.Designer.cs b/Novetus/NovetusCore/CharCustom/Forms/Compact/CharacterCustomizationCompact.Designer.cs index ad9f23b..4f6685a 100644 --- a/Novetus/NovetusCore/CharCustom/Forms/Compact/CharacterCustomizationCompact.Designer.cs +++ b/Novetus/NovetusCore/CharCustom/Forms/Compact/CharacterCustomizationCompact.Designer.cs @@ -7,6 +7,8 @@ * To change this template use Tools | Options | Coding | Edit Standard Headers. */ +using Novetus.Core; + partial class CharacterCustomizationCompact { /// diff --git a/Novetus/NovetusCore/CharCustom/Forms/Compact/CharacterCustomizationCompact.cs b/Novetus/NovetusCore/CharCustom/Forms/Compact/CharacterCustomizationCompact.cs index 31293c8..5e57cba 100644 --- a/Novetus/NovetusCore/CharCustom/Forms/Compact/CharacterCustomizationCompact.cs +++ b/Novetus/NovetusCore/CharCustom/Forms/Compact/CharacterCustomizationCompact.cs @@ -1,4 +1,5 @@ #region Usings +using Novetus.Core; using System; using System.Collections.Generic; using System.ComponentModel; diff --git a/Novetus/NovetusCore/CharCustom/Forms/Extended/CharacterCustomizationExtended.Designer.cs b/Novetus/NovetusCore/CharCustom/Forms/Extended/CharacterCustomizationExtended.Designer.cs index c34e88f..31e009f 100644 --- a/Novetus/NovetusCore/CharCustom/Forms/Extended/CharacterCustomizationExtended.Designer.cs +++ b/Novetus/NovetusCore/CharCustom/Forms/Extended/CharacterCustomizationExtended.Designer.cs @@ -6,6 +6,8 @@ * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ +using Novetus.Core; + partial class CharacterCustomizationExtended { /// diff --git a/Novetus/NovetusCore/CharCustom/Forms/Extended/CharacterCustomizationExtended.cs b/Novetus/NovetusCore/CharCustom/Forms/Extended/CharacterCustomizationExtended.cs index 0da8827..f802a87 100644 --- a/Novetus/NovetusCore/CharCustom/Forms/Extended/CharacterCustomizationExtended.cs +++ b/Novetus/NovetusCore/CharCustom/Forms/Extended/CharacterCustomizationExtended.cs @@ -1,4 +1,5 @@ #region Usings +using Novetus.Core; using System; using System.Collections.Generic; using System.ComponentModel; diff --git a/Novetus/NovetusCore/Classes/CommandLineArguments.cs b/Novetus/NovetusCore/Classes/CommandLineArguments.cs index d685e98..212b26c 100644 --- a/Novetus/NovetusCore/Classes/CommandLineArguments.cs +++ b/Novetus/NovetusCore/Classes/CommandLineArguments.cs @@ -3,7 +3,9 @@ using System.Collections.Specialized; using System.Text.RegularExpressions; #endregion -#region CommandLineArguments +namespace Novetus.Core +{ + #region CommandLineArguments public class CommandLineArguments { //https://www.codeproject.com/Articles/3111/C-NET-Command-Line-Arguments-Parser @@ -118,3 +120,4 @@ using System.Text.RegularExpressions; } } #endregion +} diff --git a/Novetus/NovetusCore/Classes/CryptoRandom.cs b/Novetus/NovetusCore/Classes/CryptoRandom.cs index ac252f3..2a879f0 100644 --- a/Novetus/NovetusCore/Classes/CryptoRandom.cs +++ b/Novetus/NovetusCore/Classes/CryptoRandom.cs @@ -3,49 +3,52 @@ using System; using System.Security.Cryptography; #endregion -#region CryptoRandom - -public class CryptoRandom : RandomNumberGenerator +namespace Novetus.Core { - private static RandomNumberGenerator r; + #region CryptoRandom - public CryptoRandom() + public class CryptoRandom : RandomNumberGenerator { - r = Create(); - } + private static RandomNumberGenerator r; - ///An array of bytes to contain random numbers. - public override void GetBytes(byte[] buffer) - { - r.GetBytes(buffer); - } + public CryptoRandom() + { + r = Create(); + } - public override void GetNonZeroBytes(byte[] data) - { - r.GetNonZeroBytes(data); - } - public double NextDouble() - { - byte[] b = new byte[4]; - r.GetBytes(b); - return (double)BitConverter.ToUInt32(b, 0) / UInt32.MaxValue; - } + ///An array of bytes to contain random numbers. + public override void GetBytes(byte[] buffer) + { + r.GetBytes(buffer); + } - ///The inclusive lower bound of the random number returned. - ///The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue. - public int Next(int minValue, int maxValue) - { - return (int)Math.Round(NextDouble() * (maxValue - minValue - 1)) + minValue; - } - public int Next() - { - return Next(0, int.MaxValue); - } + public override void GetNonZeroBytes(byte[] data) + { + r.GetNonZeroBytes(data); + } + public double NextDouble() + { + byte[] b = new byte[4]; + r.GetBytes(b); + return (double)BitConverter.ToUInt32(b, 0) / UInt32.MaxValue; + } - ///The inclusive upper bound of the random number returned. maxValue must be greater than or equal 0 - public int Next(int maxValue) - { - return Next(0, maxValue); + ///The inclusive lower bound of the random number returned. + ///The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue. + public int Next(int minValue, int maxValue) + { + return (int)Math.Round(NextDouble() * (maxValue - minValue - 1)) + minValue; + } + public int Next() + { + return Next(0, int.MaxValue); + } + + ///The inclusive upper bound of the random number returned. maxValue must be greater than or equal 0 + public int Next(int maxValue) + { + return Next(0, maxValue); + } } + #endregion } -#endregion diff --git a/Novetus/NovetusCore/Classes/Downloader.cs b/Novetus/NovetusCore/Classes/Downloader.cs index c9f9b44..225e9f0 100644 --- a/Novetus/NovetusCore/Classes/Downloader.cs +++ b/Novetus/NovetusCore/Classes/Downloader.cs @@ -6,245 +6,248 @@ using System.Threading; using System.Windows.Forms; #endregion -#region Downloader - -class Downloader +namespace Novetus.Core { - public readonly string fileURL; - public readonly string fileName; - public readonly string fileFilter; - public readonly string filePath; - public static bool showErrorInfo = true; - public static bool overwrite = true; - public int downloadSize; - private string downloadOutcome; - private static string downloadOutcomeException; + #region Downloader - public Downloader(string url, string name, string filter) + class Downloader { - fileName = name; - fileURL = url; - fileFilter = filter; - } + public readonly string fileURL; + public readonly string fileName; + public readonly string fileFilter; + public readonly string filePath; + public static bool showErrorInfo = true; + public static bool overwrite = true; + public int downloadSize; + private string downloadOutcome; + private static string downloadOutcomeException; - public Downloader(string url, string name, string filter, string path) - { - fileName = name; - fileURL = url; - fileFilter = filter; - filePath = path; - } - - public Downloader(string url, string name) - { - fileName = name; - fileURL = url; - fileFilter = ""; - } - - public void setDownloadOptions(bool ExtraErrorInfo, bool OverwriteFiles) - { - showErrorInfo = ExtraErrorInfo; - overwrite = OverwriteFiles; - } - - public string getDownloadOutcome() - { - return downloadOutcome; - } - - public void InitDownloadDirect(string path, string fileext, string additionalText = "", bool removeSpaces = false) - { - string outputfilename = ""; - - if (removeSpaces == true) + public Downloader(string url, string name, string filter) { - outputfilename = (fileName + fileext).Replace(" ", ""); - } - else - { - outputfilename = fileName + fileext; - } - - string fullpath = path + "\\" + outputfilename; - - InitDownloadNoDialog(fullpath, additionalText); - } - - public void InitDownload(string additionalText = "") - { - SaveFileDialog saveFileDialog1 = new SaveFileDialog - { - FileName = fileName, - //"Compressed zip files (*.zip)|*.zip|All files (*.*)|*.*" - Filter = fileFilter, - Title = "Save " + fileName - }; - - if (saveFileDialog1.ShowDialog() == DialogResult.OK) - { - InitDownloadNoDialog(saveFileDialog1.FileName, additionalText); - } - } - - public void InitDownloadNoDialog(string name, string additionalText = "") - { - if (!overwrite && File.Exists(name)) - { - downloadOutcome = "Download skipped due to same file name."; - return; + fileName = name; + fileURL = url; + fileFilter = filter; } - int read = 0; - - try + public Downloader(string url, string name, string filter, string path) { - read = DownloadFile(fileURL, name); + fileName = name; + fileURL = url; + fileFilter = filter; + filePath = path; } + + public Downloader(string url, string name) + { + fileName = name; + fileURL = url; + fileFilter = ""; + } + + public void setDownloadOptions(bool ExtraErrorInfo, bool OverwriteFiles) + { + showErrorInfo = ExtraErrorInfo; + overwrite = OverwriteFiles; + } + + public string getDownloadOutcome() + { + return downloadOutcome; + } + + public void InitDownloadDirect(string path, string fileext, string additionalText = "", bool removeSpaces = false) + { + string outputfilename = ""; + + if (removeSpaces == true) + { + outputfilename = (fileName + fileext).Replace(" ", ""); + } + else + { + outputfilename = fileName + fileext; + } + + string fullpath = path + "\\" + outputfilename; + + InitDownloadNoDialog(fullpath, additionalText); + } + + public void InitDownload(string additionalText = "") + { + SaveFileDialog saveFileDialog1 = new SaveFileDialog + { + FileName = fileName, + //"Compressed zip files (*.zip)|*.zip|All files (*.*)|*.*" + Filter = fileFilter, + Title = "Save " + fileName + }; + + if (saveFileDialog1.ShowDialog() == DialogResult.OK) + { + InitDownloadNoDialog(saveFileDialog1.FileName, additionalText); + } + } + + public void InitDownloadNoDialog(string name, string additionalText = "") + { + if (!overwrite && File.Exists(name)) + { + downloadOutcome = "Download skipped due to same file name."; + return; + } + + int read = 0; + + try + { + read = DownloadFile(fileURL, name); + } #if URI || LAUNCHER || BASICLAUNCHER - catch (Exception ex) - { - Util.LogExceptions(ex); + catch (Exception ex) + { + Util.LogExceptions(ex); #else catch (Exception) { #endif - downloadOutcome = "Error when downloading file: " + ex.Message; - } - finally - { - //wait a few seconds for the download to finish - //Thread.Sleep(2000); - if (File.Exists(name) && read > 0) - { - downloadSize = read; - downloadOutcome = "File " + Path.GetFileName(name) + " downloaded! " + Util.SizeSuffix(Convert.ToInt64(downloadSize), 2) + " written (" + downloadSize + " bytes)! " + additionalText; + downloadOutcome = "Error when downloading file: " + ex.Message; } - else + finally { - if (!string.IsNullOrWhiteSpace(downloadOutcomeException)) + //wait a few seconds for the download to finish + //Thread.Sleep(2000); + if (File.Exists(name) && read > 0) { - downloadOutcome = "Error: Download of file " + Path.GetFileName(name) + " failed. " + downloadOutcomeException; + downloadSize = read; + downloadOutcome = "File " + Path.GetFileName(name) + " downloaded! " + Util.SizeSuffix(Convert.ToInt64(downloadSize), 2) + " written (" + downloadSize + " bytes)! " + additionalText; } else { - downloadOutcome = "Error: Download of file " + Path.GetFileName(name) + " failed. The file wasn't downloaded to the assigned directory."; - } - - if (showErrorInfo) - { - downloadOutcome += "\n\nMore error info:\n\nFile URL: " + fileURL + "\n\nFile Path: " + name; - } - } - } - } - - public string GetFullDLPath() - { - return filePath + Path.DirectorySeparatorChar + fileName; - } - - private static int DownloadFile(string remoteFilename, string localFilename) - { - //credit to Tom Archer (https://www.codeguru.com/columns/dotnettips/article.php/c7005/Downloading-Files-with-the-WebRequest-and-WebResponse-Classes.htm) - //and Brokenglass (https://stackoverflow.com/questions/4567313/uncompressing-gzip-response-from-webclient/4567408#4567408) - - // Function will return the number of bytes processed - // to the caller. Initialize to 0 here. - int bytesProcessed = 0; - - // Assign values to these objects here so that they can - // be referenced in the finally block - Stream remoteStream = null; - Stream localStream = null; - WebResponse response = null; - - // Use a try/catch/finally block as both the WebRequest and Stream - // classes throw exceptions upon error - //thanks to https://stackoverflow.com/questions/33761919/tls-1-2-in-net-framework-4-0 for the net 4.0 compatible TLS 1.1/1.2 code! - try - { - ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls - | (SecurityProtocolType)3072 - | (SecurityProtocolType)768 - | SecurityProtocolType.Ssl3; - ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true; - // Create a request for the specified remote file name - HttpWebRequest request = (HttpWebRequest)WebRequest.Create(remoteFilename); - //changing it to just "roblox" since roblox is breaking everything. - //request.UserAgent = "Roblox/WinINet"; - request.UserAgent = "Roblox"; - request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); - request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; - if (request != null) - { - // Send the request to the server and retrieve the - // WebResponse object - response = request.GetResponse(); - if (response != null) - { - // Once the WebResponse object has been retrieved, - // get the stream object associated with the response's data - remoteStream = response.GetResponseStream(); - - // Create the local file - localStream = File.Create(localFilename); - - // Allocate a 1k buffer - byte[] buffer = new byte[1024]; - int bytesRead; - - // Simple do/while loop to read from stream until - // no bytes are returned - do + if (!string.IsNullOrWhiteSpace(downloadOutcomeException)) { - // Read data (up to 1k) from the stream - bytesRead = remoteStream.Read(buffer, 0, buffer.Length); + downloadOutcome = "Error: Download of file " + Path.GetFileName(name) + " failed. " + downloadOutcomeException; + } + else + { + downloadOutcome = "Error: Download of file " + Path.GetFileName(name) + " failed. The file wasn't downloaded to the assigned directory."; + } - // Write the data to the local file - localStream.Write(buffer, 0, bytesRead); - - // Increment total bytes processed - bytesProcessed += bytesRead; - } while (bytesRead > 0); + if (showErrorInfo) + { + downloadOutcome += "\n\nMore error info:\n\nFile URL: " + fileURL + "\n\nFile Path: " + name; + } } } } - catch (Exception e) + + public string GetFullDLPath() { -#if URI || LAUNCHER || BASICLAUNCHER - Util.LogExceptions(e); -#endif - if (e is WebException && bytesProcessed == 0) + return filePath + Path.DirectorySeparatorChar + fileName; + } + + private static int DownloadFile(string remoteFilename, string localFilename) + { + //credit to Tom Archer (https://www.codeguru.com/columns/dotnettips/article.php/c7005/Downloading-Files-with-the-WebRequest-and-WebResponse-Classes.htm) + //and Brokenglass (https://stackoverflow.com/questions/4567313/uncompressing-gzip-response-from-webclient/4567408#4567408) + + // Function will return the number of bytes processed + // to the caller. Initialize to 0 here. + int bytesProcessed = 0; + + // Assign values to these objects here so that they can + // be referenced in the finally block + Stream remoteStream = null; + Stream localStream = null; + WebResponse response = null; + + // Use a try/catch/finally block as both the WebRequest and Stream + // classes throw exceptions upon error + //thanks to https://stackoverflow.com/questions/33761919/tls-1-2-in-net-framework-4-0 for the net 4.0 compatible TLS 1.1/1.2 code! + try { - WebException ex = (WebException)e; - HttpWebResponse errorResponse = ex.Response as HttpWebResponse; - if (errorResponse.StatusCode == HttpStatusCode.Conflict || errorResponse.StatusCode == HttpStatusCode.Forbidden) + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls + | (SecurityProtocolType)3072 + | (SecurityProtocolType)768 + | SecurityProtocolType.Ssl3; + ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true; + // Create a request for the specified remote file name + HttpWebRequest request = (HttpWebRequest)WebRequest.Create(remoteFilename); + //changing it to just "roblox" since roblox is breaking everything. + //request.UserAgent = "Roblox/WinINet"; + request.UserAgent = "Roblox"; + request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); + request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; + if (request != null) { - downloadOutcomeException = "Error: Unable to download item. The item may not be publically available."; + // Send the request to the server and retrieve the + // WebResponse object + response = request.GetResponse(); + if (response != null) + { + // Once the WebResponse object has been retrieved, + // get the stream object associated with the response's data + remoteStream = response.GetResponseStream(); + + // Create the local file + localStream = File.Create(localFilename); + + // Allocate a 1k buffer + byte[] buffer = new byte[1024]; + int bytesRead; + + // Simple do/while loop to read from stream until + // no bytes are returned + do + { + // Read data (up to 1k) from the stream + bytesRead = remoteStream.Read(buffer, 0, buffer.Length); + + // Write the data to the local file + localStream.Write(buffer, 0, bytesRead); + + // Increment total bytes processed + bytesProcessed += bytesRead; + } while (bytesRead > 0); + } + } + } + catch (Exception e) + { +#if URI || LAUNCHER || BASICLAUNCHER + Util.LogExceptions(e); +#endif + if (e is WebException && bytesProcessed == 0) + { + WebException ex = (WebException)e; + HttpWebResponse errorResponse = ex.Response as HttpWebResponse; + if (errorResponse.StatusCode == HttpStatusCode.Conflict || errorResponse.StatusCode == HttpStatusCode.Forbidden) + { + downloadOutcomeException = "Error: Unable to download item. The item may not be publically available."; + } + else + { + downloadOutcomeException = "Exception: " + ex.Message; + } } else { - downloadOutcomeException = "Exception: " + ex.Message; + downloadOutcomeException = "Exception: " + e.Message; } } - else + finally { - downloadOutcomeException = "Exception: " + e.Message; + // Close the response and streams objects here + // to make sure they're closed even if an exception + // is thrown at some point + if (response != null) response.Close(); + if (remoteStream != null) remoteStream.Close(); + if (localStream != null) localStream.Close(); } - } - finally - { - // Close the response and streams objects here - // to make sure they're closed even if an exception - // is thrown at some point - if (response != null) response.Close(); - if (remoteStream != null) remoteStream.Close(); - if (localStream != null) localStream.Close(); - } - // Return total bytes processed to caller. - return bytesProcessed; + // Return total bytes processed to caller. + return bytesProcessed; + } } + #endregion } -#endregion diff --git a/Novetus/NovetusCore/Classes/IDiscordRPC.cs b/Novetus/NovetusCore/Classes/IDiscordRPC.cs index 0899dc9..afda33f 100644 --- a/Novetus/NovetusCore/Classes/IDiscordRPC.cs +++ b/Novetus/NovetusCore/Classes/IDiscordRPC.cs @@ -2,95 +2,98 @@ using System.Runtime.InteropServices; #endregion -#region Discord RPC -//code by discord obv. just renamed it to fit better. -public class DiscordRPC +namespace Novetus.Core { - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public delegate void ReadyCallback(); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public delegate void DisconnectedCallback(int errorCode, string message); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public delegate void ErrorCallback(int errorCode, string message); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public delegate void JoinCallback(string secret); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public delegate void SpectateCallback(string secret); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public delegate void RequestCallback(JoinRequest request); - - public struct EventHandlers + #region Discord RPC + //code by discord obv. just renamed it to fit better. + public class DiscordRPC { - public ReadyCallback readyCallback; - public DisconnectedCallback disconnectedCallback; - public ErrorCallback errorCallback; - public JoinCallback joinCallback; - public SpectateCallback spectateCallback; - public RequestCallback requestCallback; + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void ReadyCallback(); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void DisconnectedCallback(int errorCode, string message); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void ErrorCallback(int errorCode, string message); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void JoinCallback(string secret); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void SpectateCallback(string secret); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void RequestCallback(JoinRequest request); + + public struct EventHandlers + { + public ReadyCallback readyCallback; + public DisconnectedCallback disconnectedCallback; + public ErrorCallback errorCallback; + public JoinCallback joinCallback; + public SpectateCallback spectateCallback; + public RequestCallback requestCallback; + } + + [System.Serializable] + public struct RichPresence + { + public string state; + /* max 128 bytes */ + public string details; + /* max 128 bytes */ + public long startTimestamp; + public long endTimestamp; + public string largeImageKey; + /* max 32 bytes */ + public string largeImageText; + /* max 128 bytes */ + public string smallImageKey; + /* max 32 bytes */ + public string smallImageText; + /* max 128 bytes */ + public string partyId; + /* max 128 bytes */ + public int partySize; + public int partyMax; + public string matchSecret; + /* max 128 bytes */ + public string joinSecret; + /* max 128 bytes */ + public string spectateSecret; + /* max 128 bytes */ + public bool instance; + } + + [System.Serializable] + public struct JoinRequest + { + public string userId; + public string username; + public string avatar; + } + + public enum Reply + { + No = 0, + Yes = 1, + Ignore = 2 + } + [DllImport("discord-rpc", EntryPoint = "Discord_Initialize", CallingConvention = CallingConvention.Cdecl)] + public static extern void Initialize(string applicationId, ref EventHandlers handlers, bool autoRegister, string optionalSteamId); + + [DllImport("discord-rpc", EntryPoint = "Discord_Shutdown", CallingConvention = CallingConvention.Cdecl)] + public static extern void Shutdown(); + + [DllImport("discord-rpc", EntryPoint = "Discord_RunCallbacks", CallingConvention = CallingConvention.Cdecl)] + public static extern void RunCallbacks(); + + [DllImport("discord-rpc", EntryPoint = "Discord_UpdatePresence", CallingConvention = CallingConvention.Cdecl)] + public static extern void UpdatePresence(ref RichPresence presence); + + [DllImport("discord-rpc", EntryPoint = "Discord_Respond", CallingConvention = CallingConvention.Cdecl)] + public static extern void Respond(string userId, Reply reply); } - - [System.Serializable] - public struct RichPresence - { - public string state; - /* max 128 bytes */ - public string details; - /* max 128 bytes */ - public long startTimestamp; - public long endTimestamp; - public string largeImageKey; - /* max 32 bytes */ - public string largeImageText; - /* max 128 bytes */ - public string smallImageKey; - /* max 32 bytes */ - public string smallImageText; - /* max 128 bytes */ - public string partyId; - /* max 128 bytes */ - public int partySize; - public int partyMax; - public string matchSecret; - /* max 128 bytes */ - public string joinSecret; - /* max 128 bytes */ - public string spectateSecret; - /* max 128 bytes */ - public bool instance; - } - - [System.Serializable] - public struct JoinRequest - { - public string userId; - public string username; - public string avatar; - } - - public enum Reply - { - No = 0, - Yes = 1, - Ignore = 2 - } - [DllImport("discord-rpc", EntryPoint = "Discord_Initialize", CallingConvention = CallingConvention.Cdecl)] - public static extern void Initialize(string applicationId, ref EventHandlers handlers, bool autoRegister, string optionalSteamId); - - [DllImport("discord-rpc", EntryPoint = "Discord_Shutdown", CallingConvention = CallingConvention.Cdecl)] - public static extern void Shutdown(); - - [DllImport("discord-rpc", EntryPoint = "Discord_RunCallbacks", CallingConvention = CallingConvention.Cdecl)] - public static extern void RunCallbacks(); - - [DllImport("discord-rpc", EntryPoint = "Discord_UpdatePresence", CallingConvention = CallingConvention.Cdecl)] - public static extern void UpdatePresence(ref RichPresence presence); - - [DllImport("discord-rpc", EntryPoint = "Discord_Respond", CallingConvention = CallingConvention.Cdecl)] - public static extern void Respond(string userId, Reply reply); + #endregion } -#endregion diff --git a/Novetus/NovetusCore/Classes/INIFile.cs b/Novetus/NovetusCore/Classes/INIFile.cs index 9d944c0..3e4236c 100644 --- a/Novetus/NovetusCore/Classes/INIFile.cs +++ b/Novetus/NovetusCore/Classes/INIFile.cs @@ -5,95 +5,98 @@ using System.Runtime.InteropServices; using System.Text; #endregion -#region INI File Parser -//modified from https://www.codeproject.com/articles/1966/an-ini-file-handling-class-using-c?fid=425860&df=90&mpp=25&prof=True&sort=Position&view=Normal&spc=Relaxed&fr=51 - -public class INIFile +namespace Novetus.Core { - public string path; + #region INI File Parser + //modified from https://www.codeproject.com/articles/1966/an-ini-file-handling-class-using-c?fid=425860&df=90&mpp=25&prof=True&sort=Position&view=Normal&spc=Relaxed&fr=51 - [DllImport("kernel32")] - private static extern long WritePrivateProfileString(string section, - string key, string val, string filePath); - [DllImport("kernel32")] - private static extern int GetPrivateProfileString(string section, - string key, string def, StringBuilder retVal, - int size, string filePath); + public class INIFile + { + public string path; - /// - /// INIFile Constructor. - /// - /// - public INIFile(string INIPath) - { - path = INIPath; - } - /// - /// Write Data to the INI File - /// - /// - /// Section name - /// - /// Key Name - /// - /// Value Name - public void IniWriteValue(string Section, string Key, string Value) - { - WritePrivateProfileString(Section, Key, Value, path); - } + [DllImport("kernel32")] + private static extern long WritePrivateProfileString(string section, + string key, string val, string filePath); + [DllImport("kernel32")] + private static extern int GetPrivateProfileString(string section, + string key, string def, StringBuilder retVal, + int size, string filePath); - /// - /// Read Data Value From the Ini File - /// - /// - /// - /// - /// - public string IniReadValue(string Section, string Key, string DefaultValue = "") - { - if (IniValueExists(Key)) + /// + /// INIFile Constructor. + /// + /// + public INIFile(string INIPath) { - StringBuilder temp = new StringBuilder(255); - int i = GetPrivateProfileString(Section, Key, "", temp, - 255, path); - return temp.ToString(); + path = INIPath; } - else + /// + /// Write Data to the INI File + /// + /// + /// Section name + /// + /// Key Name + /// + /// Value Name + public void IniWriteValue(string Section, string Key, string Value) { - IniWriteValue(Section, Key, DefaultValue); - return DefaultValue; + WritePrivateProfileString(Section, Key, Value, path); } - } - public bool IniValueExists(string SearchString) - { - try + /// + /// Read Data Value From the Ini File + /// + /// + /// + /// + /// + public string IniReadValue(string Section, string Key, string DefaultValue = "") { - if (File.Exists(path)) + if (IniValueExists(Key)) { - string[] lines = File.ReadAllLines(path); + StringBuilder temp = new StringBuilder(255); + int i = GetPrivateProfileString(Section, Key, "", temp, + 255, path); + return temp.ToString(); + } + else + { + IniWriteValue(Section, Key, DefaultValue); + return DefaultValue; + } + } - foreach (string line in lines) + public bool IniValueExists(string SearchString) + { + try + { + if (File.Exists(path)) { - if (line.Contains(SearchString)) + string[] lines = File.ReadAllLines(path); + + foreach (string line in lines) { - return true; + if (line.Contains(SearchString)) + { + return true; + } } } - } - return false; - } + return false; + } #if URI || LAUNCHER || BASICLAUNCHER - catch (Exception ex) - { - Util.LogExceptions(ex); + catch (Exception ex) + { + Util.LogExceptions(ex); #else catch (Exception) { #endif - return false; + return false; + } } } + #endregion } -#endregion diff --git a/Novetus/NovetusCore/Classes/Script.cs b/Novetus/NovetusCore/Classes/Script.cs new file mode 100644 index 0000000..d8b9525 --- /dev/null +++ b/Novetus/NovetusCore/Classes/Script.cs @@ -0,0 +1,111 @@ +#region Usings +using System; +using System.Reflection; +using Microsoft.CSharp; +using System.CodeDom.Compiler; +using System.IO; +using System.Linq; +#endregion + +// based on https://stackoverflow.com/questions/137933/what-is-the-best-scripting-language-to-embed-in-a-c-sharp-desktop-application +namespace Novetus.Core +{ + #region Script + public class Script + { + public static object LoadScriptFromContent(string scriptPath) + { + try + { + using (var stream = File.OpenRead(scriptPath)) + { + using (var reader = new StreamReader(stream)) + { + string script = reader.ReadToEnd(); + Assembly compiled = CompileScript(script, scriptPath); + object code = ExecuteScript(compiled, scriptPath); + return code; + } + } + } + catch (Exception ex) + { + ErrorHandler(scriptPath + ": " + ex.ToString(), true); + } + + return null; + } + + private static object ExecuteScript(Assembly assemblyScript, string filePath) + { + if (assemblyScript == null) + { + goto error; + } + + foreach (Type type in assemblyScript.GetExportedTypes()) + { + if (type.IsInterface || type.IsAbstract) + continue; + + ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes); + + if (constructor != null && constructor.IsPublic) + { + return constructor.Invoke(null); + } + else + { + ErrorHandler(filePath + ": Constructor does not exist or it is not public.", true); + return null; + } + } + +error: + ErrorHandler(filePath + ": Failed to load script.", true); + return null; + } + + private static Assembly CompileScript(string code, string filePath) + { + CSharpCodeProvider provider = new CSharpCodeProvider(); + + CompilerParameters perams = new CompilerParameters(); + perams.GenerateExecutable = false; + perams.GenerateInMemory = true; + + var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic).Select(a => a.Location); + perams.ReferencedAssemblies.AddRange(assemblies.ToArray()); + + CompilerResults result = provider.CompileAssemblyFromSource(perams, code); + + foreach (CompilerError error in result.Errors) + { + ErrorHandler(error, filePath, error.IsWarning, false); + } + + if (result.Errors.HasErrors) + { + return null; + } + + return result.CompiledAssembly; + } + + public static void ErrorHandler(string error, bool finalError = false) + { + ErrorHandler(error, false, finalError); + } + + private static void ErrorHandler(string error, bool warning, bool finalError) + { + Util.ConsolePrint(warning ? "[SCRIPT WARNING] - " : "[SCRIPT ERROR] - " + error, warning ? 5 : 2); + } + + private static void ErrorHandler(CompilerError error, string fileName, bool warning, bool finalError) + { + Util.ConsolePrint(warning ? "[SCRIPT WARNING] - " : "[SCRIPT ERROR] - " + fileName + " (" + error.Line + "," + error.Column + "): " + error.ErrorText, warning ? 5 : 2); + } + } + #endregion +} diff --git a/Novetus/NovetusCore/Classes/TextLineRemover.cs b/Novetus/NovetusCore/Classes/TextLineRemover.cs index 2a44ee3..fe6d400 100644 --- a/Novetus/NovetusCore/Classes/TextLineRemover.cs +++ b/Novetus/NovetusCore/Classes/TextLineRemover.cs @@ -4,100 +4,103 @@ using System.Collections.Generic; using System.IO; #endregion -#region Text Line Remover and Friends -// modified from https://stackoverflow.com/questions/668907/how-to-delete-a-line-from-a-text-file-in-c/668914#668914 - -public static class TextLineRemover +namespace Novetus.Core { - public static void RemoveTextLines(IList linesToRemove, string filename, string tempFilename) - { - // Initial values - int lineNumber = 0; - int linesRemoved = 0; - DateTime startTime = DateTime.Now; + #region Text Line Remover and Friends + // modified from https://stackoverflow.com/questions/668907/how-to-delete-a-line-from-a-text-file-in-c/668914#668914 - // Read file - using (var sr = new StreamReader(filename)) + public static class TextLineRemover + { + public static void RemoveTextLines(IList linesToRemove, string filename, string tempFilename) { - // Write new file - using (var sw = new StreamWriter(tempFilename)) + // Initial values + int lineNumber = 0; + int linesRemoved = 0; + DateTime startTime = DateTime.Now; + + // Read file + using (var sr = new StreamReader(filename)) { - // Read lines - string line; - while ((line = sr.ReadLine()) != null) + // Write new file + using (var sw = new StreamWriter(tempFilename)) { - lineNumber++; - // Look for text to remove - if (!ContainsString(line, linesToRemove)) + // Read lines + string line; + while ((line = sr.ReadLine()) != null) { - // Keep lines that does not match - sw.WriteLine(line); - } - else - { - // Ignore lines that DO match - linesRemoved++; - InvokeOnRemovedLine(new RemovedLineArgs + lineNumber++; + // Look for text to remove + if (!ContainsString(line, linesToRemove)) { - RemovedLine = line, - RemovedLineNumber = lineNumber - }); + // Keep lines that does not match + sw.WriteLine(line); + } + else + { + // Ignore lines that DO match + linesRemoved++; + InvokeOnRemovedLine(new RemovedLineArgs + { + RemovedLine = line, + RemovedLineNumber = lineNumber + }); + } } } } + + //FixedFileMove deletes the original file and moves the temp file in. + Util.FixedFileMove(tempFilename, filename, true); + + // Final calculations + DateTime endTime = DateTime.Now; + InvokeOnFinished(new FinishedArgs + { + LinesRemoved = linesRemoved, + TotalLines = lineNumber, + TotalTime = endTime.Subtract(startTime) + }); } - //FixedFileMove deletes the original file and moves the temp file in. - Util.FixedFileMove(tempFilename, filename, true); - - // Final calculations - DateTime endTime = DateTime.Now; - InvokeOnFinished(new FinishedArgs + private static bool ContainsString(string line, IEnumerable linesToRemove) { - LinesRemoved = linesRemoved, - TotalLines = lineNumber, - TotalTime = endTime.Subtract(startTime) - }); - } - - private static bool ContainsString(string line, IEnumerable linesToRemove) - { - foreach (var lineToRemove in linesToRemove) - { - if (line.Contains(lineToRemove)) - return true; + foreach (var lineToRemove in linesToRemove) + { + if (line.Contains(lineToRemove)) + return true; + } + return false; + } + + public static event RemovedLine OnRemovedLine; + public static event Finished OnFinished; + + public static void InvokeOnFinished(FinishedArgs args) + { + OnFinished?.Invoke(null, args); + } + + public static void InvokeOnRemovedLine(RemovedLineArgs args) + { + OnRemovedLine?.Invoke(null, args); } - return false; } - public static event RemovedLine OnRemovedLine; - public static event Finished OnFinished; + public delegate void Finished(object sender, FinishedArgs args); - public static void InvokeOnFinished(FinishedArgs args) + public struct FinishedArgs { - OnFinished?.Invoke(null, args); + public int TotalLines { get; set; } + public int LinesRemoved { get; set; } + public TimeSpan TotalTime { get; set; } } - public static void InvokeOnRemovedLine(RemovedLineArgs args) + public delegate void RemovedLine(object sender, RemovedLineArgs args); + + public struct RemovedLineArgs { - OnRemovedLine?.Invoke(null, args); + public string RemovedLine { get; set; } + public int RemovedLineNumber { get; set; } } + #endregion } - -public delegate void Finished(object sender, FinishedArgs args); - -public struct FinishedArgs -{ - public int TotalLines { get; set; } - public int LinesRemoved { get; set; } - public TimeSpan TotalTime { get; set; } -} - -public delegate void RemovedLine(object sender, RemovedLineArgs args); - -public struct RemovedLineArgs -{ - public string RemovedLine { get; set; } - public int RemovedLineNumber { get; set; } -} -#endregion diff --git a/Novetus/NovetusCore/Classes/UHWIDEngine.cs b/Novetus/NovetusCore/Classes/UHWIDEngine.cs index 1821c7b..205586c 100644 --- a/Novetus/NovetusCore/Classes/UHWIDEngine.cs +++ b/Novetus/NovetusCore/Classes/UHWIDEngine.cs @@ -7,9 +7,10 @@ using System.IO; using System.Runtime.InteropServices; #endregion + //https://github.com/davcs86/csharp-uhwid //merged into one class -namespace UHWID +namespace Novetus.Core { #region UHWIDEngine public static class UHWIDEngine diff --git a/Novetus/NovetusCore/Classes/WebProxy.cs b/Novetus/NovetusCore/Classes/WebProxy.cs index a54446d..31892b3 100644 --- a/Novetus/NovetusCore/Classes/WebProxy.cs +++ b/Novetus/NovetusCore/Classes/WebProxy.cs @@ -12,162 +12,268 @@ using Titanium.Web.Proxy.EventArguments; using Titanium.Web.Proxy.Http; using Titanium.Web.Proxy.Models; -public class WebProxy +namespace Novetus.Core { - private static ProxyServer Server = new ProxyServer(); - private static ExplicitProxyEndPoint end; - - public bool HasStarted() + public class IWebProxyExtension { - return Server.ProxyRunning; + public virtual string Name { get; set; } = "Unnamed Web Proxy Extension"; + public virtual void OnExtensionLoad() { } + public virtual void OnProxyStart() { } + public virtual void OnProxyStopped() { } + + public virtual bool IsValidURL(string absolutePath, string host) { return false; } + + public virtual Task OnBeforeTunnelConnectRequest(object sender, TunnelConnectSessionEventArgs e) { return Task.CompletedTask; } +#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously + public virtual async Task OnRequest(object sender, SessionEventArgs e) { } +#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously } - public void DoSetup() + public class WebProxy { - if (GlobalVars.UserConfiguration.WebProxyInitialSetupRequired) + private static List ExtensionList = new List(); + private static ProxyServer Server = new ProxyServer(); + private static ExplicitProxyEndPoint end; + + public void LoadExtensions() { - string text = "Would you like to enable the Novetus web proxy?\n\n" + - "A web proxy redirects web traffic to a different location and in some cases can act as a gateway to different sites. Novetus uses the web proxy for additional client features and asset redirection.\n\n" + - "When enabling the web proxy, Novetus will locally create a certificate upon startup that ensures the proxy's functionality. Novetus will not send any user data to anyone, as everything involving the web proxy is entirely local to this computer.\n" + - "If you have any issue connecting to other web sites, including Roblox, closing Novetus or typing 'proxy off' into Novetus' console will fix it in most instances.\n\n" + - "Upon pressing 'Yes', Windows will ask you for permission to install the certificate.\n\n" + - "You can change this option at any time by typing 'proxy disable' or 'proxy on' in the Novetus console. This message will appear only once.\n"; + string nothingFoundError = "No extensions found. The Web Proxy will run with limited functionality."; - DialogResult result = MessageBox.Show(text, "Novetus - Web Proxy Opt-In", MessageBoxButtons.YesNo); - - switch (result) + if (!Directory.Exists(GlobalPaths.NovetusExtsWebProxy)) { - case DialogResult.Yes: - GlobalVars.UserConfiguration.WebProxyEnabled = true; + Util.ConsolePrint(nothingFoundError, 5); + return; + } + + // load up all .cs files. + string[] filePaths = Directory.GetFiles(GlobalPaths.NovetusExtsWebProxy, "*.cs", SearchOption.TopDirectoryOnly); + + if (filePaths.Count() == 0) + { + Util.ConsolePrint(nothingFoundError, 5); + return; + } + + foreach (string file in filePaths) + { + try + { + IWebProxyExtension newExt = (IWebProxyExtension)Script.LoadScriptFromContent(file); + ExtensionList.Add(newExt); + Util.ConsolePrint("Web Proxy: Loaded extension " + newExt.Name + " from " + Path.GetFileName(file), 3); + newExt.OnExtensionLoad(); + } + catch (Exception e) + { + Util.LogExceptions(e); + } + } + } + + public bool HasStarted() + { + return Server.ProxyRunning; + } + + public void DoSetup() + { + if (GlobalVars.UserConfiguration.WebProxyInitialSetupRequired) + { + string text = "Would you like to enable the Novetus web proxy?\n\n" + + "A web proxy redirects web traffic to a different location and in some cases can act as a gateway to different sites. Novetus uses the web proxy for additional client features and asset redirection.\n\n" + + "When enabling the web proxy, Novetus will locally create a certificate upon startup that ensures the proxy's functionality. Novetus will not send any user data to anyone, as everything involving the web proxy is entirely local to this computer.\n" + + "If you have any issue connecting to other web sites, including Roblox, closing Novetus or typing 'proxy off' into Novetus' console will fix it in most instances.\n\n" + + "Upon pressing 'Yes', Windows will ask you for permission to install the certificate.\n\n" + + "You can change this option at any time by typing 'proxy disable' or 'proxy on' in the Novetus console. This message will appear only once.\n"; + + DialogResult result = MessageBox.Show(text, "Novetus - Web Proxy Opt-In", MessageBoxButtons.YesNo); + + switch (result) + { + case DialogResult.Yes: + GlobalVars.UserConfiguration.WebProxyEnabled = true; + Start(); + break; + case DialogResult.No: + default: + break; + } + + GlobalVars.UserConfiguration.WebProxyInitialSetupRequired = false; + FileManagement.Config(GlobalPaths.ConfigDir + "\\" + GlobalPaths.ConfigName, true); + } + else + { + if (GlobalVars.UserConfiguration.WebProxyEnabled) + { Start(); - break; - case DialogResult.No: - default: - break; + } } - - GlobalVars.UserConfiguration.WebProxyInitialSetupRequired = false; - FileManagement.Config(GlobalPaths.ConfigDir + "\\" + GlobalPaths.ConfigName, true); } - else + + public void Start() { - if (GlobalVars.UserConfiguration.WebProxyEnabled) + try { - Start(); + LoadExtensions(); + Server.CertificateManager.RootCertificateIssuerName = "Novetus"; + Server.CertificateManager.RootCertificateName = "Novetus Web Proxy"; + Server.BeforeRequest += new AsyncEventHandler(OnRequest); + UpdateEndPoint(true); + Util.ConsolePrint("Web Proxy started on port " + GlobalVars.WebProxyPort, 3); + foreach (IWebProxyExtension extension in ExtensionList.ToArray()) + { + extension.OnProxyStart(); + } } - } - } - - public void Start() - { - try - { - //load ext - Server.CertificateManager.RootCertificateIssuerName = "Novetus"; - Server.CertificateManager.RootCertificateName = "Novetus Web Proxy"; - Server.BeforeRequest += new AsyncEventHandler(OnRequest); - UpdateEndPoint(true); - Util.ConsolePrint("Web Proxy started on port " + GlobalVars.WebProxyPort, 3); - } - catch (Exception e) - { - Util.LogExceptions(e); - } - } - - public void UpdateEndPoint(bool shouldRunServer = false, bool decrypt = true) - { - if (Server.ProxyEndPoints.Count > 0) - { - Server.RemoveEndPoint(end); - } - - GlobalVars.WebProxyPort = GlobalVars.UserConfiguration.RobloxPort + 1; - end = new ExplicitProxyEndPoint(IPAddress.Any, GlobalVars.WebProxyPort, decrypt); - end.BeforeTunnelConnectRequest += new AsyncEventHandler(OnBeforeTunnelConnectRequest); - Server.AddEndPoint(end); - - if (!Server.ProxyRunning && shouldRunServer) - { - Server.Start(); - } - - if (Server.ProxyRunning) - { - foreach (ProxyEndPoint endPoint in Server.ProxyEndPoints) + catch (Exception e) { - Server.SetAsSystemHttpProxy(end); - Server.SetAsSystemHttpsProxy(end); + Util.LogExceptions(e); } } - Util.ConsolePrint("Web Proxy Endpoint updated with port " + GlobalVars.WebProxyPort, 3); - } - - private bool IsURIAllowed(HttpWebClient client) - { - string uri = client.Request.RequestUri.Host; - - if ((!uri.StartsWith("www.") && - !uri.StartsWith("web.") && - !uri.StartsWith("assetgame.") && - !uri.StartsWith("wiki.") && - !uri.EndsWith("api.roblox.com") && - !uri.StartsWith("roblox.com") || !uri.EndsWith("roblox.com")) && - !uri.EndsWith("robloxlabs.com")) + public void UpdateEndPoint(bool shouldRunServer = false, bool decrypt = true) { - return false; + if (Server.ProxyEndPoints.Count > 0) + { + Server.RemoveEndPoint(end); + } + + GlobalVars.WebProxyPort = GlobalVars.UserConfiguration.RobloxPort + 1; + end = new ExplicitProxyEndPoint(IPAddress.Any, GlobalVars.WebProxyPort, decrypt); + end.BeforeTunnelConnectRequest += new AsyncEventHandler(OnBeforeTunnelConnectRequest); + Server.AddEndPoint(end); + + if (!Server.ProxyRunning && shouldRunServer) + { + Server.Start(); + } + + if (Server.ProxyRunning) + { + foreach (ProxyEndPoint endPoint in Server.ProxyEndPoints) + { + Server.SetAsSystemHttpProxy(end); + Server.SetAsSystemHttpsProxy(end); + } + } + + Util.ConsolePrint("Web Proxy Endpoint updated with port " + GlobalVars.WebProxyPort, 3); } - //we check the header - HeaderCollection headers = client.Request.Headers; - List userAgents = headers.GetHeaders("User-Agent"); - - if (userAgents == null) - return false; - - if (string.IsNullOrWhiteSpace(userAgents.FirstOrDefault().Value)) - return false; - - string ua = userAgents.FirstOrDefault().Value.ToLowerInvariant(); - - //for some reason, this doesn't go through for the browser unless we look for mozilla/4.0. - //this shouldn't break modern mozilla browsers though. - return (ua.Contains("mozilla/4.0") || ua.Contains("roblox")); - } - - private Task OnBeforeTunnelConnectRequest(object sender, TunnelConnectSessionEventArgs e) - { - if (!IsURIAllowed(e.HttpClient)) + private bool IsValidURL(HttpWebClient client) { - e.DecryptSsl = false; + string uri = client.Request.RequestUri.Host; + + if ((!uri.StartsWith("www.") && + !uri.StartsWith("web.") && + !uri.StartsWith("assetgame.") && + !uri.StartsWith("wiki.") && + !uri.EndsWith("api.roblox.com") && + !uri.StartsWith("roblox.com") || !uri.EndsWith("roblox.com")) && + !uri.EndsWith("robloxlabs.com")) + { + return false; + } + + //we check the header + HeaderCollection headers = client.Request.Headers; + List userAgents = headers.GetHeaders("User-Agent"); + + if (userAgents == null) + return false; + + if (string.IsNullOrWhiteSpace(userAgents.FirstOrDefault().Value)) + return false; + + string ua = userAgents.FirstOrDefault().Value.ToLowerInvariant(); + + //for some reason, this doesn't go through for the browser unless we look for mozilla/4.0. + //this shouldn't break modern mozilla browsers though. + return (ua.Contains("mozilla/4.0") || ua.Contains("roblox")); } - return Task.CompletedTask; - } + private Task OnBeforeTunnelConnectRequest(object sender, TunnelConnectSessionEventArgs e) + { + if (!IsValidURL(e.HttpClient)) + { + e.DecryptSsl = false; + } + + Uri uri = e.HttpClient.Request.RequestUri; + + foreach (IWebProxyExtension extension in ExtensionList.ToArray()) + { + if (extension.IsValidURL(uri.AbsolutePath.ToLowerInvariant(), uri.Host)) + { + try + { + extension.OnBeforeTunnelConnectRequest(sender, e); + } + catch (Exception ex) + { + Util.LogExceptions(ex); + } + } + else + { + e.DecryptSsl = false; + } + } + + return Task.CompletedTask; + } #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously - private async Task OnRequest(object sender, SessionEventArgs e) + private async Task OnRequest(object sender, SessionEventArgs e) #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously - { - if (!IsURIAllowed(e.HttpClient)) { - return; + if (!IsValidURL(e.HttpClient)) + { + return; + } + + Uri uri = e.HttpClient.Request.RequestUri; + + foreach (IWebProxyExtension extension in ExtensionList.ToArray()) + { + if (extension.IsValidURL(uri.AbsolutePath.ToLowerInvariant(), uri.Host)) + { + try + { + await extension.OnRequest(sender, e); + return; + } + catch (Exception ex) + { + Util.LogExceptions(ex); + e.GenericResponse("", HttpStatusCode.InternalServerError); + return; + } + } + } + + e.GenericResponse("", HttpStatusCode.NotFound); } - e.GenericResponse("", HttpStatusCode.NotFound); + public void Stop() + { + Util.ConsolePrint("Web Proxy stopping on port " + GlobalVars.WebProxyPort, 3); + Server.BeforeRequest -= new AsyncEventHandler(OnRequest); + Server.Stop(); + + foreach (IWebProxyExtension extension in ExtensionList.ToArray()) + { + try + { + extension.OnProxyStopped(); + } + catch (Exception e) + { + Util.LogExceptions(e); + } + } + } } - - public void Stop() - { - Util.ConsolePrint("Web Proxy stopping on port " + GlobalVars.WebProxyPort, 3); - Server.BeforeRequest -= new AsyncEventHandler(OnRequest); - Server.Stop(); - } -} - -public interface IWebProxyExtention -{ - } #endif diff --git a/Novetus/NovetusCore/NovetusCore.projitems b/Novetus/NovetusCore/NovetusCore.projitems index 2657b69..2563963 100644 --- a/Novetus/NovetusCore/NovetusCore.projitems +++ b/Novetus/NovetusCore/NovetusCore.projitems @@ -9,6 +9,7 @@ NovetusCore + diff --git a/Novetus/NovetusCore/StorageAndFunctions/ClientManagement.cs b/Novetus/NovetusCore/StorageAndFunctions/ClientManagement.cs index 162621a..edd96bd 100644 --- a/Novetus/NovetusCore/StorageAndFunctions/ClientManagement.cs +++ b/Novetus/NovetusCore/StorageAndFunctions/ClientManagement.cs @@ -12,190 +12,192 @@ using System.Security.Cryptography; using System.Reflection; #endregion -#region Client Management -public class ClientManagement +namespace Novetus.Core { - public static void ReadClientValues(bool initial = false) + #region Client Management + public class ClientManagement { - ReadClientValues(GlobalVars.UserConfiguration.SelectedClient, initial); - } - - public static void ReadClientValues(string ClientName, bool initial = false) - { - string name = ClientName; - if (string.IsNullOrWhiteSpace(name)) + public static void ReadClientValues(bool initial = false) { - if (!string.IsNullOrWhiteSpace(GlobalVars.ProgramInformation.DefaultClient)) - { - name = GlobalVars.ProgramInformation.DefaultClient; - } - else - { - return; - } + ReadClientValues(GlobalVars.UserConfiguration.SelectedClient, initial); } - string clientpath = GlobalPaths.ClientDir + @"\\" + name + @"\\clientinfo.nov"; - - if (!File.Exists(clientpath)) + public static void ReadClientValues(string ClientName, bool initial = false) { - try + string name = ClientName; + if (string.IsNullOrWhiteSpace(name)) { - Util.ConsolePrint("ERROR - No clientinfo.nov detected with the client you chose. The client either cannot be loaded, or it is not available. Novetus will attempt to generate one.", 2); - GenerateDefaultClientInfo(Path.GetDirectoryName(clientpath)); - ReadClientValues(name, initial); + if (!string.IsNullOrWhiteSpace(GlobalVars.ProgramInformation.DefaultClient)) + { + name = GlobalVars.ProgramInformation.DefaultClient; + } + else + { + return; + } } -#if URI || LAUNCHER || BASICLAUNCHER - catch (Exception ex) + + string clientpath = GlobalPaths.ClientDir + @"\\" + name + @"\\clientinfo.nov"; + + if (!File.Exists(clientpath)) { - Util.LogExceptions(ex); + try + { + Util.ConsolePrint("ERROR - No clientinfo.nov detected with the client you chose. The client either cannot be loaded, or it is not available. Novetus will attempt to generate one.", 2); + GenerateDefaultClientInfo(Path.GetDirectoryName(clientpath)); + ReadClientValues(name, initial); + } +#if URI || LAUNCHER || BASICLAUNCHER + catch (Exception ex) + { + Util.LogExceptions(ex); #else catch (Exception) { #endif - Util.ConsolePrint("ERROR - Failed to generate default clientinfo.nov. Info: " + ex.Message, 2); - Util.ConsolePrint("Loading default client '" + GlobalVars.ProgramInformation.DefaultClient + "'", 4); - name = GlobalVars.ProgramInformation.DefaultClient; - ReadClientValues(name, initial); - } - } - else - { - LoadClientValues(clientpath); - - if (initial) - { - Util.ConsolePrint("Client '" + name + "' successfully loaded.", 3); - } - } - - string terms = "_" + ClientName + "_default"; - string[] dirs = Directory.GetFiles(GlobalPaths.ConfigDirClients); - - foreach (string dir in dirs) - { - if (dir.Contains(terms) && dir.EndsWith(".xml")) - { - string fullpath = dir.Replace("_default", ""); - - if (!File.Exists(fullpath)) - { - Util.FixedFileCopy(dir, fullpath, false); + Util.ConsolePrint("ERROR - Failed to generate default clientinfo.nov. Info: " + ex.Message, 2); + Util.ConsolePrint("Loading default client '" + GlobalVars.ProgramInformation.DefaultClient + "'", 4); + name = GlobalVars.ProgramInformation.DefaultClient; + ReadClientValues(name, initial); } } + else + { + LoadClientValues(clientpath); + + if (initial) + { + Util.ConsolePrint("Client '" + name + "' successfully loaded.", 3); + } + } + + string terms = "_" + ClientName + "_default"; + string[] dirs = Directory.GetFiles(GlobalPaths.ConfigDirClients); + + foreach (string dir in dirs) + { + if (dir.Contains(terms) && dir.EndsWith(".xml")) + { + string fullpath = dir.Replace("_default", ""); + + if (!File.Exists(fullpath)) + { + Util.FixedFileCopy(dir, fullpath, false); + } + } + } + + ChangeGameSettings(ClientName); } - ChangeGameSettings(ClientName); - } + //Modified from https://stackoverflow.com/questions/4286487/is-there-any-lorem-ipsum-generator-in-c + public static string LoremIpsum(int minWords, int maxWords, + int minSentences, int maxSentences, + int numParagraphs) + { - //Modified from https://stackoverflow.com/questions/4286487/is-there-any-lorem-ipsum-generator-in-c - public static string LoremIpsum(int minWords, int maxWords, - int minSentences, int maxSentences, - int numParagraphs) - { - - var words = new[]{"lorem", "ipsum", "dolor", "sit", "amet", "consectetuer", + var words = new[]{"lorem", "ipsum", "dolor", "sit", "amet", "consectetuer", "adipiscing", "elit", "sed", "diam", "nonummy", "nibh", "euismod", "tincidunt", "ut", "laoreet", "dolore", "magna", "aliquam", "erat"}; - var rand = new Random(); - int numSentences = rand.Next(maxSentences - minSentences) - + minSentences + 1; - int numWords = rand.Next(maxWords - minWords) + minWords + 1; + var rand = new Random(); + int numSentences = rand.Next(maxSentences - minSentences) + + minSentences + 1; + int numWords = rand.Next(maxWords - minWords) + minWords + 1; - StringBuilder result = new StringBuilder(); + StringBuilder result = new StringBuilder(); - for (int p = 0; p < numParagraphs; p++) - { - result.Append("lorem ipsum "); - for (int s = 0; s < numSentences; s++) + for (int p = 0; p < numParagraphs; p++) { - for (int w = 0; w < numWords; w++) + result.Append("lorem ipsum "); + for (int s = 0; s < numSentences; s++) { - if (w > 0) { result.Append(" "); } - result.Append(words[rand.Next(words.Length)]); + for (int w = 0; w < numWords; w++) + { + if (w > 0) { result.Append(" "); } + result.Append(words[rand.Next(words.Length)]); + } + result.Append(". "); } - result.Append(". "); } + + return result.ToString(); } - return result.ToString(); - } - - //https://stackoverflow.com/questions/63879676/open-all-exe-files-in-a-directory-c-sharp - public static List GetAllExecutables(string path) - { - return Directory.Exists(path) - ? Directory.GetFiles(path, "*.exe").ToList() - : new List(); // or null - } - - public static void GenerateDefaultClientInfo(string path) - { - FileFormat.ClientInfo DefaultClientInfo = new FileFormat.ClientInfo(); - bool placeholder = false; - - string ClientName = ""; - List exeList = GetAllExecutables(path); - - if (File.Exists(path + "\\RobloxApp_client.exe")) + //https://stackoverflow.com/questions/63879676/open-all-exe-files-in-a-directory-c-sharp + public static List GetAllExecutables(string path) { - ClientName = "\\RobloxApp_client.exe"; - } - else if (File.Exists(path + "\\client\\RobloxApp_client.exe")) - { - ClientName = "\\client\\RobloxApp_client.exe"; - DefaultClientInfo.SeperateFolders = true; - } - else if (File.Exists(path + "\\RobloxApp.exe")) - { - ClientName = "\\RobloxApp.exe"; - DefaultClientInfo.LegacyMode = true; - } - else if (exeList.Count > 0) - { - string FirstEXE = exeList[0].Replace(path, "").Replace(@"\", ""); - ClientName = @"\\" + FirstEXE; - DefaultClientInfo.CustomClientEXEName = ClientName; - DefaultClientInfo.UsesCustomClientEXEName = true; - } - else - { - IOException clientNotFoundEX = new IOException("Could not find client exe file. Your client must have a .exe file to function."); - throw clientNotFoundEX; + return Directory.Exists(path) + ? Directory.GetFiles(path, "*.exe").ToList() + : new List(); // or null } - string ClientMD5 = File.Exists(path + ClientName) ? SecurityFuncs.GenerateMD5(path + ClientName) : ""; - - if (!string.IsNullOrWhiteSpace(ClientMD5)) + public static void GenerateDefaultClientInfo(string path) { - DefaultClientInfo.ClientMD5 = ClientMD5.ToUpper(CultureInfo.InvariantCulture); - } - else - { - IOException clientNotFoundEX = new IOException("Could not find client exe for MD5 generation. It must be named either RobloxApp.exe or RobloxApp_client.exe in order to function."); - throw clientNotFoundEX; - } + FileFormat.ClientInfo DefaultClientInfo = new FileFormat.ClientInfo(); + bool placeholder = false; - string ClientScriptMD5 = File.Exists(path + "\\content\\scripts\\" + GlobalPaths.ScriptName + ".lua") ? SecurityFuncs.GenerateMD5(path + "\\content\\scripts\\" + GlobalPaths.ScriptName + ".lua") : ""; + string ClientName = ""; + List exeList = GetAllExecutables(path); - if (!string.IsNullOrWhiteSpace(ClientScriptMD5)) - { - DefaultClientInfo.ScriptMD5 = ClientScriptMD5.ToUpper(CultureInfo.InvariantCulture); - } - /*else - { - IOException clientNotFoundEX = new IOException("Could not find script file for MD5 generation. You must have a CSMPFunctions.lua script in your client's content/scripts folder."); - throw clientNotFoundEX; - }*/ + if (File.Exists(path + "\\RobloxApp_client.exe")) + { + ClientName = "\\RobloxApp_client.exe"; + } + else if (File.Exists(path + "\\client\\RobloxApp_client.exe")) + { + ClientName = "\\client\\RobloxApp_client.exe"; + DefaultClientInfo.SeperateFolders = true; + } + else if (File.Exists(path + "\\RobloxApp.exe")) + { + ClientName = "\\RobloxApp.exe"; + DefaultClientInfo.LegacyMode = true; + } + else if (exeList.Count > 0) + { + string FirstEXE = exeList[0].Replace(path, "").Replace(@"\", ""); + ClientName = @"\\" + FirstEXE; + DefaultClientInfo.CustomClientEXEName = ClientName; + DefaultClientInfo.UsesCustomClientEXEName = true; + } + else + { + IOException clientNotFoundEX = new IOException("Could not find client exe file. Your client must have a .exe file to function."); + throw clientNotFoundEX; + } - string desc = "This client information file for '" + GlobalVars.UserConfiguration.SelectedClient + - "' was pre-generated by Novetus for your convienence. You will need to load this clientinfo.nov file into the Client SDK for additional options. " - + LoremIpsum(1, 128, 1, 6, 1); + string ClientMD5 = File.Exists(path + ClientName) ? SecurityFuncs.GenerateMD5(path + ClientName) : ""; - DefaultClientInfo.Description = desc; + if (!string.IsNullOrWhiteSpace(ClientMD5)) + { + DefaultClientInfo.ClientMD5 = ClientMD5.ToUpper(CultureInfo.InvariantCulture); + } + else + { + IOException clientNotFoundEX = new IOException("Could not find client exe for MD5 generation. It must be named either RobloxApp.exe or RobloxApp_client.exe in order to function."); + throw clientNotFoundEX; + } - string[] lines = { + string ClientScriptMD5 = File.Exists(path + "\\content\\scripts\\" + GlobalPaths.ScriptName + ".lua") ? SecurityFuncs.GenerateMD5(path + "\\content\\scripts\\" + GlobalPaths.ScriptName + ".lua") : ""; + + if (!string.IsNullOrWhiteSpace(ClientScriptMD5)) + { + DefaultClientInfo.ScriptMD5 = ClientScriptMD5.ToUpper(CultureInfo.InvariantCulture); + } + /*else + { + IOException clientNotFoundEX = new IOException("Could not find script file for MD5 generation. You must have a CSMPFunctions.lua script in your client's content/scripts folder."); + throw clientNotFoundEX; + }*/ + + string desc = "This client information file for '" + GlobalVars.UserConfiguration.SelectedClient + + "' was pre-generated by Novetus for your convienence. You will need to load this clientinfo.nov file into the Client SDK for additional options. " + + LoremIpsum(1, 128, 1, 6, 1); + + DefaultClientInfo.Description = desc; + + string[] lines = { SecurityFuncs.Base64Encode(DefaultClientInfo.UsesPlayerName.ToString()), SecurityFuncs.Base64Encode(DefaultClientInfo.UsesID.ToString()), SecurityFuncs.Base64Encode(DefaultClientInfo.Warning.ToString()), @@ -213,362 +215,443 @@ public class ClientManagement SecurityFuncs.Base64Encode(DefaultClientInfo.CommandLineArgs.ToString()) }; - File.WriteAllText(path + "\\clientinfo.nov", SecurityFuncs.Base64Encode(string.Join("|", lines))); - } - - //NOT FOR SDK. - public static FileFormat.ClientInfo GetClientInfoValues(string ClientName) - { - string name = ClientName; - - try - { - FileFormat.ClientInfo info = new FileFormat.ClientInfo(); - string clientpath = GlobalPaths.ClientDir + @"\\" + name + @"\\clientinfo.nov"; - LoadClientValues(info, clientpath); - return info; + File.WriteAllText(path + "\\clientinfo.nov", SecurityFuncs.Base64Encode(string.Join("|", lines))); } -#if URI || LAUNCHER || BASICLAUNCHER - catch (Exception ex) + + //NOT FOR SDK. + public static FileFormat.ClientInfo GetClientInfoValues(string ClientName) { - Util.LogExceptions(ex); + string name = ClientName; + + try + { + FileFormat.ClientInfo info = new FileFormat.ClientInfo(); + string clientpath = GlobalPaths.ClientDir + @"\\" + name + @"\\clientinfo.nov"; + LoadClientValues(info, clientpath); + return info; + } +#if URI || LAUNCHER || BASICLAUNCHER + catch (Exception ex) + { + Util.LogExceptions(ex); #else catch (Exception) { #endif - return null; - } - } - - public static void LoadClientValues(string clientpath) - { - LoadClientValues(GlobalVars.SelectedClientInfo, clientpath); - } - - public static void LoadClientValues(FileFormat.ClientInfo info, string clientpath) - { - string file, usesplayername, usesid, warning, - legacymode, clientmd5, scriptmd5, - desc, fix2007, alreadyhassecurity, - clientloadoptions, commandlineargs, folders, - usescustomname, customname; - - using (StreamReader reader = new StreamReader(clientpath)) - { - file = reader.ReadLine(); + return null; + } } - string ConvertedLine = SecurityFuncs.Base64Decode(file); - string[] result = ConvertedLine.Split('|'); - usesplayername = SecurityFuncs.Base64Decode(result[0]); - usesid = SecurityFuncs.Base64Decode(result[1]); - warning = SecurityFuncs.Base64Decode(result[2]); - legacymode = SecurityFuncs.Base64Decode(result[3]); - clientmd5 = SecurityFuncs.Base64Decode(result[4]); - scriptmd5 = SecurityFuncs.Base64Decode(result[5]); - desc = SecurityFuncs.Base64Decode(result[6]); - fix2007 = SecurityFuncs.Base64Decode(result[8]); - alreadyhassecurity = SecurityFuncs.Base64Decode(result[9]); - clientloadoptions = SecurityFuncs.Base64Decode(result[10]); - folders = "False"; - usescustomname = "False"; - customname = ""; - try + public static void LoadClientValues(string clientpath) { - commandlineargs = SecurityFuncs.Base64Decode(result[11]); + LoadClientValues(GlobalVars.SelectedClientInfo, clientpath); + } - bool parsedValue; - if (bool.TryParse(commandlineargs, out parsedValue)) + public static void LoadClientValues(FileFormat.ClientInfo info, string clientpath) + { + string file, usesplayername, usesid, warning, + legacymode, clientmd5, scriptmd5, + desc, fix2007, alreadyhassecurity, + clientloadoptions, commandlineargs, folders, + usescustomname, customname; + + using (StreamReader reader = new StreamReader(clientpath)) { - folders = SecurityFuncs.Base64Decode(result[11]); - commandlineargs = SecurityFuncs.Base64Decode(result[12]); - bool parsedValue2; - if (bool.TryParse(commandlineargs, out parsedValue2)) + file = reader.ReadLine(); + } + + string ConvertedLine = SecurityFuncs.Base64Decode(file); + string[] result = ConvertedLine.Split('|'); + usesplayername = SecurityFuncs.Base64Decode(result[0]); + usesid = SecurityFuncs.Base64Decode(result[1]); + warning = SecurityFuncs.Base64Decode(result[2]); + legacymode = SecurityFuncs.Base64Decode(result[3]); + clientmd5 = SecurityFuncs.Base64Decode(result[4]); + scriptmd5 = SecurityFuncs.Base64Decode(result[5]); + desc = SecurityFuncs.Base64Decode(result[6]); + fix2007 = SecurityFuncs.Base64Decode(result[8]); + alreadyhassecurity = SecurityFuncs.Base64Decode(result[9]); + clientloadoptions = SecurityFuncs.Base64Decode(result[10]); + folders = "False"; + usescustomname = "False"; + customname = ""; + try + { + commandlineargs = SecurityFuncs.Base64Decode(result[11]); + + bool parsedValue; + if (bool.TryParse(commandlineargs, out parsedValue)) { - usescustomname = SecurityFuncs.Base64Decode(result[12]); - customname = SecurityFuncs.Base64Decode(result[13]); - commandlineargs = SecurityFuncs.Base64Decode(result[14]); - } - } - } - catch (Exception) - { - //fake this option until we properly apply it. - clientloadoptions = "2"; - commandlineargs = SecurityFuncs.Base64Decode(result[10]); - } - - info.UsesPlayerName = Convert.ToBoolean(usesplayername); - info.UsesID = Convert.ToBoolean(usesid); - info.Warning = warning; - info.LegacyMode = Convert.ToBoolean(legacymode); - info.ClientMD5 = clientmd5; - info.ScriptMD5 = scriptmd5; - info.Description = desc; - info.Fix2007 = Convert.ToBoolean(fix2007); - info.AlreadyHasSecurity = Convert.ToBoolean(alreadyhassecurity); - if (clientloadoptions.Equals("True") || clientloadoptions.Equals("False")) - { - info.ClientLoadOptions = Settings.GetClientLoadOptionsForBool(Convert.ToBoolean(clientloadoptions)); - } - else - { - info.ClientLoadOptions = (Settings.ClientLoadOptions)Convert.ToInt32(clientloadoptions); - } - - info.SeperateFolders = Convert.ToBoolean(folders); - info.UsesCustomClientEXEName = Convert.ToBoolean(usescustomname); - info.CustomClientEXEName = customname; - info.CommandLineArgs = commandlineargs; - } - - public static GlobalVars.LauncherState GetStateForType(ScriptType type) - { - switch (type) - { - case ScriptType.Client: - return GlobalVars.LauncherState.InMPGame; - case ScriptType.Solo: - return GlobalVars.LauncherState.InSoloGame; - case ScriptType.Studio: - return GlobalVars.LauncherState.InStudio; - case ScriptType.EasterEgg: - return GlobalVars.LauncherState.InEasterEggGame; - default: - return GlobalVars.LauncherState.InLauncher; - } - } - - public static void UpdateRichPresence(GlobalVars.LauncherState state, bool initial = false) - { - string mapname = ""; - if (GlobalVars.GameOpened != ScriptType.Client) - { - mapname = GlobalVars.UserConfiguration.Map; - } - - UpdateRichPresence(state, GlobalVars.UserConfiguration.SelectedClient, mapname, initial); - } - - public static void UpdateRichPresence(GlobalVars.LauncherState state, string mapname, bool initial = false) - { - UpdateRichPresence(state, GlobalVars.UserConfiguration.SelectedClient, mapname, initial); - } - - public static void UpdateRichPresence(GlobalVars.LauncherState state, string clientname, string mapname, bool initial = false) - { - if (GlobalVars.UserConfiguration.DiscordPresence) - { - if (initial) - { - GlobalVars.presence.largeImageKey = GlobalVars.imagekey_large; - GlobalVars.presence.startTimestamp = SecurityFuncs.UnixTimeNow(); - } - - string ValidMapname = (string.IsNullOrWhiteSpace(mapname) ? "Place1" : mapname); - - switch (state) - { - case GlobalVars.LauncherState.InLauncher: - GlobalVars.presence.smallImageKey = GlobalVars.image_inlauncher; - GlobalVars.presence.state = "In Launcher"; - GlobalVars.presence.details = "Selected " + clientname; - GlobalVars.presence.largeImageText = GlobalVars.UserConfiguration.PlayerName + " | Novetus " + GlobalVars.ProgramInformation.Version; - GlobalVars.presence.smallImageText = "In Launcher"; - break; - case GlobalVars.LauncherState.InMPGame: - GlobalVars.presence.smallImageKey = GlobalVars.image_ingame; - GlobalVars.presence.details = ValidMapname; - GlobalVars.presence.state = "In " + clientname + " Multiplayer Game"; - GlobalVars.presence.largeImageText = GlobalVars.UserConfiguration.PlayerName + " | Novetus " + GlobalVars.ProgramInformation.Version; - GlobalVars.presence.smallImageText = "In " + clientname + " Multiplayer Game"; - break; - case GlobalVars.LauncherState.InSoloGame: - GlobalVars.presence.smallImageKey = GlobalVars.image_ingame; - GlobalVars.presence.details = ValidMapname; - GlobalVars.presence.state = "In " + clientname + " Solo Game"; - GlobalVars.presence.largeImageText = GlobalVars.UserConfiguration.PlayerName + " | Novetus " + GlobalVars.ProgramInformation.Version; - GlobalVars.presence.smallImageText = "In " + clientname + " Solo Game"; - break; - case GlobalVars.LauncherState.InStudio: - GlobalVars.presence.smallImageKey = GlobalVars.image_instudio; - GlobalVars.presence.details = ValidMapname; - GlobalVars.presence.state = "In " + clientname + " Studio"; - GlobalVars.presence.largeImageText = GlobalVars.UserConfiguration.PlayerName + " | Novetus " + GlobalVars.ProgramInformation.Version; - GlobalVars.presence.smallImageText = "In " + clientname + " Studio"; - break; - case GlobalVars.LauncherState.InCustomization: - GlobalVars.presence.smallImageKey = GlobalVars.image_incustomization; - GlobalVars.presence.details = "Customizing " + GlobalVars.UserConfiguration.PlayerName; - GlobalVars.presence.state = "In Character Customization"; - GlobalVars.presence.largeImageText = GlobalVars.UserConfiguration.PlayerName + " | Novetus " + GlobalVars.ProgramInformation.Version; - GlobalVars.presence.smallImageText = "In Character Customization"; - break; - case GlobalVars.LauncherState.InEasterEggGame: - GlobalVars.presence.smallImageKey = GlobalVars.image_ingame; - GlobalVars.presence.details = ValidMapname; - GlobalVars.presence.state = "Reading a message."; - GlobalVars.presence.largeImageText = GlobalVars.UserConfiguration.PlayerName + " | Novetus " + GlobalVars.ProgramInformation.Version; - GlobalVars.presence.smallImageText = "Reading a message."; - break; - case GlobalVars.LauncherState.LoadingURI: - GlobalVars.presence.smallImageKey = GlobalVars.image_ingame; - GlobalVars.presence.details = ValidMapname; - GlobalVars.presence.state = "Joining a " + clientname + " Multiplayer Game"; - GlobalVars.presence.largeImageText = GlobalVars.UserConfiguration.PlayerName + " | Novetus " + GlobalVars.ProgramInformation.Version; - GlobalVars.presence.smallImageText = "Joining a " + clientname + " Multiplayer Game"; - break; - default: - break; - } - - DiscordRPC.UpdatePresence(ref GlobalVars.presence); - } - } - - public static void ChangeGameSettings(string ClientName) - { - try - { - FileFormat.ClientInfo info = GetClientInfoValues(ClientName); - - string filterPath = GlobalPaths.ConfigDir + @"\\" + GlobalPaths.FileDeleteFilterName; - string[] fileListToDelete = File.ReadAllLines(filterPath); - - foreach (string file in fileListToDelete) - { - string fullFilePath = Settings.GetPathForClientLoadOptions(info.ClientLoadOptions) + @"\" + file; - Util.FixedFileDelete(fullFilePath); - } - - if (GlobalVars.UserConfiguration.QualityLevel != Settings.Level.Custom) - { - int GraphicsMode = 0; - - if (info.ClientLoadOptions == Settings.ClientLoadOptions.Client_2008AndUp_ForceAutomaticQL21 || - info.ClientLoadOptions == Settings.ClientLoadOptions.Client_2008AndUp_ForceAutomatic) - { - GraphicsMode = 1; - } - else - { - if (info.ClientLoadOptions != Settings.ClientLoadOptions.Client_2007_NoGraphicsOptions || - info.ClientLoadOptions != Settings.ClientLoadOptions.Client_2008AndUp_NoGraphicsOptions) + folders = SecurityFuncs.Base64Decode(result[11]); + commandlineargs = SecurityFuncs.Base64Decode(result[12]); + bool parsedValue2; + if (bool.TryParse(commandlineargs, out parsedValue2)) { - - switch (GlobalVars.UserConfiguration.GraphicsMode) - { - case Settings.Mode.OpenGLStable: - switch (info.ClientLoadOptions) - { - case Settings.ClientLoadOptions.Client_2007: - case Settings.ClientLoadOptions.Client_2008AndUp_LegacyOpenGL: - case Settings.ClientLoadOptions.Client_2008AndUp_HasCharacterOnlyShadowsLegacyOpenGL: - GraphicsMode = 2; - break; - case Settings.ClientLoadOptions.Client_2008AndUp: - case Settings.ClientLoadOptions.Client_2008AndUp_QualityLevel21: - GraphicsMode = 4; - break; - default: - break; - } - break; - case Settings.Mode.OpenGLExperimental: - GraphicsMode = 4; - break; - case Settings.Mode.DirectX: - GraphicsMode = 3; - break; - default: - GraphicsMode = 1; - break; - } + usescustomname = SecurityFuncs.Base64Decode(result[12]); + customname = SecurityFuncs.Base64Decode(result[13]); + commandlineargs = SecurityFuncs.Base64Decode(result[14]); } } + } + catch (Exception) + { + //fake this option until we properly apply it. + clientloadoptions = "2"; + commandlineargs = SecurityFuncs.Base64Decode(result[10]); + } - //default values are ultra settings - int MeshDetail = 100; - int ShadingQuality = 100; - int GFXQualityLevel = 19; - if (info.ClientLoadOptions == Settings.ClientLoadOptions.Client_2008AndUp_ForceAutomaticQL21 || - info.ClientLoadOptions == Settings.ClientLoadOptions.Client_2008AndUp_QualityLevel21) + info.UsesPlayerName = Convert.ToBoolean(usesplayername); + info.UsesID = Convert.ToBoolean(usesid); + info.Warning = warning; + info.LegacyMode = Convert.ToBoolean(legacymode); + info.ClientMD5 = clientmd5; + info.ScriptMD5 = scriptmd5; + info.Description = desc; + info.Fix2007 = Convert.ToBoolean(fix2007); + info.AlreadyHasSecurity = Convert.ToBoolean(alreadyhassecurity); + if (clientloadoptions.Equals("True") || clientloadoptions.Equals("False")) + { + info.ClientLoadOptions = Settings.GetClientLoadOptionsForBool(Convert.ToBoolean(clientloadoptions)); + } + else + { + info.ClientLoadOptions = (Settings.ClientLoadOptions)Convert.ToInt32(clientloadoptions); + } + + info.SeperateFolders = Convert.ToBoolean(folders); + info.UsesCustomClientEXEName = Convert.ToBoolean(usescustomname); + info.CustomClientEXEName = customname; + info.CommandLineArgs = commandlineargs; + } + + public static GlobalVars.LauncherState GetStateForType(ScriptType type) + { + switch (type) + { + case ScriptType.Client: + return GlobalVars.LauncherState.InMPGame; + case ScriptType.Solo: + return GlobalVars.LauncherState.InSoloGame; + case ScriptType.Studio: + return GlobalVars.LauncherState.InStudio; + case ScriptType.EasterEgg: + return GlobalVars.LauncherState.InEasterEggGame; + default: + return GlobalVars.LauncherState.InLauncher; + } + } + + public static void UpdateRichPresence(GlobalVars.LauncherState state, bool initial = false) + { + string mapname = ""; + if (GlobalVars.GameOpened != ScriptType.Client) + { + mapname = GlobalVars.UserConfiguration.Map; + } + + UpdateRichPresence(state, GlobalVars.UserConfiguration.SelectedClient, mapname, initial); + } + + public static void UpdateRichPresence(GlobalVars.LauncherState state, string mapname, bool initial = false) + { + UpdateRichPresence(state, GlobalVars.UserConfiguration.SelectedClient, mapname, initial); + } + + public static void UpdateRichPresence(GlobalVars.LauncherState state, string clientname, string mapname, bool initial = false) + { + if (GlobalVars.UserConfiguration.DiscordPresence) + { + if (initial) { - GFXQualityLevel = 21; + GlobalVars.presence.largeImageKey = GlobalVars.imagekey_large; + GlobalVars.presence.startTimestamp = SecurityFuncs.UnixTimeNow(); } - int MaterialQuality = 3; - int AASamples = 8; - int Bevels = 1; - int Shadows_2008 = 1; - int AA = 1; - bool Shadows_2007 = true; - switch (GlobalVars.UserConfiguration.QualityLevel) + string ValidMapname = (string.IsNullOrWhiteSpace(mapname) ? "Place1" : mapname); + + switch (state) { - case Settings.Level.Automatic: - //set everything to automatic. Some ultra settings will still be enabled. - AA = 0; - Bevels = 0; - Shadows_2008 = 0; - GFXQualityLevel = 0; - MaterialQuality = 0; - Shadows_2007 = false; + case GlobalVars.LauncherState.InLauncher: + GlobalVars.presence.smallImageKey = GlobalVars.image_inlauncher; + GlobalVars.presence.state = "In Launcher"; + GlobalVars.presence.details = "Selected " + clientname; + GlobalVars.presence.largeImageText = GlobalVars.UserConfiguration.PlayerName + " | Novetus " + GlobalVars.ProgramInformation.Version; + GlobalVars.presence.smallImageText = "In Launcher"; break; - case Settings.Level.VeryLow: - AA = 2; - MeshDetail = 50; - ShadingQuality = 50; - GFXQualityLevel = 1; - MaterialQuality = 1; - AASamples = 1; - Bevels = 2; - Shadows_2008 = 2; - Shadows_2007 = false; + case GlobalVars.LauncherState.InMPGame: + GlobalVars.presence.smallImageKey = GlobalVars.image_ingame; + GlobalVars.presence.details = ValidMapname; + GlobalVars.presence.state = "In " + clientname + " Multiplayer Game"; + GlobalVars.presence.largeImageText = GlobalVars.UserConfiguration.PlayerName + " | Novetus " + GlobalVars.ProgramInformation.Version; + GlobalVars.presence.smallImageText = "In " + clientname + " Multiplayer Game"; break; - case Settings.Level.Low: - AA = 2; - MeshDetail = 50; - ShadingQuality = 50; - GFXQualityLevel = 5; - MaterialQuality = 1; - AASamples = 1; - Bevels = 2; - Shadows_2008 = 2; - Shadows_2007 = false; + case GlobalVars.LauncherState.InSoloGame: + GlobalVars.presence.smallImageKey = GlobalVars.image_ingame; + GlobalVars.presence.details = ValidMapname; + GlobalVars.presence.state = "In " + clientname + " Solo Game"; + GlobalVars.presence.largeImageText = GlobalVars.UserConfiguration.PlayerName + " | Novetus " + GlobalVars.ProgramInformation.Version; + GlobalVars.presence.smallImageText = "In " + clientname + " Solo Game"; break; - case Settings.Level.Medium: - MeshDetail = 75; - ShadingQuality = 75; - GFXQualityLevel = 10; - MaterialQuality = 2; - AASamples = 4; - Bevels = 2; - if (info.ClientLoadOptions == Settings.ClientLoadOptions.Client_2008AndUp_ForceAutomatic || - info.ClientLoadOptions == Settings.ClientLoadOptions.Client_2008AndUp_ForceAutomaticQL21 || - info.ClientLoadOptions == Settings.ClientLoadOptions.Client_2008AndUp_QualityLevel21 || - info.ClientLoadOptions == Settings.ClientLoadOptions.Client_2008AndUp_HasCharacterOnlyShadowsLegacyOpenGL) - { - Shadows_2008 = 3; - } - Shadows_2007 = false; + case GlobalVars.LauncherState.InStudio: + GlobalVars.presence.smallImageKey = GlobalVars.image_instudio; + GlobalVars.presence.details = ValidMapname; + GlobalVars.presence.state = "In " + clientname + " Studio"; + GlobalVars.presence.largeImageText = GlobalVars.UserConfiguration.PlayerName + " | Novetus " + GlobalVars.ProgramInformation.Version; + GlobalVars.presence.smallImageText = "In " + clientname + " Studio"; break; - case Settings.Level.High: - MeshDetail = 75; - ShadingQuality = 75; - GFXQualityLevel = 15; - AASamples = 4; + case GlobalVars.LauncherState.InCustomization: + GlobalVars.presence.smallImageKey = GlobalVars.image_incustomization; + GlobalVars.presence.details = "Customizing " + GlobalVars.UserConfiguration.PlayerName; + GlobalVars.presence.state = "In Character Customization"; + GlobalVars.presence.largeImageText = GlobalVars.UserConfiguration.PlayerName + " | Novetus " + GlobalVars.ProgramInformation.Version; + GlobalVars.presence.smallImageText = "In Character Customization"; + break; + case GlobalVars.LauncherState.InEasterEggGame: + GlobalVars.presence.smallImageKey = GlobalVars.image_ingame; + GlobalVars.presence.details = ValidMapname; + GlobalVars.presence.state = "Reading a message."; + GlobalVars.presence.largeImageText = GlobalVars.UserConfiguration.PlayerName + " | Novetus " + GlobalVars.ProgramInformation.Version; + GlobalVars.presence.smallImageText = "Reading a message."; + break; + case GlobalVars.LauncherState.LoadingURI: + GlobalVars.presence.smallImageKey = GlobalVars.image_ingame; + GlobalVars.presence.details = ValidMapname; + GlobalVars.presence.state = "Joining a " + clientname + " Multiplayer Game"; + GlobalVars.presence.largeImageText = GlobalVars.UserConfiguration.PlayerName + " | Novetus " + GlobalVars.ProgramInformation.Version; + GlobalVars.presence.smallImageText = "Joining a " + clientname + " Multiplayer Game"; break; - case Settings.Level.Ultra: default: break; } - ApplyClientSettings(info, ClientName, GraphicsMode, MeshDetail, ShadingQuality, MaterialQuality, AA, AASamples, Bevels, - Shadows_2008, Shadows_2007, "", GFXQualityLevel, "800x600", "1024x768", 0); + DiscordRPC.UpdatePresence(ref GlobalVars.presence); } - else + } + + public static void ChangeGameSettings(string ClientName) + { + try + { + FileFormat.ClientInfo info = GetClientInfoValues(ClientName); + + string filterPath = GlobalPaths.ConfigDir + @"\\" + GlobalPaths.FileDeleteFilterName; + string[] fileListToDelete = File.ReadAllLines(filterPath); + + foreach (string file in fileListToDelete) + { + string fullFilePath = Settings.GetPathForClientLoadOptions(info.ClientLoadOptions) + @"\" + file; + Util.FixedFileDelete(fullFilePath); + } + + if (GlobalVars.UserConfiguration.QualityLevel != Settings.Level.Custom) + { + int GraphicsMode = 0; + + if (info.ClientLoadOptions == Settings.ClientLoadOptions.Client_2008AndUp_ForceAutomaticQL21 || + info.ClientLoadOptions == Settings.ClientLoadOptions.Client_2008AndUp_ForceAutomatic) + { + GraphicsMode = 1; + } + else + { + if (info.ClientLoadOptions != Settings.ClientLoadOptions.Client_2007_NoGraphicsOptions || + info.ClientLoadOptions != Settings.ClientLoadOptions.Client_2008AndUp_NoGraphicsOptions) + { + + switch (GlobalVars.UserConfiguration.GraphicsMode) + { + case Settings.Mode.OpenGLStable: + switch (info.ClientLoadOptions) + { + case Settings.ClientLoadOptions.Client_2007: + case Settings.ClientLoadOptions.Client_2008AndUp_LegacyOpenGL: + case Settings.ClientLoadOptions.Client_2008AndUp_HasCharacterOnlyShadowsLegacyOpenGL: + GraphicsMode = 2; + break; + case Settings.ClientLoadOptions.Client_2008AndUp: + case Settings.ClientLoadOptions.Client_2008AndUp_QualityLevel21: + GraphicsMode = 4; + break; + default: + break; + } + break; + case Settings.Mode.OpenGLExperimental: + GraphicsMode = 4; + break; + case Settings.Mode.DirectX: + GraphicsMode = 3; + break; + default: + GraphicsMode = 1; + break; + } + } + } + + //default values are ultra settings + int MeshDetail = 100; + int ShadingQuality = 100; + int GFXQualityLevel = 19; + if (info.ClientLoadOptions == Settings.ClientLoadOptions.Client_2008AndUp_ForceAutomaticQL21 || + info.ClientLoadOptions == Settings.ClientLoadOptions.Client_2008AndUp_QualityLevel21) + { + GFXQualityLevel = 21; + } + int MaterialQuality = 3; + int AASamples = 8; + int Bevels = 1; + int Shadows_2008 = 1; + int AA = 1; + bool Shadows_2007 = true; + + switch (GlobalVars.UserConfiguration.QualityLevel) + { + case Settings.Level.Automatic: + //set everything to automatic. Some ultra settings will still be enabled. + AA = 0; + Bevels = 0; + Shadows_2008 = 0; + GFXQualityLevel = 0; + MaterialQuality = 0; + Shadows_2007 = false; + break; + case Settings.Level.VeryLow: + AA = 2; + MeshDetail = 50; + ShadingQuality = 50; + GFXQualityLevel = 1; + MaterialQuality = 1; + AASamples = 1; + Bevels = 2; + Shadows_2008 = 2; + Shadows_2007 = false; + break; + case Settings.Level.Low: + AA = 2; + MeshDetail = 50; + ShadingQuality = 50; + GFXQualityLevel = 5; + MaterialQuality = 1; + AASamples = 1; + Bevels = 2; + Shadows_2008 = 2; + Shadows_2007 = false; + break; + case Settings.Level.Medium: + MeshDetail = 75; + ShadingQuality = 75; + GFXQualityLevel = 10; + MaterialQuality = 2; + AASamples = 4; + Bevels = 2; + if (info.ClientLoadOptions == Settings.ClientLoadOptions.Client_2008AndUp_ForceAutomatic || + info.ClientLoadOptions == Settings.ClientLoadOptions.Client_2008AndUp_ForceAutomaticQL21 || + info.ClientLoadOptions == Settings.ClientLoadOptions.Client_2008AndUp_QualityLevel21 || + info.ClientLoadOptions == Settings.ClientLoadOptions.Client_2008AndUp_HasCharacterOnlyShadowsLegacyOpenGL) + { + Shadows_2008 = 3; + } + Shadows_2007 = false; + break; + case Settings.Level.High: + MeshDetail = 75; + ShadingQuality = 75; + GFXQualityLevel = 15; + AASamples = 4; + break; + case Settings.Level.Ultra: + default: + break; + } + + ApplyClientSettings(info, ClientName, GraphicsMode, MeshDetail, ShadingQuality, MaterialQuality, AA, AASamples, Bevels, + Shadows_2008, Shadows_2007, "", GFXQualityLevel, "800x600", "1024x768", 0); + } + else + { + //save graphics mode. + int GraphicsMode = 0; + + if (info.ClientLoadOptions == Settings.ClientLoadOptions.Client_2008AndUp_ForceAutomaticQL21 || + info.ClientLoadOptions == Settings.ClientLoadOptions.Client_2008AndUp_ForceAutomatic) + { + GraphicsMode = 1; + } + else + { + if (info.ClientLoadOptions != Settings.ClientLoadOptions.Client_2007_NoGraphicsOptions || + info.ClientLoadOptions != Settings.ClientLoadOptions.Client_2008AndUp_NoGraphicsOptions) + { + + switch (GlobalVars.UserConfiguration.GraphicsMode) + { + case Settings.Mode.OpenGLStable: + switch (info.ClientLoadOptions) + { + case Settings.ClientLoadOptions.Client_2007: + case Settings.ClientLoadOptions.Client_2008AndUp_LegacyOpenGL: + case Settings.ClientLoadOptions.Client_2008AndUp_HasCharacterOnlyShadowsLegacyOpenGL: + GraphicsMode = 2; + break; + case Settings.ClientLoadOptions.Client_2008AndUp: + case Settings.ClientLoadOptions.Client_2008AndUp_QualityLevel21: + GraphicsMode = 4; + break; + default: + break; + } + break; + case Settings.Mode.OpenGLExperimental: + GraphicsMode = 4; + break; + case Settings.Mode.DirectX: + GraphicsMode = 3; + break; + default: + GraphicsMode = 1; + break; + } + } + } + + ApplyClientSettings(info, ClientName, GraphicsMode, 0, 0, 0, 0, 0, 0, 0, false, "", 0, "800x600", "1024x768", 0, true); + + //just copy the file. + string terms = "_" + ClientName; + string[] dirs = Directory.GetFiles(GlobalPaths.ConfigDirClients); + + foreach (string dir in dirs) + { + if (dir.Contains(terms) && !dir.Contains("_default")) + { + Util.FixedFileCopy(dir, Settings.GetPathForClientLoadOptions(info.ClientLoadOptions) + @"\" + Path.GetFileName(dir).Replace(terms, "") + .Replace(dir.Substring(dir.LastIndexOf('-') + 1), "") + .Replace("-", ".xml"), true); + } + } + } + } +#if URI || LAUNCHER || BASICLAUNCHER + catch (Exception ex) + { + Util.LogExceptions(ex); +#else + catch (Exception) + { +#endif + return; + } + } + + //oh god.... + //we're using this one for custom graphics quality. Better than the latter. + public static void ApplyClientSettings_custom(FileFormat.ClientInfo info, string ClientName, int MeshDetail, int ShadingQuality, int MaterialQuality, + int AA, int AASamples, int Bevels, int Shadows_2008, bool Shadows_2007, string Style_2007, int GFXQualityLevel, string WindowResolution, string FullscreenResolution, + int ModernResolution) + { + try { - //save graphics mode. int GraphicsMode = 0; if (info.ClientLoadOptions == Settings.ClientLoadOptions.Client_2008AndUp_ForceAutomaticQL21 || @@ -581,7 +664,6 @@ public class ClientManagement if (info.ClientLoadOptions != Settings.ClientLoadOptions.Client_2007_NoGraphicsOptions || info.ClientLoadOptions != Settings.ClientLoadOptions.Client_2008AndUp_NoGraphicsOptions) { - switch (GlobalVars.UserConfiguration.GraphicsMode) { case Settings.Mode.OpenGLStable: @@ -613,9 +695,31 @@ public class ClientManagement } } - ApplyClientSettings(info, ClientName, GraphicsMode, 0, 0, 0, 0, 0, 0, 0, false, "", 0, "800x600", "1024x768", 0, true); + ApplyClientSettings(info, ClientName, GraphicsMode, MeshDetail, ShadingQuality, MaterialQuality, + AA, AASamples, Bevels, Shadows_2008, Shadows_2007, Style_2007, GFXQualityLevel, WindowResolution, FullscreenResolution, ModernResolution); + } +#if URI || LAUNCHER || BASICLAUNCHER + catch (Exception ex) + { + Util.LogExceptions(ex); +#else + catch (Exception) + { +#endif + return; + } + } + + //it's worse. + public static void ApplyClientSettings(FileFormat.ClientInfo info, string ClientName, int GraphicsMode, int MeshDetail, int ShadingQuality, int MaterialQuality, + int AA, int AASamples, int Bevels, int Shadows_2008, bool Shadows_2007, string Style_2007, int GFXQualityLevel, string WindowResolution, string FullscreenResolution, + int ModernResolution, bool onlyGraphicsMode = false) + { + try + { + string winRes = WindowResolution; + string fullRes = FullscreenResolution; - //just copy the file. string terms = "_" + ClientName; string[] dirs = Directory.GetFiles(GlobalPaths.ConfigDirClients); @@ -623,362 +727,260 @@ public class ClientManagement { if (dir.Contains(terms) && !dir.Contains("_default")) { - Util.FixedFileCopy(dir, Settings.GetPathForClientLoadOptions(info.ClientLoadOptions) + @"\" + Path.GetFileName(dir).Replace(terms, "") - .Replace(dir.Substring(dir.LastIndexOf('-') + 1), "") - .Replace("-", ".xml"), true); - } - } - } - } + string oldfile = ""; + string fixedfile = ""; + XDocument doc = null; + + try + { + oldfile = File.ReadAllText(dir); + fixedfile = RobloxXML.RemoveInvalidXmlChars(RobloxXML.ReplaceHexadecimalSymbols(oldfile)); + doc = XDocument.Parse(fixedfile); + } #if URI || LAUNCHER || BASICLAUNCHER - catch (Exception ex) - { - Util.LogExceptions(ex); + catch (Exception ex) + { + Util.LogExceptions(ex); #else - catch (Exception) - { + catch (Exception) + { #endif - return; - } - } + return; + } - //oh god.... - //we're using this one for custom graphics quality. Better than the latter. - public static void ApplyClientSettings_custom(FileFormat.ClientInfo info, string ClientName, int MeshDetail, int ShadingQuality, int MaterialQuality, - int AA, int AASamples, int Bevels, int Shadows_2008, bool Shadows_2007, string Style_2007, int GFXQualityLevel, string WindowResolution, string FullscreenResolution, - int ModernResolution) - { - try - { - int GraphicsMode = 0; - - if (info.ClientLoadOptions == Settings.ClientLoadOptions.Client_2008AndUp_ForceAutomaticQL21 || - info.ClientLoadOptions == Settings.ClientLoadOptions.Client_2008AndUp_ForceAutomatic) - { - GraphicsMode = 1; - } - else - { - if (info.ClientLoadOptions != Settings.ClientLoadOptions.Client_2007_NoGraphicsOptions || - info.ClientLoadOptions != Settings.ClientLoadOptions.Client_2008AndUp_NoGraphicsOptions) - { - switch (GlobalVars.UserConfiguration.GraphicsMode) - { - case Settings.Mode.OpenGLStable: - switch (info.ClientLoadOptions) + try + { + if (GraphicsMode != 0) { - case Settings.ClientLoadOptions.Client_2007: - case Settings.ClientLoadOptions.Client_2008AndUp_LegacyOpenGL: - case Settings.ClientLoadOptions.Client_2008AndUp_HasCharacterOnlyShadowsLegacyOpenGL: - GraphicsMode = 2; - break; - case Settings.ClientLoadOptions.Client_2008AndUp: - case Settings.ClientLoadOptions.Client_2008AndUp_QualityLevel21: - GraphicsMode = 4; - break; - default: - break; + RobloxXML.EditRenderSettings(doc, "graphicsMode", GraphicsMode.ToString(), XMLTypes.Token); } - break; - case Settings.Mode.OpenGLExperimental: - GraphicsMode = 4; - break; - case Settings.Mode.DirectX: - GraphicsMode = 3; - break; - default: - GraphicsMode = 1; - break; - } - } - } - ApplyClientSettings(info, ClientName, GraphicsMode, MeshDetail, ShadingQuality, MaterialQuality, - AA, AASamples, Bevels, Shadows_2008, Shadows_2007, Style_2007, GFXQualityLevel, WindowResolution, FullscreenResolution, ModernResolution); - } + if (!onlyGraphicsMode) + { + RobloxXML.EditRenderSettings(doc, "maxMeshDetail", MeshDetail.ToString(), XMLTypes.Float); + RobloxXML.EditRenderSettings(doc, "maxShadingQuality", ShadingQuality.ToString(), XMLTypes.Float); + RobloxXML.EditRenderSettings(doc, "minMeshDetail", MeshDetail.ToString(), XMLTypes.Float); + RobloxXML.EditRenderSettings(doc, "minShadingQuality", ShadingQuality.ToString(), XMLTypes.Float); + RobloxXML.EditRenderSettings(doc, "AluminumQuality", MaterialQuality.ToString(), XMLTypes.Token); + RobloxXML.EditRenderSettings(doc, "CompoundMaterialQuality", MaterialQuality.ToString(), XMLTypes.Token); + RobloxXML.EditRenderSettings(doc, "CorrodedMetalQuality", MaterialQuality.ToString(), XMLTypes.Token); + RobloxXML.EditRenderSettings(doc, "DiamondPlateQuality", MaterialQuality.ToString(), XMLTypes.Token); + RobloxXML.EditRenderSettings(doc, "GrassQuality", MaterialQuality.ToString(), XMLTypes.Token); + RobloxXML.EditRenderSettings(doc, "IceQuality", MaterialQuality.ToString(), XMLTypes.Token); + RobloxXML.EditRenderSettings(doc, "PlasticQuality", MaterialQuality.ToString(), XMLTypes.Token); + RobloxXML.EditRenderSettings(doc, "SlateQuality", MaterialQuality.ToString(), XMLTypes.Token); + // fix truss detail. We're keeping it at 0. + RobloxXML.EditRenderSettings(doc, "TrussDetail", MaterialQuality.ToString(), XMLTypes.Token); + RobloxXML.EditRenderSettings(doc, "WoodQuality", MaterialQuality.ToString(), XMLTypes.Token); + RobloxXML.EditRenderSettings(doc, "Antialiasing", AA.ToString(), XMLTypes.Token); + RobloxXML.EditRenderSettings(doc, "AASamples", AASamples.ToString(), XMLTypes.Token); + RobloxXML.EditRenderSettings(doc, "Bevels", Bevels.ToString(), XMLTypes.Token); + RobloxXML.EditRenderSettings(doc, "Shadow", Shadows_2008.ToString(), XMLTypes.Token); + RobloxXML.EditRenderSettings(doc, "Shadows", Shadows_2007.ToString().ToLower(), XMLTypes.Bool); + RobloxXML.EditRenderSettings(doc, "shadows", Shadows_2007.ToString().ToLower(), XMLTypes.Bool); + RobloxXML.EditRenderSettings(doc, "_skinFile", !string.IsNullOrWhiteSpace(Style_2007) ? @"Styles\" + Style_2007 : "", XMLTypes.String); + RobloxXML.EditRenderSettings(doc, "QualityLevel", GFXQualityLevel.ToString(), XMLTypes.Token); + RobloxXML.EditRenderSettings(doc, "FullscreenSizePreference", fullRes.ToString(), XMLTypes.Vector2Int16); + RobloxXML.EditRenderSettings(doc, "FullscreenSize", fullRes.ToString(), XMLTypes.Vector2Int16); + RobloxXML.EditRenderSettings(doc, "WindowSizePreference", winRes.ToString(), XMLTypes.Vector2Int16); + RobloxXML.EditRenderSettings(doc, "WindowSize", winRes.ToString(), XMLTypes.Vector2Int16); + RobloxXML.EditRenderSettings(doc, "Resolution", ModernResolution.ToString(), XMLTypes.Token); + } + } #if URI || LAUNCHER || BASICLAUNCHER - catch (Exception ex) - { - Util.LogExceptions(ex); -#else - catch (Exception) - { -#endif - return; - } - } - - //it's worse. - public static void ApplyClientSettings(FileFormat.ClientInfo info, string ClientName, int GraphicsMode, int MeshDetail, int ShadingQuality, int MaterialQuality, - int AA, int AASamples, int Bevels, int Shadows_2008, bool Shadows_2007, string Style_2007, int GFXQualityLevel, string WindowResolution, string FullscreenResolution, - int ModernResolution, bool onlyGraphicsMode = false) - { - try - { - string winRes = WindowResolution; - string fullRes = FullscreenResolution; - - string terms = "_" + ClientName; - string[] dirs = Directory.GetFiles(GlobalPaths.ConfigDirClients); - - foreach (string dir in dirs) - { - if (dir.Contains(terms) && !dir.Contains("_default")) - { - string oldfile = ""; - string fixedfile = ""; - XDocument doc = null; - - try - { - oldfile = File.ReadAllText(dir); - fixedfile = RobloxXML.RemoveInvalidXmlChars(RobloxXML.ReplaceHexadecimalSymbols(oldfile)); - doc = XDocument.Parse(fixedfile); - } -#if URI || LAUNCHER || BASICLAUNCHER - catch (Exception ex) - { - Util.LogExceptions(ex); + catch (Exception ex) + { + Util.LogExceptions(ex); #else catch (Exception) { #endif - return; - } - - try - { - if (GraphicsMode != 0) - { - RobloxXML.EditRenderSettings(doc, "graphicsMode", GraphicsMode.ToString(), XMLTypes.Token); + return; } - - if (!onlyGraphicsMode) + finally { - RobloxXML.EditRenderSettings(doc, "maxMeshDetail", MeshDetail.ToString(), XMLTypes.Float); - RobloxXML.EditRenderSettings(doc, "maxShadingQuality", ShadingQuality.ToString(), XMLTypes.Float); - RobloxXML.EditRenderSettings(doc, "minMeshDetail", MeshDetail.ToString(), XMLTypes.Float); - RobloxXML.EditRenderSettings(doc, "minShadingQuality", ShadingQuality.ToString(), XMLTypes.Float); - RobloxXML.EditRenderSettings(doc, "AluminumQuality", MaterialQuality.ToString(), XMLTypes.Token); - RobloxXML.EditRenderSettings(doc, "CompoundMaterialQuality", MaterialQuality.ToString(), XMLTypes.Token); - RobloxXML.EditRenderSettings(doc, "CorrodedMetalQuality", MaterialQuality.ToString(), XMLTypes.Token); - RobloxXML.EditRenderSettings(doc, "DiamondPlateQuality", MaterialQuality.ToString(), XMLTypes.Token); - RobloxXML.EditRenderSettings(doc, "GrassQuality", MaterialQuality.ToString(), XMLTypes.Token); - RobloxXML.EditRenderSettings(doc, "IceQuality", MaterialQuality.ToString(), XMLTypes.Token); - RobloxXML.EditRenderSettings(doc, "PlasticQuality", MaterialQuality.ToString(), XMLTypes.Token); - RobloxXML.EditRenderSettings(doc, "SlateQuality", MaterialQuality.ToString(), XMLTypes.Token); - // fix truss detail. We're keeping it at 0. - RobloxXML.EditRenderSettings(doc, "TrussDetail", MaterialQuality.ToString(), XMLTypes.Token); - RobloxXML.EditRenderSettings(doc, "WoodQuality", MaterialQuality.ToString(), XMLTypes.Token); - RobloxXML.EditRenderSettings(doc, "Antialiasing", AA.ToString(), XMLTypes.Token); - RobloxXML.EditRenderSettings(doc, "AASamples", AASamples.ToString(), XMLTypes.Token); - RobloxXML.EditRenderSettings(doc, "Bevels", Bevels.ToString(), XMLTypes.Token); - RobloxXML.EditRenderSettings(doc, "Shadow", Shadows_2008.ToString(), XMLTypes.Token); - RobloxXML.EditRenderSettings(doc, "Shadows", Shadows_2007.ToString().ToLower(), XMLTypes.Bool); - RobloxXML.EditRenderSettings(doc, "shadows", Shadows_2007.ToString().ToLower(), XMLTypes.Bool); - RobloxXML.EditRenderSettings(doc, "_skinFile", !string.IsNullOrWhiteSpace(Style_2007) ? @"Styles\" + Style_2007 : "", XMLTypes.String); - RobloxXML.EditRenderSettings(doc, "QualityLevel", GFXQualityLevel.ToString(), XMLTypes.Token); - RobloxXML.EditRenderSettings(doc, "FullscreenSizePreference", fullRes.ToString(), XMLTypes.Vector2Int16); - RobloxXML.EditRenderSettings(doc, "FullscreenSize", fullRes.ToString(), XMLTypes.Vector2Int16); - RobloxXML.EditRenderSettings(doc, "WindowSizePreference", winRes.ToString(), XMLTypes.Vector2Int16); - RobloxXML.EditRenderSettings(doc, "WindowSize", winRes.ToString(), XMLTypes.Vector2Int16); - RobloxXML.EditRenderSettings(doc, "Resolution", ModernResolution.ToString(), XMLTypes.Token); + doc.Save(dir); + Util.FixedFileCopy(dir, Settings.GetPathForClientLoadOptions(info.ClientLoadOptions) + @"\" + Path.GetFileName(dir).Replace(terms, "") + .Replace(dir.Substring(dir.LastIndexOf('-') + 1), "") + .Replace("-", ".xml"), true); } } -#if URI || LAUNCHER || BASICLAUNCHER - catch (Exception ex) - { - Util.LogExceptions(ex); -#else - catch (Exception) - { -#endif - return; - } - finally - { - doc.Save(dir); - Util.FixedFileCopy(dir, Settings.GetPathForClientLoadOptions(info.ClientLoadOptions) + @"\" + Path.GetFileName(dir).Replace(terms, "") - .Replace(dir.Substring(dir.LastIndexOf('-') + 1), "") - .Replace("-", ".xml"), true); - } } } - } #if URI || LAUNCHER || BASICLAUNCHER - catch (Exception ex) - { - Util.LogExceptions(ex); + catch (Exception ex) + { + Util.LogExceptions(ex); #else catch (Exception) { #endif - return; - } - } - - public static string GetGenLuaFileName(string ClientName, ScriptType type) - { - string luafile = ""; - - bool rbxasset = GlobalVars.SelectedClientInfo.CommandLineArgs.Contains("%userbxassetforgeneration%"); - - if (!rbxasset) - { - if (GlobalVars.SelectedClientInfo.SeperateFolders) - { - luafile = GlobalPaths.ClientDir + @"\\" + ClientName + @"\\" + GetClientSeperateFolderName(type) + @"\\content\\scripts\\" + GlobalPaths.ScriptGenName + ".lua"; - } - else - { - luafile = GlobalPaths.ClientDir + @"\\" + ClientName + @"\\content\\scripts\\" + GlobalPaths.ScriptGenName + ".lua"; + return; } } - else + + public static string GetGenLuaFileName(string ClientName, ScriptType type) { - luafile = @"rbxasset://scripts\\" + GlobalPaths.ScriptGenName + ".lua"; - } + string luafile = ""; - return luafile; - } + bool rbxasset = GlobalVars.SelectedClientInfo.CommandLineArgs.Contains("%userbxassetforgeneration%"); - public static string GetLuaFileName(ScriptType type) - { - return GetLuaFileName(GlobalVars.UserConfiguration.SelectedClient, type); - } - - public static string GetLuaFileName(string ClientName, ScriptType type) - { - string luafile = ""; - - if (!GlobalVars.SelectedClientInfo.Fix2007) - { - bool HasGenerateScript = false; - - foreach (string line in GlobalVars.SelectedClientInfo.CommandLineArgs.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)) + if (!rbxasset) { - if (line.Contains("%generatescript%")) + if (GlobalVars.SelectedClientInfo.SeperateFolders) { - HasGenerateScript = true; + luafile = GlobalPaths.ClientDir + @"\\" + ClientName + @"\\" + GetClientSeperateFolderName(type) + @"\\content\\scripts\\" + GlobalPaths.ScriptGenName + ".lua"; + } + else + { + luafile = GlobalPaths.ClientDir + @"\\" + ClientName + @"\\content\\scripts\\" + GlobalPaths.ScriptGenName + ".lua"; } } - - if (HasGenerateScript) + else { - luafile = ScriptFuncs.Generator.GetGeneratedScriptName(ClientName, type); + luafile = @"rbxasset://scripts\\" + GlobalPaths.ScriptGenName + ".lua"; + } + + return luafile; + } + + public static string GetLuaFileName(ScriptType type) + { + return GetLuaFileName(GlobalVars.UserConfiguration.SelectedClient, type); + } + + public static string GetLuaFileName(string ClientName, ScriptType type) + { + string luafile = ""; + + if (!GlobalVars.SelectedClientInfo.Fix2007) + { + bool HasGenerateScript = false; + + foreach (string line in GlobalVars.SelectedClientInfo.CommandLineArgs.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)) + { + if (line.Contains("%generatescript%")) + { + HasGenerateScript = true; + } + } + + if (HasGenerateScript) + { + luafile = ScriptFuncs.Generator.GetGeneratedScriptName(ClientName, type); + } + else + { + luafile = "rbxasset://scripts\\\\" + GlobalPaths.ScriptName + ".lua"; + } } else { - luafile = "rbxasset://scripts\\\\" + GlobalPaths.ScriptName + ".lua"; + luafile = GetGenLuaFileName(ClientName, type); } - } - else - { - luafile = GetGenLuaFileName(ClientName, type); + + return luafile; } - return luafile; - } - - public static string GetClientSeperateFolderName(ScriptType type) - { - string rbxfolder = ""; - switch (type) - { - case ScriptType.Client: - case ScriptType.Solo: - case ScriptType.EasterEgg: - rbxfolder = "client"; - break; - case ScriptType.Server: - rbxfolder = "server"; - break; - case ScriptType.Studio: - rbxfolder = "studio"; - break; - case ScriptType.None: - default: - rbxfolder = ""; - break; - } - - return rbxfolder; - } - - public static string GetClientEXEDir(ScriptType type) - { - return GetClientEXEDir(GlobalVars.UserConfiguration.SelectedClient, type); - } - - public static string GetClientEXEDir(string ClientName, ScriptType type) - { - string rbxexe = ""; - string BasePath = GlobalPaths.ClientDir + @"\\" + ClientName; - if (GlobalVars.SelectedClientInfo.LegacyMode) - { - rbxexe = BasePath + @"\\RobloxApp.exe"; - } - else if (GlobalVars.SelectedClientInfo.UsesCustomClientEXEName) - { - rbxexe = BasePath + @"\\" + GlobalVars.SelectedClientInfo.CustomClientEXEName; - } - else if (GlobalVars.SelectedClientInfo.SeperateFolders) + public static string GetClientSeperateFolderName(ScriptType type) { + string rbxfolder = ""; switch (type) { case ScriptType.Client: case ScriptType.Solo: case ScriptType.EasterEgg: - rbxexe = BasePath + @"\\" + GetClientSeperateFolderName(type) + @"\\RobloxApp_client.exe"; + rbxfolder = "client"; break; case ScriptType.Server: - rbxexe = BasePath + @"\\" + GetClientSeperateFolderName(type) + @"\\RobloxApp_server.exe"; + rbxfolder = "server"; break; case ScriptType.Studio: - rbxexe = BasePath + @"\\" + GetClientSeperateFolderName(type) + @"\\RobloxApp_studio.exe"; + rbxfolder = "studio"; break; case ScriptType.None: default: - rbxexe = BasePath + @"\\RobloxApp.exe"; - break; - } - } - else - { - switch (type) - { - case ScriptType.Client: - rbxexe = BasePath + @"\\RobloxApp_client.exe"; - break; - case ScriptType.Server: - rbxexe = BasePath + @"\\RobloxApp_server.exe"; - break; - case ScriptType.Studio: - rbxexe = BasePath + @"\\RobloxApp_studio.exe"; - break; - case ScriptType.Solo: - case ScriptType.EasterEgg: - rbxexe = BasePath + @"\\RobloxApp_solo.exe"; - break; - case ScriptType.None: - default: - rbxexe = BasePath + @"\\RobloxApp.exe"; + rbxfolder = ""; break; } + + return rbxfolder; } - return rbxexe; - } + public static string GetClientEXEDir(ScriptType type) + { + return GetClientEXEDir(GlobalVars.UserConfiguration.SelectedClient, type); + } + + public static string GetClientEXEDir(string ClientName, ScriptType type) + { + string rbxexe = ""; + string BasePath = GlobalPaths.ClientDir + @"\\" + ClientName; + if (GlobalVars.SelectedClientInfo.LegacyMode) + { + rbxexe = BasePath + @"\\RobloxApp.exe"; + } + else if (GlobalVars.SelectedClientInfo.UsesCustomClientEXEName) + { + rbxexe = BasePath + @"\\" + GlobalVars.SelectedClientInfo.CustomClientEXEName; + } + else if (GlobalVars.SelectedClientInfo.SeperateFolders) + { + switch (type) + { + case ScriptType.Client: + case ScriptType.Solo: + case ScriptType.EasterEgg: + rbxexe = BasePath + @"\\" + GetClientSeperateFolderName(type) + @"\\RobloxApp_client.exe"; + break; + case ScriptType.Server: + rbxexe = BasePath + @"\\" + GetClientSeperateFolderName(type) + @"\\RobloxApp_server.exe"; + break; + case ScriptType.Studio: + rbxexe = BasePath + @"\\" + GetClientSeperateFolderName(type) + @"\\RobloxApp_studio.exe"; + break; + case ScriptType.None: + default: + rbxexe = BasePath + @"\\RobloxApp.exe"; + break; + } + } + else + { + switch (type) + { + case ScriptType.Client: + rbxexe = BasePath + @"\\RobloxApp_client.exe"; + break; + case ScriptType.Server: + rbxexe = BasePath + @"\\RobloxApp_server.exe"; + break; + case ScriptType.Studio: + rbxexe = BasePath + @"\\RobloxApp_studio.exe"; + break; + case ScriptType.Solo: + case ScriptType.EasterEgg: + rbxexe = BasePath + @"\\RobloxApp_solo.exe"; + break; + case ScriptType.None: + default: + rbxexe = BasePath + @"\\RobloxApp.exe"; + break; + } + } + + return rbxexe; + } #if URI - public static void UpdateStatus(Label label, string status) - { - Util.LogPrint(status); - if (label != null) + public static void UpdateStatus(Label label, string status) { - label.Text = status; + Util.LogPrint(status); + if (label != null) + { + label.Text = status; + } } - } #endif #if LAUNCHER @@ -1012,36 +1014,36 @@ public class ClientManagement #endif #if URI - public static void LaunchRBXClient(ScriptType type, bool no3d, bool nomap, EventHandler e, Label label) + public static void LaunchRBXClient(ScriptType type, bool no3d, bool nomap, EventHandler e, Label label) #else public static void LaunchRBXClient(ScriptType type, bool no3d, bool nomap, EventHandler e) #endif - { + { #if URI - LaunchRBXClient(GlobalVars.UserConfiguration.SelectedClient, type, no3d, nomap, e, label); + LaunchRBXClient(GlobalVars.UserConfiguration.SelectedClient, type, no3d, nomap, e, label); #else LaunchRBXClient(GlobalVars.UserConfiguration.SelectedClient, type, no3d, nomap, e); #endif - } + } #if URI - public static void ValidateFiles(string line, string validstart, string validend, Label label) + public static void ValidateFiles(string line, string validstart, string validend, Label label) #else public static void ValidateFiles(string line, string validstart, string validend) #endif - { - string extractedFile = ScriptFuncs.ClientScript.GetArgsFromTag(line, validstart, validend); - if (!string.IsNullOrWhiteSpace(extractedFile)) { - string[] parsedFileParams = extractedFile.Split('|'); - string filePath = parsedFileParams[0]; - string fileMD5 = parsedFileParams[1]; - string fullFilePath = GlobalPaths.ClientDir + @"\\" + GlobalVars.UserConfiguration.SelectedClient + @"\\" + filePath; - - if (!SecurityFuncs.CheckMD5(fileMD5, fullFilePath)) + string extractedFile = ScriptFuncs.ClientScript.GetArgsFromTag(line, validstart, validend); + if (!string.IsNullOrWhiteSpace(extractedFile)) { + string[] parsedFileParams = extractedFile.Split('|'); + string filePath = parsedFileParams[0]; + string fileMD5 = parsedFileParams[1]; + string fullFilePath = GlobalPaths.ClientDir + @"\\" + GlobalVars.UserConfiguration.SelectedClient + @"\\" + filePath; + + if (!SecurityFuncs.CheckMD5(fileMD5, fullFilePath)) + { #if URI - UpdateStatus(label, "The client has been detected as modified."); + UpdateStatus(label, "The client has been detected as modified."); #elif LAUNCHER Util.ConsolePrint("ERROR - Failed to launch Novetus. (The client has been detected as modified.)", 2); #endif @@ -1054,41 +1056,41 @@ public class ClientManagement #endif #if URI - throw new IOException("The client has been detected as modified."); + throw new IOException("The client has been detected as modified."); #else return; #endif - } - else - { - GlobalVars.ValidatedExtraFiles += 1; + } + else + { + GlobalVars.ValidatedExtraFiles += 1; + } } } - } #if URI - public static void LaunchRBXClient(string ClientName, ScriptType type, bool no3d, bool nomap, EventHandler e, Label label) + public static void LaunchRBXClient(string ClientName, ScriptType type, bool no3d, bool nomap, EventHandler e, Label label) #else public static void LaunchRBXClient(string ClientName, ScriptType type, bool no3d, bool nomap, EventHandler e) #endif - { - #if LAUNCHER - DecompressMap(type, nomap); - #endif - - switch (type) { - case ScriptType.Client: - FileManagement.ReloadLoadoutValue(true); - if (!GlobalVars.LocalPlayMode && GlobalVars.GameOpened != ScriptType.Server) - { - goto default; - } - break; - case ScriptType.Server: - if (GlobalVars.GameOpened == ScriptType.Server) - { - Util.ConsolePrint("ERROR - Failed to launch Novetus. (A server is already running.)", 2); +#if LAUNCHER + DecompressMap(type, nomap); +#endif + + switch (type) + { + case ScriptType.Client: + FileManagement.ReloadLoadoutValue(true); + if (!GlobalVars.LocalPlayMode && GlobalVars.GameOpened != ScriptType.Server) + { + goto default; + } + break; + case ScriptType.Server: + if (GlobalVars.GameOpened == ScriptType.Server) + { + Util.ConsolePrint("ERROR - Failed to launch Novetus. (A server is already running.)", 2); #if LAUNCHER if (!GlobalVars.isConsoleOnly) @@ -1096,10 +1098,10 @@ public class ClientManagement MessageBox.Show("Failed to launch Novetus. (Error: A server is already running.)", "Novetus - Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } #endif - return; - } - else if (GlobalVars.UserConfiguration.FirstServerLaunch) - { + return; + } + else if (GlobalVars.UserConfiguration.FirstServerLaunch) + { #if LAUNCHER string hostingTips = "For your first time hosting a server, make sure your server's port forwarded (set up in your router), going through a tunnel server, or running from UPnP.\n" + "If your port is forwarded or you are going through a tunnel server, make sure your port is set up as UDP, not TCP.\n" + @@ -1114,20 +1116,20 @@ public class ClientManagement Util.ConsolePrint("Tips: " + hostingTips, 4); } #endif - GlobalVars.UserConfiguration.FirstServerLaunch = false; - } - else - { + GlobalVars.UserConfiguration.FirstServerLaunch = false; + } + else + { + goto default; + } + break; + case ScriptType.Solo: + FileManagement.ReloadLoadoutValue(true); goto default; - } - break; - case ScriptType.Solo: - FileManagement.ReloadLoadoutValue(true); - goto default; - default: - if (GlobalVars.GameOpened != ScriptType.None) - { - Util.ConsolePrint("ERROR - Failed to launch Novetus. (A game is already running.)", 2); + default: + if (GlobalVars.GameOpened != ScriptType.None) + { + Util.ConsolePrint("ERROR - Failed to launch Novetus. (A game is already running.)", 2); #if LAUNCHER if (!GlobalVars.isConsoleOnly) @@ -1135,141 +1137,141 @@ public class ClientManagement MessageBox.Show("Failed to launch Novetus. (Error: A game is already running.)", "Novetus - Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } #endif - return; - } - break; - } + return; + } + break; + } - ReadClientValues(ClientName); - string luafile = GetLuaFileName(ClientName, type); - string rbxexe = GetClientEXEDir(ClientName, type); - string mapfile = type.Equals(ScriptType.EasterEgg) ? - GlobalPaths.DataDir + "\\Appreciation.rbxl" : - (nomap ? (type.Equals(ScriptType.Studio) ? GlobalPaths.ConfigDir + "\\Place1.rbxl" : "") : GlobalVars.UserConfiguration.MapPath); - string mapname = type.Equals(ScriptType.EasterEgg) ? "" : (nomap ? "" : GlobalVars.UserConfiguration.Map); - FileFormat.ClientInfo info = GetClientInfoValues(ClientName); - string quote = "\""; - string args = ""; - GlobalVars.ValidatedExtraFiles = 0; + ReadClientValues(ClientName); + string luafile = GetLuaFileName(ClientName, type); + string rbxexe = GetClientEXEDir(ClientName, type); + string mapfile = type.Equals(ScriptType.EasterEgg) ? + GlobalPaths.DataDir + "\\Appreciation.rbxl" : + (nomap ? (type.Equals(ScriptType.Studio) ? GlobalPaths.ConfigDir + "\\Place1.rbxl" : "") : GlobalVars.UserConfiguration.MapPath); + string mapname = type.Equals(ScriptType.EasterEgg) ? "" : (nomap ? "" : GlobalVars.UserConfiguration.Map); + FileFormat.ClientInfo info = GetClientInfoValues(ClientName); + string quote = "\""; + string args = ""; + GlobalVars.ValidatedExtraFiles = 0; - bool v1 = false; + bool v1 = false; - if (info.CommandLineArgs.Contains("<") && - info.CommandLineArgs.Contains("")) - { - v1 = true; - } - - if (!GlobalVars.AdminMode && !info.AlreadyHasSecurity) - { - string validstart = ""; - string validend = ""; - string validv2 = "validate="; - - foreach (string line in info.CommandLineArgs.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)) + if (info.CommandLineArgs.Contains("<") && + info.CommandLineArgs.Contains("")) { - if (v1 && line.Contains(validstart) && line.Contains(validend)) + v1 = true; + } + + if (!GlobalVars.AdminMode && !info.AlreadyHasSecurity) + { + string validstart = ""; + string validend = ""; + string validv2 = "validate="; + + foreach (string line in info.CommandLineArgs.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)) { - try + if (v1 && line.Contains(validstart) && line.Contains(validend)) { + try + { #if URI - ValidateFiles(line, validstart, validend, label); + ValidateFiles(line, validstart, validend, label); #else ValidateFiles(line, validstart, validend); #endif - } + } #if URI || LAUNCHER || BASICLAUNCHER - catch (Exception ex) - { - Util.LogExceptions(ex); + catch (Exception ex) + { + Util.LogExceptions(ex); #else catch (Exception) { #endif - continue; + continue; + } } - } - else if (line.Contains(validv2)) - { - try + else if (line.Contains(validv2)) { + try + { #if URI - ValidateFiles(line, validv2, "", label); + ValidateFiles(line, validv2, "", label); #else ValidateFiles(line, validv2, ""); #endif - } + } #if URI || LAUNCHER || BASICLAUNCHER - catch (Exception ex) - { - Util.LogExceptions(ex); + catch (Exception ex) + { + Util.LogExceptions(ex); #else catch (Exception) { #endif - continue; + continue; + } } } } - } - if (info.CommandLineArgs.Contains("%args%")) - { - if (!info.Fix2007) + if (info.CommandLineArgs.Contains("%args%")) { - args = quote - + mapfile - + "\" -script \" dofile('" + luafile + "'); " - + ScriptFuncs.Generator.GetScriptFuncForType(ClientName, type) - + quote - + (no3d ? " -no3d" : ""); + if (!info.Fix2007) + { + args = quote + + mapfile + + "\" -script \" dofile('" + luafile + "'); " + + ScriptFuncs.Generator.GetScriptFuncForType(ClientName, type) + + quote + + (no3d ? " -no3d" : ""); + } + else + { + ScriptFuncs.Generator.GenerateScriptForClient(ClientName, type); + args = "-script " + + quote + + luafile + + quote + + (no3d ? " -no3d" : "") + + " " + + quote + + mapfile + + quote; + } } else { - ScriptFuncs.Generator.GenerateScriptForClient(ClientName, type); - args = "-script " - + quote - + luafile - + quote - + (no3d ? " -no3d" : "") - + " " - + quote - + mapfile - + quote; + args = ScriptFuncs.ClientScript.CompileScript(ClientName, info.CommandLineArgs, + ScriptFuncs.ClientScript.GetTagFromType(type, false, no3d, v1), + ScriptFuncs.ClientScript.GetTagFromType(type, true, no3d, v1), + mapfile, + luafile, + rbxexe); } - } - else - { - args = ScriptFuncs.ClientScript.CompileScript(ClientName, info.CommandLineArgs, - ScriptFuncs.ClientScript.GetTagFromType(type, false, no3d, v1), - ScriptFuncs.ClientScript.GetTagFromType(type, true, no3d, v1), - mapfile, - luafile, - rbxexe); - } - if (args == "") - return; + if (args == "") + return; - try - { - Util.ConsolePrint("Client Loaded.", 4); - - if (type.Equals(ScriptType.Client)) + try { - if (!GlobalVars.AdminMode) + Util.ConsolePrint("Client Loaded.", 4); + + if (type.Equals(ScriptType.Client)) { - if (info.AlreadyHasSecurity != true) + if (!GlobalVars.AdminMode) { - if (SecurityFuncs.checkClientMD5(ClientName) && SecurityFuncs.checkScriptMD5(ClientName)) - { - OpenClient(type, rbxexe, args, ClientName, mapname, e); - } - else + if (info.AlreadyHasSecurity != true) { + if (SecurityFuncs.checkClientMD5(ClientName) && SecurityFuncs.checkScriptMD5(ClientName)) + { + OpenClient(type, rbxexe, args, ClientName, mapname, e); + } + else + { #if URI - UpdateStatus(label, "The client has been detected as modified."); + UpdateStatus(label, "The client has been detected as modified."); #elif LAUNCHER Util.ConsolePrint("ERROR - Failed to launch Novetus. (The client has been detected as modified.)", 2); #endif @@ -1282,10 +1284,15 @@ public class ClientManagement #endif #if URI - throw new IOException("The client has been detected as modified."); + throw new IOException("The client has been detected as modified."); #else return; #endif + } + } + else + { + OpenClient(type, rbxexe, args, ClientName, mapname, e); } } else @@ -1297,258 +1304,253 @@ public class ClientManagement { OpenClient(type, rbxexe, args, ClientName, mapname, e); } - } - else - { - OpenClient(type, rbxexe, args, ClientName, mapname, e); - } - switch (type) - { - case ScriptType.Client: - if (!GlobalVars.LocalPlayMode && GlobalVars.GameOpened != ScriptType.Server) - { + switch (type) + { + case ScriptType.Client: + if (!GlobalVars.LocalPlayMode && GlobalVars.GameOpened != ScriptType.Server) + { + goto default; + } + break; + case ScriptType.Studio: + break; + case ScriptType.Server: + NovetusFuncs.PingMasterServer(true, "Server will now display on the defined master server, if available."); goto default; - } - break; - case ScriptType.Studio: - break; - case ScriptType.Server: - NovetusFuncs.PingMasterServer(true, "Server will now display on the defined master server, if available."); - goto default; - default: - GlobalVars.GameOpened = type; - break; - } + default: + GlobalVars.GameOpened = type; + break; + } - GlobalVars.ValidatedExtraFiles = 0; - } + GlobalVars.ValidatedExtraFiles = 0; + } #if URI || LAUNCHER || BASICLAUNCHER - catch (Exception ex) + catch (Exception ex) #else catch (Exception) #endif - { + { #if URI - UpdateStatus(label, "Error: " + ex.Message); + UpdateStatus(label, "Error: " + ex.Message); #elif LAUNCHER Util.ConsolePrint("ERROR - Failed to launch Novetus. (Error: " + ex.Message + ")", 2); #endif #if URI || LAUNCHER - if (!GlobalVars.isConsoleOnly) - { - MessageBox.Show("Failed to launch Novetus. (Error: " + ex.Message + ")", "Novetus - Error", MessageBoxButtons.OK, MessageBoxIcon.Error); - } + if (!GlobalVars.isConsoleOnly) + { + MessageBox.Show("Failed to launch Novetus. (Error: " + ex.Message + ")", "Novetus - Error", MessageBoxButtons.OK, MessageBoxIcon.Error); + } #endif #if URI || LAUNCHER || BASICLAUNCHER - Util.LogExceptions(ex); + Util.LogExceptions(ex); #endif #if URI - //toss the exception back to the URI - throw new Exception(ex.Message); + //toss the exception back to the URI + throw new Exception(ex.Message); #endif - } - } - - public static void OpenClient(ScriptType type, string rbxexe, string args, string clientname, string mapname, EventHandler e, bool customization = false) - { - Process client = new Process(); - client.StartInfo.FileName = rbxexe; - client.StartInfo.WorkingDirectory = Path.GetDirectoryName(rbxexe); - client.StartInfo.Arguments = args; - if (e != null) - { - client.EnableRaisingEvents = true; - client.Exited += e; - } - client.Start(); - client.PriorityClass = GlobalVars.UserConfiguration.Priority; - - if (!customization) - { - SecurityFuncs.RenameWindow(client, type, clientname, mapname); - if (e != null) - { - UpdateRichPresence(GetStateForType(type), clientname, mapname); } } - //TODO: make a command that uses this. + public static void OpenClient(ScriptType type, string rbxexe, string args, string clientname, string mapname, EventHandler e, bool customization = false) + { + Process client = new Process(); + client.StartInfo.FileName = rbxexe; + client.StartInfo.WorkingDirectory = Path.GetDirectoryName(rbxexe); + client.StartInfo.Arguments = args; + if (e != null) + { + client.EnableRaisingEvents = true; + client.Exited += e; + } + client.Start(); + client.PriorityClass = GlobalVars.UserConfiguration.Priority; + + if (!customization) + { + SecurityFuncs.RenameWindow(client, type, clientname, mapname); + if (e != null) + { + UpdateRichPresence(GetStateForType(type), clientname, mapname); + } + } + + //TODO: make a command that uses this. #if CMD_LEGACY NovetusFuncs.CreateTXT(); #endif - } - - public static bool IsClientValid(string client) - { - string clientdir = GlobalPaths.ClientDir; - DirectoryInfo dinfo = new DirectoryInfo(clientdir); - DirectoryInfo[] Dirs = dinfo.GetDirectories(); - foreach (DirectoryInfo dir in Dirs) - { - if (dir.Name == client) - { - return true; - } } - return false; - } -} -#endregion - -#region Script Functions -public class ScriptFuncs -{ -#region Script Generator/Signer - public class Generator - { - public static void SignGeneratedScript(string scriptFileName, bool newSigFormat = false, bool encodeInBase64 = true) + public static bool IsClientValid(string client) { - string privateKeyPath = Path.GetDirectoryName(scriptFileName) + "//privatekey.txt"; - - if (File.Exists(privateKeyPath)) + string clientdir = GlobalPaths.ClientDir; + DirectoryInfo dinfo = new DirectoryInfo(clientdir); + DirectoryInfo[] Dirs = dinfo.GetDirectories(); + foreach (DirectoryInfo dir in Dirs) { - //init vars - string format = (newSigFormat ? "--rbxsig" : "") + "%{0}%{1}"; - byte[] blob = Encoding.Default.GetBytes(File.ReadAllText(privateKeyPath)); - - if (encodeInBase64) + if (dir.Name == client) { - blob = Convert.FromBase64String(Encoding.Default.GetString(blob)); + return true; } - - //create cryptography providers - var shaCSP = new SHA1CryptoServiceProvider(); - var rsaCSP = new RSACryptoServiceProvider(); - rsaCSP.ImportCspBlob(blob); - - // sign script - string script = "\r\n" + File.ReadAllText(scriptFileName); - byte[] signature = rsaCSP.SignData(Encoding.Default.GetBytes(script), shaCSP); - // override file. - Util.FixedFileDelete(scriptFileName); - File.WriteAllText(scriptFileName, string.Format(format, Convert.ToBase64String(signature), script)); } - else - { - //create the signature file if it doesn't exist - var signingRSACSP = new RSACryptoServiceProvider(1024); - byte[] privateKeyBlob = signingRSACSP.ExportCspBlob(true); - signingRSACSP.Dispose(); - // save our text file in the script's directory - File.WriteAllText(privateKeyPath, encodeInBase64 ? Convert.ToBase64String(privateKeyBlob) : Encoding.Default.GetString(privateKeyBlob)); - - // try signing again. - SignGeneratedScript(scriptFileName, encodeInBase64); - } + return false; } + } + #endregion - public static string GetScriptFuncForType(ScriptType type) + #region Script Functions + public class ScriptFuncs + { + #region Script Generator/Signer + public class Generator { - return GetScriptFuncForType(GlobalVars.UserConfiguration.SelectedClient, type); - } + public static void SignGeneratedScript(string scriptFileName, bool newSigFormat = false, bool encodeInBase64 = true) + { + string privateKeyPath = Path.GetDirectoryName(scriptFileName) + "//privatekey.txt"; - public static string GetScriptFuncForType(string ClientName, ScriptType type) - { - FileFormat.ClientInfo info = ClientManagement.GetClientInfoValues(ClientName); + if (File.Exists(privateKeyPath)) + { + //init vars + string format = (newSigFormat ? "--rbxsig" : "") + "%{0}%{1}"; + byte[] blob = Encoding.Default.GetBytes(File.ReadAllText(privateKeyPath)); - string rbxexe = ""; - if (info.LegacyMode) - { - rbxexe = GlobalPaths.ClientDir + @"\\" + ClientName + @"\\RobloxApp.exe"; + if (encodeInBase64) + { + blob = Convert.FromBase64String(Encoding.Default.GetString(blob)); + } + + //create cryptography providers + var shaCSP = new SHA1CryptoServiceProvider(); + var rsaCSP = new RSACryptoServiceProvider(); + rsaCSP.ImportCspBlob(blob); + + // sign script + string script = "\r\n" + File.ReadAllText(scriptFileName); + byte[] signature = rsaCSP.SignData(Encoding.Default.GetBytes(script), shaCSP); + // override file. + Util.FixedFileDelete(scriptFileName); + File.WriteAllText(scriptFileName, string.Format(format, Convert.ToBase64String(signature), script)); + } + else + { + //create the signature file if it doesn't exist + var signingRSACSP = new RSACryptoServiceProvider(1024); + byte[] privateKeyBlob = signingRSACSP.ExportCspBlob(true); + signingRSACSP.Dispose(); + + // save our text file in the script's directory + File.WriteAllText(privateKeyPath, encodeInBase64 ? Convert.ToBase64String(privateKeyBlob) : Encoding.Default.GetString(privateKeyBlob)); + + // try signing again. + SignGeneratedScript(scriptFileName, encodeInBase64); + } } - else if (info.SeperateFolders) + + public static string GetScriptFuncForType(ScriptType type) { - rbxexe = GlobalPaths.ClientDir + @"\\" + ClientName + @"\\client\\RobloxApp_client.exe"; + return GetScriptFuncForType(GlobalVars.UserConfiguration.SelectedClient, type); } - else if (info.UsesCustomClientEXEName) + + public static string GetScriptFuncForType(string ClientName, ScriptType type) { - rbxexe = GlobalPaths.ClientDir + @"\\" + ClientName + @"\\" + info.CustomClientEXEName; - } - else - { - rbxexe = GlobalPaths.ClientDir + @"\\" + ClientName + @"\\RobloxApp_client.exe"; - } + FileFormat.ClientInfo info = ClientManagement.GetClientInfoValues(ClientName); + + string rbxexe = ""; + if (info.LegacyMode) + { + rbxexe = GlobalPaths.ClientDir + @"\\" + ClientName + @"\\RobloxApp.exe"; + } + else if (info.SeperateFolders) + { + rbxexe = GlobalPaths.ClientDir + @"\\" + ClientName + @"\\client\\RobloxApp_client.exe"; + } + else if (info.UsesCustomClientEXEName) + { + rbxexe = GlobalPaths.ClientDir + @"\\" + ClientName + @"\\" + info.CustomClientEXEName; + } + else + { + rbxexe = GlobalPaths.ClientDir + @"\\" + ClientName + @"\\RobloxApp_client.exe"; + } #if LAUNCHER string md5dir = !info.AlreadyHasSecurity ? SecurityFuncs.GenerateMD5(Assembly.GetExecutingAssembly().Location) : ""; #else - string md5dir = !info.AlreadyHasSecurity ? SecurityFuncs.GenerateMD5(GlobalPaths.RootPathLauncher + "\\Novetus.exe") : ""; + string md5dir = !info.AlreadyHasSecurity ? SecurityFuncs.GenerateMD5(GlobalPaths.RootPathLauncher + "\\Novetus.exe") : ""; #endif - string md5script = !info.AlreadyHasSecurity ? SecurityFuncs.GenerateMD5(GlobalPaths.ClientDir + @"\\" + ClientName + @"\\content\\scripts\\" + GlobalPaths.ScriptName + ".lua") : ""; - string md5exe = !info.AlreadyHasSecurity ? SecurityFuncs.GenerateMD5(rbxexe) : ""; - string md5s = "'" + md5exe + "','" + md5dir + "','" + md5script + "'"; + string md5script = !info.AlreadyHasSecurity ? SecurityFuncs.GenerateMD5(GlobalPaths.ClientDir + @"\\" + ClientName + @"\\content\\scripts\\" + GlobalPaths.ScriptName + ".lua") : ""; + string md5exe = !info.AlreadyHasSecurity ? SecurityFuncs.GenerateMD5(rbxexe) : ""; + string md5s = "'" + md5exe + "','" + md5dir + "','" + md5script + "'"; - switch (type) - { - case ScriptType.Client: - return "_G.CSConnect(" - + (info.UsesID ? GlobalVars.UserConfiguration.UserID : 0) + ",'" - + GlobalVars.CurrentServer.ServerIP + "'," - + GlobalVars.CurrentServer.ServerPort + ",'" - + (info.UsesPlayerName ? GlobalVars.UserConfiguration.PlayerName : "Player") + "'," - + GlobalVars.Loadout + "," - + md5s + ",'" - + GlobalVars.PlayerTripcode - + ((GlobalVars.ValidatedExtraFiles > 0) ? "'," + GlobalVars.ValidatedExtraFiles.ToString() + "," : "',0,") - + GlobalVars.UserConfiguration.NewGUI.ToString().ToLower() + ");"; - case ScriptType.Server: - return "_G.CSServer(" - + GlobalVars.UserConfiguration.RobloxPort + "," - + GlobalVars.UserConfiguration.PlayerLimit + "," - + md5s + "," - + GlobalVars.UserConfiguration.ShowServerNotifications.ToString().ToLower() - + ((GlobalVars.ValidatedExtraFiles > 0) ? "," + GlobalVars.ValidatedExtraFiles.ToString() + "," : ",0,") - + GlobalVars.UserConfiguration.NewGUI.ToString().ToLower() + ");"; - case ScriptType.Solo: - case ScriptType.EasterEgg: - return "_G.CSSolo(" - + (info.UsesID ? GlobalVars.UserConfiguration.UserID : 0) + ",'" - + (info.UsesPlayerName ? GlobalVars.UserConfiguration.PlayerName : "Player") + "'," - + GlobalVars.soloLoadout + "," - + GlobalVars.UserConfiguration.NewGUI.ToString().ToLower() + ");"; - case ScriptType.Studio: - return "_G.CSStudio(" - + GlobalVars.UserConfiguration.NewGUI.ToString().ToLower() + ");"; - default: - return ""; + switch (type) + { + case ScriptType.Client: + return "_G.CSConnect(" + + (info.UsesID ? GlobalVars.UserConfiguration.UserID : 0) + ",'" + + GlobalVars.CurrentServer.ServerIP + "'," + + GlobalVars.CurrentServer.ServerPort + ",'" + + (info.UsesPlayerName ? GlobalVars.UserConfiguration.PlayerName : "Player") + "'," + + GlobalVars.Loadout + "," + + md5s + ",'" + + GlobalVars.PlayerTripcode + + ((GlobalVars.ValidatedExtraFiles > 0) ? "'," + GlobalVars.ValidatedExtraFiles.ToString() + "," : "',0,") + + GlobalVars.UserConfiguration.NewGUI.ToString().ToLower() + ");"; + case ScriptType.Server: + return "_G.CSServer(" + + GlobalVars.UserConfiguration.RobloxPort + "," + + GlobalVars.UserConfiguration.PlayerLimit + "," + + md5s + "," + + GlobalVars.UserConfiguration.ShowServerNotifications.ToString().ToLower() + + ((GlobalVars.ValidatedExtraFiles > 0) ? "," + GlobalVars.ValidatedExtraFiles.ToString() + "," : ",0,") + + GlobalVars.UserConfiguration.NewGUI.ToString().ToLower() + ");"; + case ScriptType.Solo: + case ScriptType.EasterEgg: + return "_G.CSSolo(" + + (info.UsesID ? GlobalVars.UserConfiguration.UserID : 0) + ",'" + + (info.UsesPlayerName ? GlobalVars.UserConfiguration.PlayerName : "Player") + "'," + + GlobalVars.soloLoadout + "," + + GlobalVars.UserConfiguration.NewGUI.ToString().ToLower() + ");"; + case ScriptType.Studio: + return "_G.CSStudio(" + + GlobalVars.UserConfiguration.NewGUI.ToString().ToLower() + ");"; + default: + return ""; + } } - } - public static string GetNameForType(ScriptType type) - { - switch (type) + public static string GetNameForType(ScriptType type) { - case ScriptType.Client: - return "Client"; - case ScriptType.Server: - return "Server"; - case ScriptType.Solo: - return "Play Solo"; - case ScriptType.Studio: - return "Studio"; - case ScriptType.EasterEgg: - return "A message from Bitl"; - default: - return "N/A"; + switch (type) + { + case ScriptType.Client: + return "Client"; + case ScriptType.Server: + return "Server"; + case ScriptType.Solo: + return "Play Solo"; + case ScriptType.Studio: + return "Studio"; + case ScriptType.EasterEgg: + return "A message from Bitl"; + default: + return "N/A"; + } } - } - public static void GenerateScriptForClient(ScriptType type) - { - GenerateScriptForClient(GlobalVars.UserConfiguration.SelectedClient, type); - } + public static void GenerateScriptForClient(ScriptType type) + { + GenerateScriptForClient(GlobalVars.UserConfiguration.SelectedClient, type); + } - public static void GenerateScriptForClient(string ClientName, ScriptType type) - { - bool shouldUseLoadFile = GlobalVars.SelectedClientInfo.CommandLineArgs.Contains("%useloadfile%"); - string execScriptMethod = shouldUseLoadFile ? "loadfile" : "dofile"; + public static void GenerateScriptForClient(string ClientName, ScriptType type) + { + bool shouldUseLoadFile = GlobalVars.SelectedClientInfo.CommandLineArgs.Contains("%useloadfile%"); + string execScriptMethod = shouldUseLoadFile ? "loadfile" : "dofile"; - string[] code = { + string[] code = { "--Load Script", //scriptcontents, (GlobalVars.SelectedClientInfo.SeperateFolders ? "" + @@ -1557,336 +1559,337 @@ public class ScriptFuncs GetScriptFuncForType(type), }; - if (GlobalVars.SelectedClientInfo.SeperateFolders) - { - string scriptsFolder = GlobalPaths.ClientDir + @"\\" + ClientName + @"\\" + ClientManagement.GetClientSeperateFolderName(type) + @"\\content\\scripts"; - if (!Directory.Exists(scriptsFolder)) + if (GlobalVars.SelectedClientInfo.SeperateFolders) { - Directory.CreateDirectory(scriptsFolder); + string scriptsFolder = GlobalPaths.ClientDir + @"\\" + ClientName + @"\\" + ClientManagement.GetClientSeperateFolderName(type) + @"\\content\\scripts"; + if (!Directory.Exists(scriptsFolder)) + { + Directory.CreateDirectory(scriptsFolder); + } + } + + string outputPath = (GlobalVars.SelectedClientInfo.SeperateFolders ? + GlobalPaths.ClientDir + @"\\" + ClientName + @"\\" + ClientManagement.GetClientSeperateFolderName(type) + @"\\content\\scripts\\" + GlobalPaths.ScriptGenName + ".lua" : + GlobalPaths.ClientDir + @"\\" + ClientName + @"\\content\\scripts\\" + GlobalPaths.ScriptGenName + ".lua"); + + File.WriteAllLines(outputPath, code); + + bool shouldSign = GlobalVars.SelectedClientInfo.CommandLineArgs.Contains("%signgeneratedjoinscript%"); + bool shouldUseNewSigFormat = GlobalVars.SelectedClientInfo.CommandLineArgs.Contains("%usenewsignformat%"); + + if (shouldSign) + { + SignGeneratedScript(outputPath, shouldUseNewSigFormat); } } - string outputPath = (GlobalVars.SelectedClientInfo.SeperateFolders ? - GlobalPaths.ClientDir + @"\\" + ClientName + @"\\" + ClientManagement.GetClientSeperateFolderName(type) + @"\\content\\scripts\\" + GlobalPaths.ScriptGenName + ".lua" : - GlobalPaths.ClientDir + @"\\" + ClientName + @"\\content\\scripts\\" + GlobalPaths.ScriptGenName + ".lua"); - - File.WriteAllLines(outputPath, code); - - bool shouldSign = GlobalVars.SelectedClientInfo.CommandLineArgs.Contains("%signgeneratedjoinscript%"); - bool shouldUseNewSigFormat = GlobalVars.SelectedClientInfo.CommandLineArgs.Contains("%usenewsignformat%"); - - if (shouldSign) + public static string GetGeneratedScriptName(string ClientName, ScriptType type) { - SignGeneratedScript(outputPath, shouldUseNewSigFormat); + GenerateScriptForClient(ClientName, type); + return ClientManagement.GetGenLuaFileName(ClientName, type); } } + #endregion - public static string GetGeneratedScriptName(string ClientName, ScriptType type) + #region ClientScript Parser + public class ClientScript { - GenerateScriptForClient(ClientName, type); - return ClientManagement.GetGenLuaFileName(ClientName, type); - } - } -#endregion - -#region ClientScript Parser - public class ClientScript - { - public static string GetArgsFromTag(string code, string tag, string endtag) - { - try + public static string GetArgsFromTag(string code, string tag, string endtag) { - if (string.IsNullOrEmpty(endtag)) + try { - //VERSION 2!! - string result = code.Substring(code.IndexOf(tag) + tag.Length); - return result; + if (string.IsNullOrEmpty(endtag)) + { + //VERSION 2!! + string result = code.Substring(code.IndexOf(tag) + tag.Length); + return result; + } + else + { + int pFrom = code.IndexOf(tag) + tag.Length; + int pTo = code.LastIndexOf(endtag); + string result = code.Substring(pFrom, pTo - pFrom); + return result; + } } - else - { - int pFrom = code.IndexOf(tag) + tag.Length; - int pTo = code.LastIndexOf(endtag); - string result = code.Substring(pFrom, pTo - pFrom); - return result; - } - } #if URI || LAUNCHER || BASICLAUNCHER - catch (Exception ex) - { - Util.LogExceptions(ex); + catch (Exception ex) + { + Util.LogExceptions(ex); #else catch (Exception) { #endif - return ""; - } - } - - public static ScriptType GetTypeFromTag(string tag) - { - switch (tag) - { - case string client when client.Contains("client"): - return ScriptType.Client; - case string server when server.Contains("server"): - case string no3d when no3d.Contains("no3d"): - return ScriptType.Server; - case string solo when solo.Contains("solo"): - return ScriptType.Solo; - case string studio when studio.Contains("studio"): - return ScriptType.Studio; - default: - return ScriptType.None; - } - } - - public static string GetTagFromType(ScriptType type, bool endtag, bool no3d, bool v1) - { - if (v1) - { - switch (type) - { - case ScriptType.Client: - return endtag ? "" : ""; - case ScriptType.Server: - return no3d ? (endtag ? "" : "") : (endtag ? "" : ""); - case ScriptType.Solo: - return endtag ? "" : ""; - case ScriptType.Studio: - return endtag ? "" : ""; - default: - return ""; - } - } - else - { - if (endtag == true) - { - //NO END TAGS. return ""; } + } - switch (type) + public static ScriptType GetTypeFromTag(string tag) + { + switch (tag) { - case ScriptType.Client: - return "client="; - case ScriptType.Server: - return no3d ? "no3d=" : "server="; - case ScriptType.Solo: - return "solo="; - case ScriptType.Studio: - return "studio="; + case string client when client.Contains("client"): + return ScriptType.Client; + case string server when server.Contains("server"): + case string no3d when no3d.Contains("no3d"): + return ScriptType.Server; + case string solo when solo.Contains("solo"): + return ScriptType.Solo; + case string studio when studio.Contains("studio"): + return ScriptType.Studio; default: - return ""; - } - } - } - - public static int ConvertIconStringToInt() - { - switch (GlobalVars.UserCustomization.Icon) - { - case "BC": - return 1; - case "TBC": - return 2; - case "OBC": - return 3; - case "NBC": - default: - return 0; - } - } - - public static string GetFolderAndMapName(string source, string seperator) - { - try - { - string result = source.Substring(0, source.IndexOf(seperator)); - - if (File.Exists(GlobalPaths.MapsDir + @"\\" + result + @"\\" + source)) - { - return result + @"\\" + source; - } - else - { - return source; - } - } -#if URI || LAUNCHER || BASICLAUNCHER - catch (Exception ex) - { - Util.LogExceptions(ex); -#else - catch (Exception) - { -#endif - return source; - } - } - - public static string GetFolderAndMapName(string source) - { - return GetFolderAndMapName(source, " -"); - } - - public static string GetRawArgsForType(ScriptType type, string ClientName, string luafile) - { - FileFormat.ClientInfo info = ClientManagement.GetClientInfoValues(ClientName); - - if (!info.Fix2007) - { - return Generator.GetScriptFuncForType(ClientName, type); - } - else - { - return luafile; - } - } - - public static string CompileScript(string code, string tag, string endtag, string mapfile, string luafile, string rbxexe, bool usesharedtags = true) - { - return CompileScript(GlobalVars.UserConfiguration.SelectedClient, code, tag, endtag, mapfile, luafile, rbxexe, usesharedtags); - } - - public static string CompileScript(string ClientName, string code, string tag, string endtag, string mapfile, string luafile, string rbxexe, bool usesharedtags = true) - { - string start = tag; - string end = endtag; - - bool v1 = false; - - if (code.Contains("<") && - code.Contains("")) - { - v1 = true; - } - else - { - //make sure we have no end tags. - if (!string.IsNullOrWhiteSpace(end)) - { - end = ""; + return ScriptType.None; } } - FileFormat.ClientInfo info = ClientManagement.GetClientInfoValues(ClientName); - - ScriptType type = GetTypeFromTag(start); - - //we must have the ending tag before we continue. - if (v1 && string.IsNullOrWhiteSpace(end)) - { - return ""; - } - - if (usesharedtags) + public static string GetTagFromType(ScriptType type, bool endtag, bool no3d, bool v1) { if (v1) { - string sharedstart = ""; - string sharedend = ""; - - if (code.Contains(sharedstart) && code.Contains(sharedend)) + switch (type) { - start = sharedstart; - end = sharedend; + case ScriptType.Client: + return endtag ? "" : ""; + case ScriptType.Server: + return no3d ? (endtag ? "" : "") : (endtag ? "" : ""); + case ScriptType.Solo: + return endtag ? "" : ""; + case ScriptType.Studio: + return endtag ? "" : ""; + default: + return ""; } } else { - string sharedstart = "shared="; - - if (code.Contains(sharedstart)) + if (endtag == true) { - start = sharedstart; + //NO END TAGS. + return ""; + } + + switch (type) + { + case ScriptType.Client: + return "client="; + case ScriptType.Server: + return no3d ? "no3d=" : "server="; + case ScriptType.Solo: + return "solo="; + case ScriptType.Studio: + return "studio="; + default: + return ""; } } } - if (info.Fix2007) + public static int ConvertIconStringToInt() { - Generator.GenerateScriptForClient(type); + switch (GlobalVars.UserCustomization.Icon) + { + case "BC": + return 1; + case "TBC": + return 2; + case "OBC": + return 3; + case "NBC": + default: + return 0; + } } - string extractedCode = GetArgsFromTag(code, start, end); + public static string GetFolderAndMapName(string source, string seperator) + { + try + { + string result = source.Substring(0, source.IndexOf(seperator)); + + if (File.Exists(GlobalPaths.MapsDir + @"\\" + result + @"\\" + source)) + { + return result + @"\\" + source; + } + else + { + return source; + } + } +#if URI || LAUNCHER || BASICLAUNCHER + catch (Exception ex) + { + Util.LogExceptions(ex); +#else + catch (Exception) + { +#endif + return source; + } + } + + public static string GetFolderAndMapName(string source) + { + return GetFolderAndMapName(source, " -"); + } + + public static string GetRawArgsForType(ScriptType type, string ClientName, string luafile) + { + FileFormat.ClientInfo info = ClientManagement.GetClientInfoValues(ClientName); + + if (!info.Fix2007) + { + return Generator.GetScriptFuncForType(ClientName, type); + } + else + { + return luafile; + } + } + + public static string CompileScript(string code, string tag, string endtag, string mapfile, string luafile, string rbxexe, bool usesharedtags = true) + { + return CompileScript(GlobalVars.UserConfiguration.SelectedClient, code, tag, endtag, mapfile, luafile, rbxexe, usesharedtags); + } + + public static string CompileScript(string ClientName, string code, string tag, string endtag, string mapfile, string luafile, string rbxexe, bool usesharedtags = true) + { + string start = tag; + string end = endtag; + + bool v1 = false; + + if (code.Contains("<") && + code.Contains("")) + { + v1 = true; + } + else + { + //make sure we have no end tags. + if (!string.IsNullOrWhiteSpace(end)) + { + end = ""; + } + } + + FileFormat.ClientInfo info = ClientManagement.GetClientInfoValues(ClientName); + + ScriptType type = GetTypeFromTag(start); + + //we must have the ending tag before we continue. + if (v1 && string.IsNullOrWhiteSpace(end)) + { + return ""; + } + + if (usesharedtags) + { + if (v1) + { + string sharedstart = ""; + string sharedend = ""; + + if (code.Contains(sharedstart) && code.Contains(sharedend)) + { + start = sharedstart; + end = sharedend; + } + } + else + { + string sharedstart = "shared="; + + if (code.Contains(sharedstart)) + { + start = sharedstart; + } + } + } + + if (info.Fix2007) + { + Generator.GenerateScriptForClient(type); + } + + string extractedCode = GetArgsFromTag(code, start, end); #if LAUNCHER string md5dir = !info.AlreadyHasSecurity ? SecurityFuncs.GenerateMD5(Assembly.GetExecutingAssembly().Location) : ""; #else - string md5dir = !info.AlreadyHasSecurity ? SecurityFuncs.GenerateMD5(GlobalPaths.RootPathLauncher + "\\Novetus.exe") : ""; + string md5dir = !info.AlreadyHasSecurity ? SecurityFuncs.GenerateMD5(GlobalPaths.RootPathLauncher + "\\Novetus.exe") : ""; #endif - string md5script = !info.AlreadyHasSecurity ? SecurityFuncs.GenerateMD5(GlobalPaths.ClientDir + @"\\" + GlobalVars.UserConfiguration.SelectedClient + @"\\content\\scripts\\" + GlobalPaths.ScriptName + ".lua") : ""; - string md5exe = !info.AlreadyHasSecurity ? SecurityFuncs.GenerateMD5(rbxexe) : ""; - string md5sd = "'" + md5exe + "','" + md5dir + "','" + md5script + "'"; - string md5s = "'" + info.ClientMD5 + "','" + md5dir + "','" + info.ScriptMD5 + "'"; - string compiled = extractedCode.Replace("%version%", GlobalVars.ProgramInformation.Version) - .Replace("%mapfile%", mapfile) - .Replace("%luafile%", luafile) - .Replace("%charapp%", GlobalVars.UserCustomization.CharacterID) - .Replace("%server%", GlobalVars.CurrentServer.ToString()) - .Replace("%ip%", GlobalVars.CurrentServer.ServerIP) - .Replace("%port%", GlobalVars.UserConfiguration.RobloxPort.ToString()) - .Replace("%joinport%", GlobalVars.CurrentServer.ServerPort.ToString()) - .Replace("%name%", GlobalVars.UserConfiguration.PlayerName) - .Replace("%icone%", ConvertIconStringToInt().ToString()) - .Replace("%icon%", GlobalVars.UserCustomization.Icon) - .Replace("%id%", GlobalVars.UserConfiguration.UserID.ToString()) - .Replace("%face%", GlobalVars.UserCustomization.Face) - .Replace("%head%", GlobalVars.UserCustomization.Head) - .Replace("%tshirt%", GlobalVars.UserCustomization.TShirt) - .Replace("%shirt%", GlobalVars.UserCustomization.Shirt) - .Replace("%pants%", GlobalVars.UserCustomization.Pants) - .Replace("%hat1%", GlobalVars.UserCustomization.Hat1) - .Replace("%hat2%", GlobalVars.UserCustomization.Hat2) - .Replace("%hat3%", GlobalVars.UserCustomization.Hat3) - .Replace("%faced%", GlobalVars.UserCustomization.Face.Contains("http://") ? GlobalVars.UserCustomization.Face : GlobalPaths.faceGameDir + GlobalVars.UserCustomization.Face) - .Replace("%headd%", GlobalPaths.headGameDir + GlobalVars.UserCustomization.Head) - .Replace("%tshirtd%", GlobalVars.UserCustomization.TShirt.Contains("http://") ? GlobalVars.UserCustomization.TShirt : GlobalPaths.tshirtGameDir + GlobalVars.UserCustomization.TShirt) - .Replace("%shirtd%", GlobalVars.UserCustomization.Shirt.Contains("http://") ? GlobalVars.UserCustomization.Shirt : GlobalPaths.shirtGameDir + GlobalVars.UserCustomization.Shirt) - .Replace("%pantsd%", GlobalVars.UserCustomization.Pants.Contains("http://") ? GlobalVars.UserCustomization.Pants : GlobalPaths.pantsGameDir + GlobalVars.UserCustomization.Pants) - .Replace("%hat1d%", GlobalPaths.hatGameDir + GlobalVars.UserCustomization.Hat1) - .Replace("%hat2d%", GlobalPaths.hatGameDir + GlobalVars.UserCustomization.Hat2) - .Replace("%hat3d%", GlobalPaths.hatGameDir + GlobalVars.UserCustomization.Hat3) - .Replace("%headcolor%", GlobalVars.UserCustomization.HeadColorID.ToString()) - .Replace("%torsocolor%", GlobalVars.UserCustomization.TorsoColorID.ToString()) - .Replace("%larmcolor%", GlobalVars.UserCustomization.LeftArmColorID.ToString()) - .Replace("%llegcolor%", GlobalVars.UserCustomization.LeftLegColorID.ToString()) - .Replace("%rarmcolor%", GlobalVars.UserCustomization.RightArmColorID.ToString()) - .Replace("%rlegcolor%", GlobalVars.UserCustomization.RightLegColorID.ToString()) - .Replace("%md5launcher%", md5dir) - .Replace("%md5script%", info.ScriptMD5) - .Replace("%md5exe%", info.ClientMD5) - .Replace("%md5scriptd%", md5script) - .Replace("%md5exed%", md5exe) - .Replace("%md5s%", md5s) - .Replace("%md5sd%", md5sd) - .Replace("%limit%", GlobalVars.UserConfiguration.PlayerLimit.ToString()) - .Replace("%extra%", GlobalVars.UserCustomization.Extra) - .Replace("%hat4%", GlobalVars.UserCustomization.Extra) - .Replace("%extrad%", GlobalPaths.extraGameDir + GlobalVars.UserCustomization.Extra) - .Replace("%hat4d%", GlobalPaths.hatGameDir + GlobalVars.UserCustomization.Extra) - .Replace("%mapfiled%", GlobalPaths.BaseGameDir + GlobalVars.UserConfiguration.MapPathSnip.Replace(@"\\", @"\").Replace(@"/", @"\")) - .Replace("%mapfilec%", extractedCode.Contains("%mapfilec%") ? NovetusFuncs.CopyMapToRBXAsset() : "") - .Replace("%tripcode%", GlobalVars.PlayerTripcode) - .Replace("%scripttype%", Generator.GetNameForType(type)) - .Replace("%notifications%", GlobalVars.UserConfiguration.ShowServerNotifications.ToString().ToLower()) - .Replace("%loadout%", code.Contains("") ? GlobalVars.soloLoadout : GlobalVars.Loadout) - .Replace("%validatedextrafiles%", GlobalVars.ValidatedExtraFiles.ToString()) - .Replace("%argstring%", GetRawArgsForType(type, ClientName, luafile)) - .Replace("%tshirttexid%", GlobalVars.TShirtTextureID) - .Replace("%shirttexid%", GlobalVars.ShirtTextureID) - .Replace("%pantstexid%", GlobalVars.PantsTextureID) - .Replace("%facetexid%", GlobalVars.FaceTextureID) - .Replace("%tshirttexidlocal%", GlobalVars.TShirtTextureLocal) - .Replace("%shirttexidlocal%", GlobalVars.ShirtTextureLocal) - .Replace("%pantstexidlocal%", GlobalVars.PantsTextureLocal) - .Replace("%facetexlocal%", GlobalVars.FaceTextureLocal) - .Replace("%newgui%", GlobalVars.UserConfiguration.NewGUI.ToString().ToLower()); + string md5script = !info.AlreadyHasSecurity ? SecurityFuncs.GenerateMD5(GlobalPaths.ClientDir + @"\\" + GlobalVars.UserConfiguration.SelectedClient + @"\\content\\scripts\\" + GlobalPaths.ScriptName + ".lua") : ""; + string md5exe = !info.AlreadyHasSecurity ? SecurityFuncs.GenerateMD5(rbxexe) : ""; + string md5sd = "'" + md5exe + "','" + md5dir + "','" + md5script + "'"; + string md5s = "'" + info.ClientMD5 + "','" + md5dir + "','" + info.ScriptMD5 + "'"; + string compiled = extractedCode.Replace("%version%", GlobalVars.ProgramInformation.Version) + .Replace("%mapfile%", mapfile) + .Replace("%luafile%", luafile) + .Replace("%charapp%", GlobalVars.UserCustomization.CharacterID) + .Replace("%server%", GlobalVars.CurrentServer.ToString()) + .Replace("%ip%", GlobalVars.CurrentServer.ServerIP) + .Replace("%port%", GlobalVars.UserConfiguration.RobloxPort.ToString()) + .Replace("%joinport%", GlobalVars.CurrentServer.ServerPort.ToString()) + .Replace("%name%", GlobalVars.UserConfiguration.PlayerName) + .Replace("%icone%", ConvertIconStringToInt().ToString()) + .Replace("%icon%", GlobalVars.UserCustomization.Icon) + .Replace("%id%", GlobalVars.UserConfiguration.UserID.ToString()) + .Replace("%face%", GlobalVars.UserCustomization.Face) + .Replace("%head%", GlobalVars.UserCustomization.Head) + .Replace("%tshirt%", GlobalVars.UserCustomization.TShirt) + .Replace("%shirt%", GlobalVars.UserCustomization.Shirt) + .Replace("%pants%", GlobalVars.UserCustomization.Pants) + .Replace("%hat1%", GlobalVars.UserCustomization.Hat1) + .Replace("%hat2%", GlobalVars.UserCustomization.Hat2) + .Replace("%hat3%", GlobalVars.UserCustomization.Hat3) + .Replace("%faced%", GlobalVars.UserCustomization.Face.Contains("http://") ? GlobalVars.UserCustomization.Face : GlobalPaths.faceGameDir + GlobalVars.UserCustomization.Face) + .Replace("%headd%", GlobalPaths.headGameDir + GlobalVars.UserCustomization.Head) + .Replace("%tshirtd%", GlobalVars.UserCustomization.TShirt.Contains("http://") ? GlobalVars.UserCustomization.TShirt : GlobalPaths.tshirtGameDir + GlobalVars.UserCustomization.TShirt) + .Replace("%shirtd%", GlobalVars.UserCustomization.Shirt.Contains("http://") ? GlobalVars.UserCustomization.Shirt : GlobalPaths.shirtGameDir + GlobalVars.UserCustomization.Shirt) + .Replace("%pantsd%", GlobalVars.UserCustomization.Pants.Contains("http://") ? GlobalVars.UserCustomization.Pants : GlobalPaths.pantsGameDir + GlobalVars.UserCustomization.Pants) + .Replace("%hat1d%", GlobalPaths.hatGameDir + GlobalVars.UserCustomization.Hat1) + .Replace("%hat2d%", GlobalPaths.hatGameDir + GlobalVars.UserCustomization.Hat2) + .Replace("%hat3d%", GlobalPaths.hatGameDir + GlobalVars.UserCustomization.Hat3) + .Replace("%headcolor%", GlobalVars.UserCustomization.HeadColorID.ToString()) + .Replace("%torsocolor%", GlobalVars.UserCustomization.TorsoColorID.ToString()) + .Replace("%larmcolor%", GlobalVars.UserCustomization.LeftArmColorID.ToString()) + .Replace("%llegcolor%", GlobalVars.UserCustomization.LeftLegColorID.ToString()) + .Replace("%rarmcolor%", GlobalVars.UserCustomization.RightArmColorID.ToString()) + .Replace("%rlegcolor%", GlobalVars.UserCustomization.RightLegColorID.ToString()) + .Replace("%md5launcher%", md5dir) + .Replace("%md5script%", info.ScriptMD5) + .Replace("%md5exe%", info.ClientMD5) + .Replace("%md5scriptd%", md5script) + .Replace("%md5exed%", md5exe) + .Replace("%md5s%", md5s) + .Replace("%md5sd%", md5sd) + .Replace("%limit%", GlobalVars.UserConfiguration.PlayerLimit.ToString()) + .Replace("%extra%", GlobalVars.UserCustomization.Extra) + .Replace("%hat4%", GlobalVars.UserCustomization.Extra) + .Replace("%extrad%", GlobalPaths.extraGameDir + GlobalVars.UserCustomization.Extra) + .Replace("%hat4d%", GlobalPaths.hatGameDir + GlobalVars.UserCustomization.Extra) + .Replace("%mapfiled%", GlobalPaths.BaseGameDir + GlobalVars.UserConfiguration.MapPathSnip.Replace(@"\\", @"\").Replace(@"/", @"\")) + .Replace("%mapfilec%", extractedCode.Contains("%mapfilec%") ? NovetusFuncs.CopyMapToRBXAsset() : "") + .Replace("%tripcode%", GlobalVars.PlayerTripcode) + .Replace("%scripttype%", Generator.GetNameForType(type)) + .Replace("%notifications%", GlobalVars.UserConfiguration.ShowServerNotifications.ToString().ToLower()) + .Replace("%loadout%", code.Contains("") ? GlobalVars.soloLoadout : GlobalVars.Loadout) + .Replace("%validatedextrafiles%", GlobalVars.ValidatedExtraFiles.ToString()) + .Replace("%argstring%", GetRawArgsForType(type, ClientName, luafile)) + .Replace("%tshirttexid%", GlobalVars.TShirtTextureID) + .Replace("%shirttexid%", GlobalVars.ShirtTextureID) + .Replace("%pantstexid%", GlobalVars.PantsTextureID) + .Replace("%facetexid%", GlobalVars.FaceTextureID) + .Replace("%tshirttexidlocal%", GlobalVars.TShirtTextureLocal) + .Replace("%shirttexidlocal%", GlobalVars.ShirtTextureLocal) + .Replace("%pantstexidlocal%", GlobalVars.PantsTextureLocal) + .Replace("%facetexlocal%", GlobalVars.FaceTextureLocal) + .Replace("%newgui%", GlobalVars.UserConfiguration.NewGUI.ToString().ToLower()); - return compiled; + return compiled; + } } + #endregion } -#endregion + #endregion } -#endregion diff --git a/Novetus/NovetusCore/StorageAndFunctions/FileManagement.cs b/Novetus/NovetusCore/StorageAndFunctions/FileManagement.cs index 024a61f..7f0821b 100644 --- a/Novetus/NovetusCore/StorageAndFunctions/FileManagement.cs +++ b/Novetus/NovetusCore/StorageAndFunctions/FileManagement.cs @@ -14,1237 +14,947 @@ using System.Xml.Serialization; using System.Runtime.Versioning; #endregion -#region File Formats -public class FileFormat +namespace Novetus.Core { - #region Client Information - public class ClientInfo + #region File Formats + public class FileFormat { - public ClientInfo() + #region Client Information + public class ClientInfo { - UsesPlayerName = true; - UsesID = true; - Description = ""; - Warning = ""; - LegacyMode = false; - ClientMD5 = ""; - ScriptMD5 = ""; - Fix2007 = false; - AlreadyHasSecurity = false; - ClientLoadOptions = Settings.ClientLoadOptions.Client_2008AndUp; - SeperateFolders = false; - UsesCustomClientEXEName = false; - CustomClientEXEName = ""; - CommandLineArgs = "%args%"; + public ClientInfo() + { + UsesPlayerName = true; + UsesID = true; + Description = ""; + Warning = ""; + LegacyMode = false; + ClientMD5 = ""; + ScriptMD5 = ""; + Fix2007 = false; + AlreadyHasSecurity = false; + ClientLoadOptions = Settings.ClientLoadOptions.Client_2008AndUp; + SeperateFolders = false; + UsesCustomClientEXEName = false; + CustomClientEXEName = ""; + CommandLineArgs = "%args%"; + } + + public bool UsesPlayerName { get; set; } + public bool UsesID { get; set; } + public string Description { get; set; } + public string Warning { get; set; } + public bool LegacyMode { get; set; } + public string ClientMD5 { get; set; } + public string ScriptMD5 { get; set; } + public bool Fix2007 { get; set; } + public bool AlreadyHasSecurity { get; set; } + public bool SeperateFolders { get; set; } + public bool UsesCustomClientEXEName { get; set; } + public string CustomClientEXEName { get; set; } + public Settings.ClientLoadOptions ClientLoadOptions { get; set; } + public string CommandLineArgs { get; set; } } + #endregion - public bool UsesPlayerName { get; set; } - public bool UsesID { get; set; } - public string Description { get; set; } - public string Warning { get; set; } - public bool LegacyMode { get; set; } - public string ClientMD5 { get; set; } - public string ScriptMD5 { get; set; } - public bool Fix2007 { get; set; } - public bool AlreadyHasSecurity { get; set; } - public bool SeperateFolders { get; set; } - public bool UsesCustomClientEXEName { get; set; } - public string CustomClientEXEName { get; set; } - public Settings.ClientLoadOptions ClientLoadOptions { get; set; } - public string CommandLineArgs { get; set; } - } - #endregion - - #region Configuration - public class Config - { - public Config() + #region Configuration + public class Config { - SelectedClient = ""; - Map = ""; - CloseOnLaunch = false; - UserID = 0; - PlayerName = "Player"; - RobloxPort = 53640; - PlayerLimit = 12; - UPnP = false; - DisabledAssetSDKHelp = false; - DiscordPresence = true; - MapPath = ""; - MapPathSnip = ""; - GraphicsMode = Settings.Mode.Automatic; - ReShade = false; - QualityLevel = Settings.Level.Automatic; - LauncherStyle = Settings.Style.Stylish; - ReShadeFPSDisplay = false; - ReShadePerformanceMode = false; - AssetSDKFixerSaveBackups = true; - AlternateServerIP = ""; - DisableReshadeDelete = false; - ShowServerNotifications = false; - ServerBrowserServerName = "Novetus"; - ServerBrowserServerAddress = "localhost"; - Priority = ProcessPriorityClass.RealTime; - FirstServerLaunch = true; - NewGUI = false; - URIQuickConfigure = true; - BootstrapperShowUI = true; - WebProxyInitialSetupRequired = true; - WebProxyEnabled = false; + public Config() + { + SelectedClient = ""; + Map = ""; + CloseOnLaunch = false; + UserID = 0; + PlayerName = "Player"; + RobloxPort = 53640; + PlayerLimit = 12; + UPnP = false; + DisabledAssetSDKHelp = false; + DiscordPresence = true; + MapPath = ""; + MapPathSnip = ""; + GraphicsMode = Settings.Mode.Automatic; + ReShade = false; + QualityLevel = Settings.Level.Automatic; + LauncherStyle = Settings.Style.Stylish; + ReShadeFPSDisplay = false; + ReShadePerformanceMode = false; + AssetSDKFixerSaveBackups = true; + AlternateServerIP = ""; + DisableReshadeDelete = false; + ShowServerNotifications = false; + ServerBrowserServerName = "Novetus"; + ServerBrowserServerAddress = "localhost"; + Priority = ProcessPriorityClass.RealTime; + FirstServerLaunch = true; + NewGUI = false; + URIQuickConfigure = true; + BootstrapperShowUI = true; + WebProxyInitialSetupRequired = true; + WebProxyEnabled = false; + } + + public string SelectedClient { get; set; } + public string Map { get; set; } + public bool CloseOnLaunch { get; set; } + public int UserID { get; set; } + public string PlayerName { get; set; } + public int RobloxPort { get; set; } + public int PlayerLimit { get; set; } + public bool UPnP { get; set; } + public bool DisabledAssetSDKHelp { get; set; } + public bool DiscordPresence { get; set; } + public string MapPath { get; set; } + public string MapPathSnip { get; set; } + public Settings.Mode GraphicsMode { get; set; } + public bool ReShade { get; set; } + public Settings.Level QualityLevel { get; set; } + public Settings.Style LauncherStyle { get; set; } + public bool ReShadeFPSDisplay { get; set; } + public bool ReShadePerformanceMode { get; set; } + public bool AssetSDKFixerSaveBackups { get; set; } + public string AlternateServerIP { get; set; } + public bool DisableReshadeDelete { get; set; } + public bool ShowServerNotifications { get; set; } + public string ServerBrowserServerName { get; set; } + public string ServerBrowserServerAddress { get; set; } + public ProcessPriorityClass Priority { get; set; } + public bool FirstServerLaunch { get; set; } + public bool NewGUI { get; set; } + public bool URIQuickConfigure { get; set; } + public bool BootstrapperShowUI { get; set; } + public bool WebProxyInitialSetupRequired { get; set; } + public bool WebProxyEnabled { get; set; } } + #endregion - public string SelectedClient { get; set; } - public string Map { get; set; } - public bool CloseOnLaunch { get; set; } - public int UserID { get; set; } - public string PlayerName { get; set; } - public int RobloxPort { get; set; } - public int PlayerLimit { get; set; } - public bool UPnP { get; set; } - public bool DisabledAssetSDKHelp { get; set; } - public bool DiscordPresence { get; set; } - public string MapPath { get; set; } - public string MapPathSnip { get; set; } - public Settings.Mode GraphicsMode { get; set; } - public bool ReShade { get; set; } - public Settings.Level QualityLevel { get; set; } - public Settings.Style LauncherStyle { get; set; } - public bool ReShadeFPSDisplay { get; set; } - public bool ReShadePerformanceMode { get; set; } - public bool AssetSDKFixerSaveBackups { get; set; } - public string AlternateServerIP { get; set; } - public bool DisableReshadeDelete { get; set; } - public bool ShowServerNotifications { get; set; } - public string ServerBrowserServerName { get; set; } - public string ServerBrowserServerAddress { get; set; } - public ProcessPriorityClass Priority { get; set; } - public bool FirstServerLaunch { get; set; } - public bool NewGUI { get; set; } - public bool URIQuickConfigure { get; set; } - public bool BootstrapperShowUI { get; set; } - public bool WebProxyInitialSetupRequired { get; set; } - public bool WebProxyEnabled { get; set; } - } - #endregion - - #region Customization Configuration - public class CustomizationConfig - { - public CustomizationConfig() + #region Customization Configuration + public class CustomizationConfig { - Hat1 = "NoHat.rbxm"; - Hat2 = "NoHat.rbxm"; - Hat3 = "NoHat.rbxm"; - Face = "DefaultFace.rbxm"; - Head = "DefaultHead.rbxm"; - TShirt = "NoTShirt.rbxm"; - Shirt = "NoShirt.rbxm"; - Pants = "NoPants.rbxm"; - Icon = "NBC"; - Extra = "NoExtra.rbxm"; - HeadColorID = 24; - TorsoColorID = 23; - LeftArmColorID = 24; - RightArmColorID = 24; - LeftLegColorID = 119; - RightLegColorID = 119; - HeadColorString = "Color [A=255, R=245, G=205, B=47]"; - TorsoColorString = "Color [A=255, R=13, G=105, B=172]"; - LeftArmColorString = "Color [A=255, R=245, G=205, B=47]"; - RightArmColorString = "Color [A=255, R=245, G=205, B=47]"; - LeftLegColorString = "Color [A=255, R=164, G=189, B=71]"; - RightLegColorString = "Color [A=255, R=164, G=189, B=71]"; - ExtraSelectionIsHat = false; - ShowHatsInExtra = false; - CharacterID = ""; + public CustomizationConfig() + { + Hat1 = "NoHat.rbxm"; + Hat2 = "NoHat.rbxm"; + Hat3 = "NoHat.rbxm"; + Face = "DefaultFace.rbxm"; + Head = "DefaultHead.rbxm"; + TShirt = "NoTShirt.rbxm"; + Shirt = "NoShirt.rbxm"; + Pants = "NoPants.rbxm"; + Icon = "NBC"; + Extra = "NoExtra.rbxm"; + HeadColorID = 24; + TorsoColorID = 23; + LeftArmColorID = 24; + RightArmColorID = 24; + LeftLegColorID = 119; + RightLegColorID = 119; + HeadColorString = "Color [A=255, R=245, G=205, B=47]"; + TorsoColorString = "Color [A=255, R=13, G=105, B=172]"; + LeftArmColorString = "Color [A=255, R=245, G=205, B=47]"; + RightArmColorString = "Color [A=255, R=245, G=205, B=47]"; + LeftLegColorString = "Color [A=255, R=164, G=189, B=71]"; + RightLegColorString = "Color [A=255, R=164, G=189, B=71]"; + ExtraSelectionIsHat = false; + ShowHatsInExtra = false; + CharacterID = ""; + } + + public string Hat1 { get; set; } + public string Hat2 { get; set; } + public string Hat3 { get; set; } + public string Face { get; set; } + public string Head { get; set; } + public string TShirt { get; set; } + public string Shirt { get; set; } + public string Pants { get; set; } + public string Icon { get; set; } + public string Extra { get; set; } + public int HeadColorID { get; set; } + public int TorsoColorID { get; set; } + public int LeftArmColorID { get; set; } + public int RightArmColorID { get; set; } + public int LeftLegColorID { get; set; } + public int RightLegColorID { get; set; } + public string HeadColorString { get; set; } + public string TorsoColorString { get; set; } + public string LeftArmColorString { get; set; } + public string RightArmColorString { get; set; } + public string LeftLegColorString { get; set; } + public string RightLegColorString { get; set; } + public bool ExtraSelectionIsHat { get; set; } + public bool ShowHatsInExtra { get; set; } + public string CharacterID { get; set; } } + #endregion - public string Hat1 { get; set; } - public string Hat2 { get; set; } - public string Hat3 { get; set; } - public string Face { get; set; } - public string Head { get; set; } - public string TShirt { get; set; } - public string Shirt { get; set; } - public string Pants { get; set; } - public string Icon { get; set; } - public string Extra { get; set; } - public int HeadColorID { get; set; } - public int TorsoColorID { get; set; } - public int LeftArmColorID { get; set; } - public int RightArmColorID { get; set; } - public int LeftLegColorID { get; set; } - public int RightLegColorID { get; set; } - public string HeadColorString { get; set; } - public string TorsoColorString { get; set; } - public string LeftArmColorString { get; set; } - public string RightArmColorString { get; set; } - public string LeftLegColorString { get; set; } - public string RightLegColorString { get; set; } - public bool ExtraSelectionIsHat { get; set; } - public bool ShowHatsInExtra { get; set; } - public string CharacterID { get; set; } - } - #endregion - - #region Program Information - public class ProgramInfo - { - public ProgramInfo() + #region Program Information + public class ProgramInfo { - Version = ""; - Branch = ""; - DefaultClient = ""; - RegisterClient1 = ""; - RegisterClient2 = ""; - DefaultMap = ""; - //HACK + public ProgramInfo() + { + Version = ""; + Branch = ""; + DefaultClient = ""; + RegisterClient1 = ""; + RegisterClient2 = ""; + DefaultMap = ""; + //HACK #if NET4 NetVersion = ".NET 4.0"; #elif NET481 - NetVersion = ".NET 4.8"; + NetVersion = ".NET 4.8"; #endif - InitialBootup = true; - } + InitialBootup = true; + } - public string Version { get; set; } - public string Branch { get; set; } - public string DefaultClient { get; set; } - public string RegisterClient1 { get; set; } - public string RegisterClient2 { get; set; } - public string DefaultMap { get; set; } - public string NetVersion { get; set; } - public bool InitialBootup { get; set; } + public string Version { get; set; } + public string Branch { get; set; } + public string DefaultClient { get; set; } + public string RegisterClient1 { get; set; } + public string RegisterClient2 { get; set; } + public string DefaultMap { get; set; } + public string NetVersion { get; set; } + public bool InitialBootup { get; set; } + } + #endregion } #endregion -} -#endregion -#region Part Color Options -public class PartColor -{ - public string ColorName; - public int ColorID; - public string ColorRGB; - [XmlIgnore] - public Color ColorObject; - [XmlIgnore] - public string ColorGroup; - [XmlIgnore] - public string ColorRawName; - [XmlIgnore] - public Bitmap ColorImage; -} - -[XmlRoot("PartColors")] -public class PartColors -{ - [XmlArray("ColorList")] - public PartColor[] ColorList; -} - -public class PartColorLoader -{ - public static PartColor[] GetPartColors() + #region Part Color Options + public class PartColor { - if (File.Exists(GlobalPaths.ConfigDir + "\\" + GlobalPaths.PartColorXMLName)) + public string ColorName; + public int ColorID; + public string ColorRGB; + [XmlIgnore] + public Color ColorObject; + [XmlIgnore] + public string ColorGroup; + [XmlIgnore] + public string ColorRawName; + [XmlIgnore] + public Bitmap ColorImage; + } + + [XmlRoot("PartColors")] + public class PartColors + { + [XmlArray("ColorList")] + public PartColor[] ColorList; + } + + public class PartColorLoader + { + public static PartColor[] GetPartColors() { - XmlSerializer serializer = new XmlSerializer(typeof(PartColors)); - PartColors colors; - - using (FileStream fs = new FileStream(GlobalPaths.ConfigDir + "\\" + GlobalPaths.PartColorXMLName, FileMode.Open)) + if (File.Exists(GlobalPaths.ConfigDir + "\\" + GlobalPaths.PartColorXMLName)) { - colors = (PartColors)serializer.Deserialize(fs); - } + XmlSerializer serializer = new XmlSerializer(typeof(PartColors)); + PartColors colors; - foreach (var item in colors.ColorList) - { - string colorFixed = Regex.Replace(item.ColorRGB, @"[\[\]\{\}\(\)\<\> ]", ""); - string[] rgbValues = colorFixed.Split(','); - item.ColorObject = Color.FromArgb(Convert.ToInt32(rgbValues[0]), Convert.ToInt32(rgbValues[1]), Convert.ToInt32(rgbValues[2])); - - if (!(item.ColorName.Contains("[") && item.ColorName.Contains("]"))) + using (FileStream fs = new FileStream(GlobalPaths.ConfigDir + "\\" + GlobalPaths.PartColorXMLName, FileMode.Open)) { - item.ColorRawName = item.ColorName; - item.ColorName = "[Uncategorized]" + item.ColorName; - } - else - { - item.ColorRawName = item.ColorName; + colors = (PartColors)serializer.Deserialize(fs); } - int pFrom = item.ColorName.IndexOf("["); - int pTo = item.ColorName.IndexOf("]"); - item.ColorGroup = item.ColorName.Substring(pFrom + 1, pTo - pFrom - 1); - item.ColorName = item.ColorName.Replace(item.ColorGroup, "").Replace("[", "").Replace("]", ""); - item.ColorImage = GeneratePartColorIcon(item, 128); - } - - return colors.ColorList; - } - else - { - return null; - } - } - - //make faster - public static void AddPartColorsToListView(PartColor[] PartColorList, ListView ColorView, int imgsize, bool showIDs = false) - { - try - { - ImageList ColorImageList = new ImageList(); - ColorImageList.ImageSize = new Size(imgsize, imgsize); - ColorImageList.ColorDepth = ColorDepth.Depth32Bit; - ColorView.LargeImageList = ColorImageList; - ColorView.SmallImageList = ColorImageList; - - foreach (var item in PartColorList) - { - var lvi = new ListViewItem(item.ColorName); - lvi.Tag = item.ColorID; - - if (showIDs) + foreach (var item in colors.ColorList) { - lvi.Text = lvi.Text + " (" + item.ColorID + ")"; - } + string colorFixed = Regex.Replace(item.ColorRGB, @"[\[\]\{\}\(\)\<\> ]", ""); + string[] rgbValues = colorFixed.Split(','); + item.ColorObject = Color.FromArgb(Convert.ToInt32(rgbValues[0]), Convert.ToInt32(rgbValues[1]), Convert.ToInt32(rgbValues[2])); - var group = ColorView.Groups.Cast().FirstOrDefault(g => g.Header == item.ColorGroup); - - if (group == null) - { - group = new ListViewGroup(item.ColorGroup); - ColorView.Groups.Add(group); - } - - lvi.Group = group; - - if (item.ColorImage != null) - { - ColorImageList.Images.Add(item.ColorName, item.ColorImage); - lvi.ImageIndex = ColorImageList.Images.IndexOfKey(item.ColorName); - } - - ColorView.Items.Add(lvi); - } - - /*foreach (var group in ColorView.Groups.Cast()) - { - group.Header = group.Header + " (" + group.Items.Count + ")"; - }*/ - } -#if URI || LAUNCHER || CMD || BASICLAUNCHER - catch (Exception ex) - { - Util.LogExceptions(ex); -#else - catch (Exception) - { -#endif - } - } - - public static Bitmap GeneratePartColorIcon(PartColor color, int imgsize) - { - try - { - Bitmap Bmp = new Bitmap(imgsize, imgsize, PixelFormat.Format32bppArgb); - using (Graphics gfx = Graphics.FromImage(Bmp)) - using (SolidBrush brush = new SolidBrush(color.ColorObject)) - { - gfx.FillRectangle(brush, 0, 0, imgsize, imgsize); - } - - return Bmp; - } -#if URI || LAUNCHER || CMD || BASICLAUNCHER - catch (Exception ex) - { - Util.LogExceptions(ex); -#else - catch (Exception) - { -#endif - return null; - } - } - - public static PartColor FindPartColorByName(PartColor[] colors, string query) - { - if (File.Exists(GlobalPaths.ConfigDir + "\\" + GlobalPaths.PartColorXMLName)) - { - return colors.SingleOrDefault(item => query.Contains(item.ColorName)); - } - else - { - return null; - } - } - - public static PartColor FindPartColorByID(PartColor[] colors, string query) - { - if (File.Exists(GlobalPaths.ConfigDir + "\\" + GlobalPaths.PartColorXMLName)) - { - return colors.SingleOrDefault(item => query.Contains(item.ColorID.ToString())); - } - else - { - return null; - } - } -} -#endregion - -#region Content Provider Options -public class Provider -{ - public string Name; - public string URL; - public string Icon; -} - -[XmlRoot("ContentProviders")] -public class ContentProviders -{ - [XmlArray("Providers")] - public Provider[] Providers; -} - -public class OnlineClothing -{ - public static Provider[] GetContentProviders() - { - if (File.Exists(GlobalPaths.ConfigDir + "\\" + GlobalPaths.ContentProviderXMLName)) - { - XmlSerializer serializer = new XmlSerializer(typeof(ContentProviders)); - ContentProviders providers; - - using (FileStream fs = new FileStream(GlobalPaths.ConfigDir + "\\" + GlobalPaths.ContentProviderXMLName, FileMode.Open)) - { - providers = (ContentProviders)serializer.Deserialize(fs); - } - - return providers.Providers; - } - else - { - return null; - } - } - - public static Provider FindContentProviderByName(Provider[] providers, string query) - { - if (File.Exists(GlobalPaths.ConfigDir + "\\" + GlobalPaths.ContentProviderXMLName)) - { - return providers.SingleOrDefault(item => query.Contains(item.Name)); - } - else - { - return null; - } - } - - public static Provider FindContentProviderByURL(Provider[] providers, string query) - { - if (File.Exists(GlobalPaths.ConfigDir + "\\" + GlobalPaths.ContentProviderXMLName)) - { - return providers.SingleOrDefault(item => query.Contains(item.URL)); - } - else - { - return null; - } - } -} -#endregion - -#region Settings -public class Settings -{ - public enum Mode - { - Automatic = 0, - OpenGLStable = 1, - OpenGLExperimental = 2, - DirectX = 3 - } - - public enum Level - { - Automatic = 0, - VeryLow = 1, - Low = 2, - Medium = 3, - High = 4, - Ultra = 5, - Custom = 6 - } - - public enum Style - { - None = 0, - Extended = 1, - Compact = 2, - Stylish = 3 - } - - public enum ClientLoadOptions - { - Client_2007_NoGraphicsOptions = 0, - Client_2007 = 1, - Client_2008AndUp = 2, - Client_2008AndUp_LegacyOpenGL = 3, - Client_2008AndUp_QualityLevel21 = 4, - Client_2008AndUp_NoGraphicsOptions = 5, - Client_2008AndUp_ForceAutomatic = 6, - Client_2008AndUp_ForceAutomaticQL21 = 7, - Client_2008AndUp_HasCharacterOnlyShadowsLegacyOpenGL = 8 - } - - public static ClientLoadOptions GetClientLoadOptionsForBool(bool level) - { - switch (level) - { - case false: - return ClientLoadOptions.Client_2008AndUp; - default: - return ClientLoadOptions.Client_2007_NoGraphicsOptions; - } - } - - public static string GetPathForClientLoadOptions(ClientLoadOptions level) - { - string localAppdataRobloxPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Roblox"; - string appdataRobloxPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\Roblox"; - - if (!Directory.Exists(localAppdataRobloxPath)) - { - Directory.CreateDirectory(localAppdataRobloxPath); - } - - if (!Directory.Exists(appdataRobloxPath)) - { - Directory.CreateDirectory(appdataRobloxPath); - } - - switch (level) - { - case ClientLoadOptions.Client_2008AndUp_QualityLevel21: - case ClientLoadOptions.Client_2008AndUp_LegacyOpenGL: - case ClientLoadOptions.Client_2008AndUp_NoGraphicsOptions: - case ClientLoadOptions.Client_2008AndUp_ForceAutomatic: - case ClientLoadOptions.Client_2008AndUp_ForceAutomaticQL21: - case ClientLoadOptions.Client_2008AndUp_HasCharacterOnlyShadowsLegacyOpenGL: - case ClientLoadOptions.Client_2008AndUp: - return localAppdataRobloxPath; - default: - return appdataRobloxPath; - } - } -} - -#endregion - -#region Icon Loader - -public class IconLoader -{ - private OpenFileDialog openFileDialog1; - private string installOutcome = ""; - public bool CopyToItemDir = false; - public string ItemDir = ""; - public string ItemName = ""; - public string ItemPath = ""; - - public IconLoader() - { - openFileDialog1 = new OpenFileDialog() - { - FileName = "Select an icon .png file", - Filter = "Portable Network Graphics image (*.png)|*.png", - Title = "Open icon .png" - }; - } - - public void setInstallOutcome(string text) - { - installOutcome = text; - } - - public string getInstallOutcome() - { - return installOutcome; - } - - public void LoadImage() - { - string ItemNameFixed = ItemName.Replace(" ", ""); - string dir = CopyToItemDir ? ItemDir + "\\" + ItemNameFixed : GlobalPaths.extradir + "\\icons\\" + GlobalVars.UserConfiguration.PlayerName; - - if (openFileDialog1.ShowDialog() == DialogResult.OK) - { - try - { - Util.FixedFileCopy(openFileDialog1.FileName, dir + ".png", true); - - if (CopyToItemDir) - { - ItemPath = ItemDir + "\\" + ItemNameFixed + ".png"; - } - - installOutcome = "Icon " + openFileDialog1.SafeFileName + " installed!"; - } - catch (Exception ex) - { - installOutcome = "Error when installing icon: " + ex.Message; -#if URI || LAUNCHER || BASICLAUNCHER - Util.LogExceptions(ex); -#endif - } - } - } -} -#endregion - -#region File Management -public class FileManagement -{ - public static void ReadInfoFile(string infopath, bool other = false, string exepath = "") - { - //READ - string versionbranch, defaultclient, defaultmap, regclient1, - regclient2, extendedversionnumber, extendedversiontemplate, - extendedversionrevision, extendedversioneditchangelog, isLite, - initialBootup; - - INIFile ini = new INIFile(infopath); - - string section = "ProgramInfo"; - - //not using the GlobalVars definitions as those are empty until we fill them in. - versionbranch = ini.IniReadValue(section, "Branch", "0.0"); - defaultclient = ini.IniReadValue(section, "DefaultClient", "2009E"); - defaultmap = ini.IniReadValue(section, "DefaultMap", "Dev - Baseplate2048.rbxl"); - regclient1 = ini.IniReadValue(section, "UserAgentRegisterClient1", "2007M"); - regclient2 = ini.IniReadValue(section, "UserAgentRegisterClient2", "2009L"); - extendedversionnumber = ini.IniReadValue(section, "ExtendedVersionNumber", "False"); - extendedversioneditchangelog = ini.IniReadValue(section, "ExtendedVersionEditChangelog", "False"); - extendedversiontemplate = ini.IniReadValue(section, "ExtendedVersionTemplate", "%version%"); - extendedversionrevision = ini.IniReadValue(section, "ExtendedVersionRevision", "-1"); - isLite = ini.IniReadValue(section, "IsLite", "False"); - initialBootup = ini.IniReadValue(section, "InitialBootup", "True"); - - try - { - GlobalVars.ExtendedVersionNumber = Convert.ToBoolean(extendedversionnumber); - if (GlobalVars.ExtendedVersionNumber) - { - if (other) - { - if (!string.IsNullOrWhiteSpace(exepath)) + if (!(item.ColorName.Contains("[") && item.ColorName.Contains("]"))) { - var versionInfo = FileVersionInfo.GetVersionInfo(exepath); - GlobalVars.ProgramInformation.Version = extendedversiontemplate.Replace("%version%", versionbranch) - .Replace("%build%", versionInfo.ProductBuildPart.ToString()) - .Replace("%revision%", versionInfo.FilePrivatePart.ToString()) - .Replace("%extended-revision%", (!extendedversionrevision.Equals("-1") ? extendedversionrevision : "")); + item.ColorRawName = item.ColorName; + item.ColorName = "[Uncategorized]" + item.ColorName; } else { - return; + item.ColorRawName = item.ColorName; } - } - else - { - GlobalVars.ProgramInformation.Version = extendedversiontemplate.Replace("%version%", versionbranch) - .Replace("%build%", Assembly.GetExecutingAssembly().GetName().Version.Build.ToString()) - .Replace("%revision%", Assembly.GetExecutingAssembly().GetName().Version.Revision.ToString()) - .Replace("%extended-revision%", (!extendedversionrevision.Equals("-1") ? extendedversionrevision : "")); + + int pFrom = item.ColorName.IndexOf("["); + int pTo = item.ColorName.IndexOf("]"); + item.ColorGroup = item.ColorName.Substring(pFrom + 1, pTo - pFrom - 1); + item.ColorName = item.ColorName.Replace(item.ColorGroup, "").Replace("[", "").Replace("]", ""); + item.ColorImage = GeneratePartColorIcon(item, 128); } - bool changelogedit = Convert.ToBoolean(extendedversioneditchangelog); + return colors.ColorList; + } + else + { + return null; + } + } - if (changelogedit) + //make faster + public static void AddPartColorsToListView(PartColor[] PartColorList, ListView ColorView, int imgsize, bool showIDs = false) + { + try + { + ImageList ColorImageList = new ImageList(); + ColorImageList.ImageSize = new Size(imgsize, imgsize); + ColorImageList.ColorDepth = ColorDepth.Depth32Bit; + ColorView.LargeImageList = ColorImageList; + ColorView.SmallImageList = ColorImageList; + + foreach (var item in PartColorList) { - string changelog = GlobalPaths.BasePath + "\\changelog.txt"; - if (File.Exists(changelog)) + var lvi = new ListViewItem(item.ColorName); + lvi.Tag = item.ColorID; + + if (showIDs) { - string[] changeloglines = File.ReadAllLines(changelog); - if (!changeloglines[0].Equals(GlobalVars.ProgramInformation.Version)) + lvi.Text = lvi.Text + " (" + item.ColorID + ")"; + } + + var group = ColorView.Groups.Cast().FirstOrDefault(g => g.Header == item.ColorGroup); + + if (group == null) + { + group = new ListViewGroup(item.ColorGroup); + ColorView.Groups.Add(group); + } + + lvi.Group = group; + + if (item.ColorImage != null) + { + ColorImageList.Images.Add(item.ColorName, item.ColorImage); + lvi.ImageIndex = ColorImageList.Images.IndexOfKey(item.ColorName); + } + + ColorView.Items.Add(lvi); + } + + /*foreach (var group in ColorView.Groups.Cast()) + { + group.Header = group.Header + " (" + group.Items.Count + ")"; + }*/ + } +#if URI || LAUNCHER || CMD || BASICLAUNCHER + catch (Exception ex) + { + Util.LogExceptions(ex); +#else + catch (Exception) + { +#endif + } + } + + public static Bitmap GeneratePartColorIcon(PartColor color, int imgsize) + { + try + { + Bitmap Bmp = new Bitmap(imgsize, imgsize, PixelFormat.Format32bppArgb); + using (Graphics gfx = Graphics.FromImage(Bmp)) + using (SolidBrush brush = new SolidBrush(color.ColorObject)) + { + gfx.FillRectangle(brush, 0, 0, imgsize, imgsize); + } + + return Bmp; + } +#if URI || LAUNCHER || CMD || BASICLAUNCHER + catch (Exception ex) + { + Util.LogExceptions(ex); +#else + catch (Exception) + { +#endif + return null; + } + } + + public static PartColor FindPartColorByName(PartColor[] colors, string query) + { + if (File.Exists(GlobalPaths.ConfigDir + "\\" + GlobalPaths.PartColorXMLName)) + { + return colors.SingleOrDefault(item => query.Contains(item.ColorName)); + } + else + { + return null; + } + } + + public static PartColor FindPartColorByID(PartColor[] colors, string query) + { + if (File.Exists(GlobalPaths.ConfigDir + "\\" + GlobalPaths.PartColorXMLName)) + { + return colors.SingleOrDefault(item => query.Contains(item.ColorID.ToString())); + } + else + { + return null; + } + } + } + #endregion + + #region Content Provider Options + public class Provider + { + public string Name; + public string URL; + public string Icon; + } + + [XmlRoot("ContentProviders")] + public class ContentProviders + { + [XmlArray("Providers")] + public Provider[] Providers; + } + + public class OnlineClothing + { + public static Provider[] GetContentProviders() + { + if (File.Exists(GlobalPaths.ConfigDir + "\\" + GlobalPaths.ContentProviderXMLName)) + { + XmlSerializer serializer = new XmlSerializer(typeof(ContentProviders)); + ContentProviders providers; + + using (FileStream fs = new FileStream(GlobalPaths.ConfigDir + "\\" + GlobalPaths.ContentProviderXMLName, FileMode.Open)) + { + providers = (ContentProviders)serializer.Deserialize(fs); + } + + return providers.Providers; + } + else + { + return null; + } + } + + public static Provider FindContentProviderByName(Provider[] providers, string query) + { + if (File.Exists(GlobalPaths.ConfigDir + "\\" + GlobalPaths.ContentProviderXMLName)) + { + return providers.SingleOrDefault(item => query.Contains(item.Name)); + } + else + { + return null; + } + } + + public static Provider FindContentProviderByURL(Provider[] providers, string query) + { + if (File.Exists(GlobalPaths.ConfigDir + "\\" + GlobalPaths.ContentProviderXMLName)) + { + return providers.SingleOrDefault(item => query.Contains(item.URL)); + } + else + { + return null; + } + } + } + #endregion + + #region Settings + public class Settings + { + public enum Mode + { + Automatic = 0, + OpenGLStable = 1, + OpenGLExperimental = 2, + DirectX = 3 + } + + public enum Level + { + Automatic = 0, + VeryLow = 1, + Low = 2, + Medium = 3, + High = 4, + Ultra = 5, + Custom = 6 + } + + public enum Style + { + None = 0, + Extended = 1, + Compact = 2, + Stylish = 3 + } + + public enum ClientLoadOptions + { + Client_2007_NoGraphicsOptions = 0, + Client_2007 = 1, + Client_2008AndUp = 2, + Client_2008AndUp_LegacyOpenGL = 3, + Client_2008AndUp_QualityLevel21 = 4, + Client_2008AndUp_NoGraphicsOptions = 5, + Client_2008AndUp_ForceAutomatic = 6, + Client_2008AndUp_ForceAutomaticQL21 = 7, + Client_2008AndUp_HasCharacterOnlyShadowsLegacyOpenGL = 8 + } + + public static ClientLoadOptions GetClientLoadOptionsForBool(bool level) + { + switch (level) + { + case false: + return ClientLoadOptions.Client_2008AndUp; + default: + return ClientLoadOptions.Client_2007_NoGraphicsOptions; + } + } + + public static string GetPathForClientLoadOptions(ClientLoadOptions level) + { + string localAppdataRobloxPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Roblox"; + string appdataRobloxPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\Roblox"; + + if (!Directory.Exists(localAppdataRobloxPath)) + { + Directory.CreateDirectory(localAppdataRobloxPath); + } + + if (!Directory.Exists(appdataRobloxPath)) + { + Directory.CreateDirectory(appdataRobloxPath); + } + + switch (level) + { + case ClientLoadOptions.Client_2008AndUp_QualityLevel21: + case ClientLoadOptions.Client_2008AndUp_LegacyOpenGL: + case ClientLoadOptions.Client_2008AndUp_NoGraphicsOptions: + case ClientLoadOptions.Client_2008AndUp_ForceAutomatic: + case ClientLoadOptions.Client_2008AndUp_ForceAutomaticQL21: + case ClientLoadOptions.Client_2008AndUp_HasCharacterOnlyShadowsLegacyOpenGL: + case ClientLoadOptions.Client_2008AndUp: + return localAppdataRobloxPath; + default: + return appdataRobloxPath; + } + } + } + + #endregion + + #region Icon Loader + + public class IconLoader + { + private OpenFileDialog openFileDialog1; + private string installOutcome = ""; + public bool CopyToItemDir = false; + public string ItemDir = ""; + public string ItemName = ""; + public string ItemPath = ""; + + public IconLoader() + { + openFileDialog1 = new OpenFileDialog() + { + FileName = "Select an icon .png file", + Filter = "Portable Network Graphics image (*.png)|*.png", + Title = "Open icon .png" + }; + } + + public void setInstallOutcome(string text) + { + installOutcome = text; + } + + public string getInstallOutcome() + { + return installOutcome; + } + + public void LoadImage() + { + string ItemNameFixed = ItemName.Replace(" ", ""); + string dir = CopyToItemDir ? ItemDir + "\\" + ItemNameFixed : GlobalPaths.extradir + "\\icons\\" + GlobalVars.UserConfiguration.PlayerName; + + if (openFileDialog1.ShowDialog() == DialogResult.OK) + { + try + { + Util.FixedFileCopy(openFileDialog1.FileName, dir + ".png", true); + + if (CopyToItemDir) + { + ItemPath = ItemDir + "\\" + ItemNameFixed + ".png"; + } + + installOutcome = "Icon " + openFileDialog1.SafeFileName + " installed!"; + } + catch (Exception ex) + { + installOutcome = "Error when installing icon: " + ex.Message; +#if URI || LAUNCHER || BASICLAUNCHER + Util.LogExceptions(ex); +#endif + } + } + } + } + #endregion + + #region File Management + public class FileManagement + { + public static void ReadInfoFile(string infopath, bool other = false, string exepath = "") + { + //READ + string versionbranch, defaultclient, defaultmap, regclient1, + regclient2, extendedversionnumber, extendedversiontemplate, + extendedversionrevision, extendedversioneditchangelog, isLite, + initialBootup; + + INIFile ini = new INIFile(infopath); + + string section = "ProgramInfo"; + + //not using the GlobalVars definitions as those are empty until we fill them in. + versionbranch = ini.IniReadValue(section, "Branch", "0.0"); + defaultclient = ini.IniReadValue(section, "DefaultClient", "2009E"); + defaultmap = ini.IniReadValue(section, "DefaultMap", "Dev - Baseplate2048.rbxl"); + regclient1 = ini.IniReadValue(section, "UserAgentRegisterClient1", "2007M"); + regclient2 = ini.IniReadValue(section, "UserAgentRegisterClient2", "2009L"); + extendedversionnumber = ini.IniReadValue(section, "ExtendedVersionNumber", "False"); + extendedversioneditchangelog = ini.IniReadValue(section, "ExtendedVersionEditChangelog", "False"); + extendedversiontemplate = ini.IniReadValue(section, "ExtendedVersionTemplate", "%version%"); + extendedversionrevision = ini.IniReadValue(section, "ExtendedVersionRevision", "-1"); + isLite = ini.IniReadValue(section, "IsLite", "False"); + initialBootup = ini.IniReadValue(section, "InitialBootup", "True"); + + try + { + GlobalVars.ExtendedVersionNumber = Convert.ToBoolean(extendedversionnumber); + if (GlobalVars.ExtendedVersionNumber) + { + if (other) + { + if (!string.IsNullOrWhiteSpace(exepath)) { - changeloglines[0] = GlobalVars.ProgramInformation.Version; - File.WriteAllLines(changelog, changeloglines); + var versionInfo = FileVersionInfo.GetVersionInfo(exepath); + GlobalVars.ProgramInformation.Version = extendedversiontemplate.Replace("%version%", versionbranch) + .Replace("%build%", versionInfo.ProductBuildPart.ToString()) + .Replace("%revision%", versionInfo.FilePrivatePart.ToString()) + .Replace("%extended-revision%", (!extendedversionrevision.Equals("-1") ? extendedversionrevision : "")); + } + else + { + return; + } + } + else + { + GlobalVars.ProgramInformation.Version = extendedversiontemplate.Replace("%version%", versionbranch) + .Replace("%build%", Assembly.GetExecutingAssembly().GetName().Version.Build.ToString()) + .Replace("%revision%", Assembly.GetExecutingAssembly().GetName().Version.Revision.ToString()) + .Replace("%extended-revision%", (!extendedversionrevision.Equals("-1") ? extendedversionrevision : "")); + } + + bool changelogedit = Convert.ToBoolean(extendedversioneditchangelog); + + if (changelogedit) + { + string changelog = GlobalPaths.BasePath + "\\changelog.txt"; + if (File.Exists(changelog)) + { + string[] changeloglines = File.ReadAllLines(changelog); + if (!changeloglines[0].Equals(GlobalVars.ProgramInformation.Version)) + { + changeloglines[0] = GlobalVars.ProgramInformation.Version; + File.WriteAllLines(changelog, changeloglines); + } } } } - } - else - { - GlobalVars.ProgramInformation.Version = versionbranch; - } + else + { + GlobalVars.ProgramInformation.Version = versionbranch; + } - GlobalVars.ProgramInformation.Branch = versionbranch; - GlobalVars.ProgramInformation.DefaultClient = defaultclient; - GlobalVars.ProgramInformation.DefaultMap = defaultmap; - GlobalVars.ProgramInformation.RegisterClient1 = regclient1; - GlobalVars.ProgramInformation.RegisterClient2 = regclient2; - GlobalVars.ProgramInformation.InitialBootup = Convert.ToBoolean(initialBootup); - GlobalVars.UserConfiguration.SelectedClient = GlobalVars.ProgramInformation.DefaultClient; - GlobalVars.UserConfiguration.Map = GlobalVars.ProgramInformation.DefaultMap; - GlobalVars.UserConfiguration.MapPath = GlobalPaths.MapsDir + @"\\" + GlobalVars.ProgramInformation.DefaultMap; - GlobalVars.UserConfiguration.MapPathSnip = GlobalPaths.MapsDirBase + @"\\" + GlobalVars.ProgramInformation.DefaultMap; - } + GlobalVars.ProgramInformation.Branch = versionbranch; + GlobalVars.ProgramInformation.DefaultClient = defaultclient; + GlobalVars.ProgramInformation.DefaultMap = defaultmap; + GlobalVars.ProgramInformation.RegisterClient1 = regclient1; + GlobalVars.ProgramInformation.RegisterClient2 = regclient2; + GlobalVars.ProgramInformation.InitialBootup = Convert.ToBoolean(initialBootup); + GlobalVars.UserConfiguration.SelectedClient = GlobalVars.ProgramInformation.DefaultClient; + GlobalVars.UserConfiguration.Map = GlobalVars.ProgramInformation.DefaultMap; + GlobalVars.UserConfiguration.MapPath = GlobalPaths.MapsDir + @"\\" + GlobalVars.ProgramInformation.DefaultMap; + GlobalVars.UserConfiguration.MapPathSnip = GlobalPaths.MapsDirBase + @"\\" + GlobalVars.ProgramInformation.DefaultMap; + } #if URI || LAUNCHER || BASICLAUNCHER - catch (Exception ex) - { - Util.LogExceptions(ex); + catch (Exception ex) + { + Util.LogExceptions(ex); #else catch (Exception) { #endif - ReadInfoFile(infopath, other); + ReadInfoFile(infopath, other); + } } - } - public static void TurnOffInitialSequence() - { - //READ - INIFile ini = new INIFile(GlobalPaths.ConfigDir + "\\" + GlobalPaths.InfoName); - string section = "ProgramInfo"; - - string initialBootup = ini.IniReadValue(section, "InitialBootup", "True"); - if (Convert.ToBoolean(initialBootup) == true) + public static void TurnOffInitialSequence() { - ini.IniWriteValue(section, "InitialBootup", "False"); - } - } + //READ + INIFile ini = new INIFile(GlobalPaths.ConfigDir + "\\" + GlobalPaths.InfoName); + string section = "ProgramInfo"; - public static string ConfigUseOldValIfExists(INIFile ini, string section, string oldKey, string newKey, string val, bool write) - { - if (write) - { - if (!ini.IniValueExists(newKey)) + string initialBootup = ini.IniReadValue(section, "InitialBootup", "True"); + if (Convert.ToBoolean(initialBootup) == true) { - if (GlobalVars.ProgramInformation.InitialBootup) + ini.IniWriteValue(section, "InitialBootup", "False"); + } + } + + public static string ConfigUseOldValIfExists(INIFile ini, string section, string oldKey, string newKey, string val, bool write) + { + if (write) + { + if (!ini.IniValueExists(newKey)) { - if (ini.IniValueExists(oldKey)) + if (GlobalVars.ProgramInformation.InitialBootup) { - ini.IniWriteValue(section, oldKey, val); + if (ini.IniValueExists(oldKey)) + { + ini.IniWriteValue(section, oldKey, val); + } + else + { + ini.IniWriteValue(section, newKey, val); + } } else { - ini.IniWriteValue(section, newKey, val); + ini.IniWriteValue(section, oldKey, val); } } else { - ini.IniWriteValue(section, oldKey, val); + ini.IniWriteValue(section, newKey, val); + } + + return ""; + } + else + { + if (ini.IniValueExists(newKey)) + { + return ini.IniReadValue(section, newKey, val); + } + else + { + return ini.IniReadValue(section, oldKey, val); } } - else - { - ini.IniWriteValue(section, newKey, val); - } - - return ""; } - else + + private static int ValueInt(string val, int defaultVal) { - if (ini.IniValueExists(newKey)) + int res; + if (int.TryParse(val, out res)) { - return ini.IniReadValue(section, newKey, val); + return Convert.ToInt32(val); } else { - return ini.IniReadValue(section, oldKey, val); + return defaultVal; } } - } - private static int ValueInt(string val, int defaultVal) - { - int res; - if (int.TryParse(val, out res)) + private static bool ValueBool(string val, bool defaultVal) { - return Convert.ToInt32(val); - } - else - { - return defaultVal; - } - } - - private static bool ValueBool(string val, bool defaultVal) - { - bool res; - if (bool.TryParse(val, out res)) - { - return Convert.ToBoolean(val); - } - else - { - return defaultVal; - } - } - - public static void Config(string cfgpath, bool write, bool doubleCheck = false) - { - bool forcewrite = false; - - if (!File.Exists(cfgpath)) - { - // force write mode on if the file doesn't exist. - write = true; - forcewrite = true; - } - - if (write) - { - if (Util.IsWineRunning()) + bool res; + if (bool.TryParse(val, out res)) { - GlobalVars.UserConfiguration.LauncherStyle = Settings.Style.Extended; + return Convert.ToBoolean(val); } - - //WRITE - INIFile ini = new INIFile(cfgpath); - - string section = "Config"; - - ini.IniWriteValue(section, "CloseOnLaunch", GlobalVars.UserConfiguration.CloseOnLaunch.ToString()); - ini.IniWriteValue(section, "UserID", GlobalVars.UserConfiguration.UserID.ToString()); - ini.IniWriteValue(section, "PlayerName", GlobalVars.UserConfiguration.PlayerName.ToString()); - ini.IniWriteValue(section, "SelectedClient", GlobalVars.UserConfiguration.SelectedClient.ToString()); - ini.IniWriteValue(section, "Map", GlobalVars.UserConfiguration.Map.ToString()); - ini.IniWriteValue(section, "RobloxPort", GlobalVars.UserConfiguration.RobloxPort.ToString()); - ini.IniWriteValue(section, "PlayerLimit", GlobalVars.UserConfiguration.PlayerLimit.ToString()); - ini.IniWriteValue(section, "UPnP", GlobalVars.UserConfiguration.UPnP.ToString()); - ini.IniWriteValue(section, "DiscordRichPresence", GlobalVars.UserConfiguration.DiscordPresence.ToString()); - ini.IniWriteValue(section, "MapPath", GlobalVars.UserConfiguration.MapPath.ToString()); - ini.IniWriteValue(section, "MapPathSnip", GlobalVars.UserConfiguration.MapPathSnip.ToString()); - ini.IniWriteValue(section, "GraphicsMode", ((int)GlobalVars.UserConfiguration.GraphicsMode).ToString()); - ini.IniWriteValue(section, "ReShade", GlobalVars.UserConfiguration.ReShade.ToString()); - ini.IniWriteValue(section, "QualityLevel", ((int)GlobalVars.UserConfiguration.QualityLevel).ToString()); - ini.IniWriteValue(section, "Style", ((int)GlobalVars.UserConfiguration.LauncherStyle).ToString()); - ini.IniWriteValue(section, "AlternateServerIP", GlobalVars.UserConfiguration.AlternateServerIP.ToString()); - ini.IniWriteValue(section, "DisableReshadeDelete", GlobalVars.UserConfiguration.DisableReshadeDelete.ToString()); - ini.IniWriteValue(section, "ShowServerNotifications", GlobalVars.UserConfiguration.ShowServerNotifications.ToString()); - ini.IniWriteValue(section, "ServerBrowserServerName", GlobalVars.UserConfiguration.ServerBrowserServerName.ToString()); - ini.IniWriteValue(section, "ServerBrowserServerAddress", GlobalVars.UserConfiguration.ServerBrowserServerAddress.ToString()); - ini.IniWriteValue(section, "ClientLaunchPriority", ((int)GlobalVars.UserConfiguration.Priority).ToString()); - ini.IniWriteValue(section, "FirstServerLaunch", GlobalVars.UserConfiguration.FirstServerLaunch.ToString()); - ini.IniWriteValue(section, "NewGUI", GlobalVars.UserConfiguration.NewGUI.ToString()); - ini.IniWriteValue(section, "URIQuickConfigure", GlobalVars.UserConfiguration.URIQuickConfigure.ToString()); - ini.IniWriteValue(section, "BootstrapperShowUI", GlobalVars.UserConfiguration.BootstrapperShowUI.ToString()); - ini.IniWriteValue(section, "WebProxyInitialSetupRequired", GlobalVars.UserConfiguration.WebProxyInitialSetupRequired.ToString()); - ini.IniWriteValue(section, "WebProxyEnabled", GlobalVars.UserConfiguration.WebProxyEnabled.ToString()); - ConfigUseOldValIfExists(ini, section, "ItemMakerDisableHelpMessage", "AssetSDKDisableHelpMessage", GlobalVars.UserConfiguration.DisabledAssetSDKHelp.ToString(), write); - ConfigUseOldValIfExists(ini, section, "AssetLocalizerSaveBackups", "AssetSDKFixerSaveBackups", GlobalVars.UserConfiguration.AssetSDKFixerSaveBackups.ToString(), write); - - if (forcewrite) + else { - // try again.... - Config(cfgpath, false, doubleCheck); + return defaultVal; } } - else - { - try - { - //READ - string closeonlaunch, userid, name, selectedclient, - map, port, limit, upnp, - disablehelpmessage, discord, mappath, mapsnip, - graphics, reshade, qualitylevel, style, savebackups, altIP, - disReshadeDel, showNotifs, SB_Name, SB_Address, priority, - firstServerLaunch, newgui, quickconfigure, bootstrapper, - webproxysetup, webproxy; + public static void Config(string cfgpath, bool write, bool doubleCheck = false) + { + bool forcewrite = false; + + if (!File.Exists(cfgpath)) + { + // force write mode on if the file doesn't exist. + write = true; + forcewrite = true; + } + + if (write) + { + if (Util.IsWineRunning()) + { + GlobalVars.UserConfiguration.LauncherStyle = Settings.Style.Extended; + } + + //WRITE INIFile ini = new INIFile(cfgpath); string section = "Config"; - closeonlaunch = ini.IniReadValue(section, "CloseOnLaunch", GlobalVars.UserConfiguration.CloseOnLaunch.ToString()); - userid = ini.IniReadValue(section, "UserID", GlobalVars.UserConfiguration.UserID.ToString()); - name = ini.IniReadValue(section, "PlayerName", GlobalVars.UserConfiguration.PlayerName.ToString()); - selectedclient = ini.IniReadValue(section, "SelectedClient", GlobalVars.UserConfiguration.SelectedClient.ToString()); - map = ini.IniReadValue(section, "Map", GlobalVars.UserConfiguration.Map.ToString()); - port = ini.IniReadValue(section, "RobloxPort", GlobalVars.UserConfiguration.RobloxPort.ToString()); - limit = ini.IniReadValue(section, "PlayerLimit", GlobalVars.UserConfiguration.PlayerLimit.ToString()); - upnp = ini.IniReadValue(section, "UPnP", GlobalVars.UserConfiguration.UPnP.ToString()); - discord = ini.IniReadValue(section, "DiscordRichPresence", GlobalVars.UserConfiguration.DiscordPresence.ToString()); - mappath = ini.IniReadValue(section, "MapPath", GlobalVars.UserConfiguration.MapPath.ToString()); - mapsnip = ini.IniReadValue(section, "MapPathSnip", GlobalVars.UserConfiguration.MapPathSnip.ToString()); - graphics = ini.IniReadValue(section, "GraphicsMode", ((int)GlobalVars.UserConfiguration.GraphicsMode).ToString()); - reshade = ini.IniReadValue(section, "ReShade", GlobalVars.UserConfiguration.ReShade.ToString()); - qualitylevel = ini.IniReadValue(section, "QualityLevel", ((int)GlobalVars.UserConfiguration.QualityLevel).ToString()); - style = ini.IniReadValue(section, "Style", ((int)GlobalVars.UserConfiguration.LauncherStyle).ToString()); - altIP = ini.IniReadValue(section, "AlternateServerIP", GlobalVars.UserConfiguration.AlternateServerIP.ToString()); - disReshadeDel = ini.IniReadValue(section, "DisableReshadeDelete", GlobalVars.UserConfiguration.DisableReshadeDelete.ToString()); - showNotifs = ini.IniReadValue(section, "ShowServerNotifications", GlobalVars.UserConfiguration.ShowServerNotifications.ToString()); - SB_Name = ini.IniReadValue(section, "ServerBrowserServerName", GlobalVars.UserConfiguration.ServerBrowserServerName.ToString()); - SB_Address = ini.IniReadValue(section, "ServerBrowserServerAddress", GlobalVars.UserConfiguration.ServerBrowserServerAddress.ToString()); - priority = ini.IniReadValue(section, "ClientLaunchPriority", ((int)GlobalVars.UserConfiguration.Priority).ToString()); - firstServerLaunch = ini.IniReadValue(section, "FirstServerLaunch", GlobalVars.UserConfiguration.FirstServerLaunch.ToString()); - newgui = ini.IniReadValue(section, "NewGUI", GlobalVars.UserConfiguration.NewGUI.ToString()); - quickconfigure = ini.IniReadValue(section, "URIQuickConfigure", GlobalVars.UserConfiguration.URIQuickConfigure.ToString()); - bootstrapper = ini.IniReadValue(section, "BootstrapperShowUI", GlobalVars.UserConfiguration.BootstrapperShowUI.ToString()); - webproxysetup = ini.IniReadValue(section, "WebProxyInitialSetupRequired", GlobalVars.UserConfiguration.WebProxyInitialSetupRequired.ToString()); - webproxy = ini.IniReadValue(section, "WebProxyEnabled", GlobalVars.UserConfiguration.WebProxyEnabled.ToString()); - disablehelpmessage = ConfigUseOldValIfExists(ini, section, "ItemMakerDisableHelpMessage", "AssetSDKDisableHelpMessage", GlobalVars.UserConfiguration.DisabledAssetSDKHelp.ToString(), write); - savebackups = ConfigUseOldValIfExists(ini, section, "AssetLocalizerSaveBackups", "AssetSDKFixerSaveBackups", GlobalVars.UserConfiguration.AssetSDKFixerSaveBackups.ToString(), write); + ini.IniWriteValue(section, "CloseOnLaunch", GlobalVars.UserConfiguration.CloseOnLaunch.ToString()); + ini.IniWriteValue(section, "UserID", GlobalVars.UserConfiguration.UserID.ToString()); + ini.IniWriteValue(section, "PlayerName", GlobalVars.UserConfiguration.PlayerName.ToString()); + ini.IniWriteValue(section, "SelectedClient", GlobalVars.UserConfiguration.SelectedClient.ToString()); + ini.IniWriteValue(section, "Map", GlobalVars.UserConfiguration.Map.ToString()); + ini.IniWriteValue(section, "RobloxPort", GlobalVars.UserConfiguration.RobloxPort.ToString()); + ini.IniWriteValue(section, "PlayerLimit", GlobalVars.UserConfiguration.PlayerLimit.ToString()); + ini.IniWriteValue(section, "UPnP", GlobalVars.UserConfiguration.UPnP.ToString()); + ini.IniWriteValue(section, "DiscordRichPresence", GlobalVars.UserConfiguration.DiscordPresence.ToString()); + ini.IniWriteValue(section, "MapPath", GlobalVars.UserConfiguration.MapPath.ToString()); + ini.IniWriteValue(section, "MapPathSnip", GlobalVars.UserConfiguration.MapPathSnip.ToString()); + ini.IniWriteValue(section, "GraphicsMode", ((int)GlobalVars.UserConfiguration.GraphicsMode).ToString()); + ini.IniWriteValue(section, "ReShade", GlobalVars.UserConfiguration.ReShade.ToString()); + ini.IniWriteValue(section, "QualityLevel", ((int)GlobalVars.UserConfiguration.QualityLevel).ToString()); + ini.IniWriteValue(section, "Style", ((int)GlobalVars.UserConfiguration.LauncherStyle).ToString()); + ini.IniWriteValue(section, "AlternateServerIP", GlobalVars.UserConfiguration.AlternateServerIP.ToString()); + ini.IniWriteValue(section, "DisableReshadeDelete", GlobalVars.UserConfiguration.DisableReshadeDelete.ToString()); + ini.IniWriteValue(section, "ShowServerNotifications", GlobalVars.UserConfiguration.ShowServerNotifications.ToString()); + ini.IniWriteValue(section, "ServerBrowserServerName", GlobalVars.UserConfiguration.ServerBrowserServerName.ToString()); + ini.IniWriteValue(section, "ServerBrowserServerAddress", GlobalVars.UserConfiguration.ServerBrowserServerAddress.ToString()); + ini.IniWriteValue(section, "ClientLaunchPriority", ((int)GlobalVars.UserConfiguration.Priority).ToString()); + ini.IniWriteValue(section, "FirstServerLaunch", GlobalVars.UserConfiguration.FirstServerLaunch.ToString()); + ini.IniWriteValue(section, "NewGUI", GlobalVars.UserConfiguration.NewGUI.ToString()); + ini.IniWriteValue(section, "URIQuickConfigure", GlobalVars.UserConfiguration.URIQuickConfigure.ToString()); + ini.IniWriteValue(section, "BootstrapperShowUI", GlobalVars.UserConfiguration.BootstrapperShowUI.ToString()); + ini.IniWriteValue(section, "WebProxyInitialSetupRequired", GlobalVars.UserConfiguration.WebProxyInitialSetupRequired.ToString()); + ini.IniWriteValue(section, "WebProxyEnabled", GlobalVars.UserConfiguration.WebProxyEnabled.ToString()); + ConfigUseOldValIfExists(ini, section, "ItemMakerDisableHelpMessage", "AssetSDKDisableHelpMessage", GlobalVars.UserConfiguration.DisabledAssetSDKHelp.ToString(), write); + ConfigUseOldValIfExists(ini, section, "AssetLocalizerSaveBackups", "AssetSDKFixerSaveBackups", GlobalVars.UserConfiguration.AssetSDKFixerSaveBackups.ToString(), write); - FileFormat.Config DefaultConfiguration = new FileFormat.Config(); - DefaultConfiguration.SelectedClient = GlobalVars.ProgramInformation.DefaultClient; - DefaultConfiguration.Map = GlobalVars.ProgramInformation.DefaultMap; - DefaultConfiguration.MapPath = GlobalPaths.MapsDir + @"\\" + GlobalVars.ProgramInformation.DefaultMap; - DefaultConfiguration.MapPathSnip = GlobalPaths.MapsDirBase + @"\\" + GlobalVars.ProgramInformation.DefaultMap; - - GlobalVars.UserConfiguration.CloseOnLaunch = ValueBool(closeonlaunch, DefaultConfiguration.CloseOnLaunch); - - if (userid.Equals("0")) + if (forcewrite) { - NovetusFuncs.GeneratePlayerID(); - Config(cfgpath, true); - } - else - { - GlobalVars.UserConfiguration.UserID = ValueInt(userid, DefaultConfiguration.UserID); - } - - GlobalVars.UserConfiguration.PlayerName = name; - GlobalVars.UserConfiguration.SelectedClient = selectedclient; - GlobalVars.UserConfiguration.Map = map; - GlobalVars.UserConfiguration.RobloxPort = ValueInt(port, DefaultConfiguration.RobloxPort); - GlobalVars.UserConfiguration.PlayerLimit = ValueInt(limit, DefaultConfiguration.PlayerLimit); - GlobalVars.UserConfiguration.UPnP = ValueBool(upnp, DefaultConfiguration.UPnP); - GlobalVars.UserConfiguration.DisabledAssetSDKHelp = ValueBool(disablehelpmessage, DefaultConfiguration.DisabledAssetSDKHelp); - GlobalVars.UserConfiguration.DiscordPresence = ValueBool(discord, DefaultConfiguration.DiscordPresence); - GlobalVars.UserConfiguration.MapPathSnip = mapsnip; - GlobalVars.UserConfiguration.GraphicsMode = (Settings.Mode)ValueInt(graphics, Convert.ToInt32(DefaultConfiguration.GraphicsMode)); - GlobalVars.UserConfiguration.ReShade = ValueBool(reshade, DefaultConfiguration.ReShade); - GlobalVars.UserConfiguration.QualityLevel = (Settings.Level)ValueInt(qualitylevel, Convert.ToInt32(DefaultConfiguration.QualityLevel)); - GlobalVars.UserConfiguration.LauncherStyle = (Settings.Style)ValueInt(style, Convert.ToInt32(DefaultConfiguration.LauncherStyle)); - GlobalVars.UserConfiguration.AssetSDKFixerSaveBackups = ValueBool(savebackups, DefaultConfiguration.AssetSDKFixerSaveBackups); - GlobalVars.UserConfiguration.AlternateServerIP = altIP; - GlobalVars.UserConfiguration.DisableReshadeDelete = ValueBool(disReshadeDel, DefaultConfiguration.DisableReshadeDelete); - GlobalVars.UserConfiguration.ShowServerNotifications = ValueBool(showNotifs, DefaultConfiguration.ShowServerNotifications); - GlobalVars.UserConfiguration.ServerBrowserServerName = SB_Name; - GlobalVars.UserConfiguration.ServerBrowserServerAddress = SB_Address; - GlobalVars.UserConfiguration.Priority = (ProcessPriorityClass)ValueInt(priority, Convert.ToInt32(DefaultConfiguration.Priority)); - GlobalVars.UserConfiguration.FirstServerLaunch = ValueBool(firstServerLaunch, DefaultConfiguration.FirstServerLaunch); - GlobalVars.UserConfiguration.NewGUI = ValueBool(newgui, DefaultConfiguration.NewGUI); - GlobalVars.UserConfiguration.URIQuickConfigure = ValueBool(quickconfigure, DefaultConfiguration.URIQuickConfigure); - GlobalVars.UserConfiguration.BootstrapperShowUI = ValueBool(bootstrapper, DefaultConfiguration.BootstrapperShowUI); - GlobalVars.UserConfiguration.WebProxyInitialSetupRequired = ValueBool(webproxysetup, DefaultConfiguration.WebProxyInitialSetupRequired); - GlobalVars.UserConfiguration.WebProxyEnabled = ValueBool(webproxy, DefaultConfiguration.WebProxyEnabled); - - string oldMapath = Path.GetDirectoryName(GlobalVars.UserConfiguration.MapPath); - //update the map path if the file doesn't exist and write to config. - if (oldMapath.Equals(GlobalPaths.MapsDir.Replace(@"\\", @"\")) && File.Exists(mappath)) - { - GlobalVars.UserConfiguration.MapPath = mappath; - } - else - { - GlobalVars.UserConfiguration.MapPath = GlobalPaths.BasePath + @"\\" + GlobalVars.UserConfiguration.MapPathSnip; - Config(cfgpath, true); - } - - if (ResetMapIfNecessary()) - { - Config(cfgpath, true); - } - } -#if URI || LAUNCHER || BASICLAUNCHER - catch (Exception ex) - { - Util.LogExceptions(ex); -#else - catch (Exception) - { -#endif - Config(cfgpath, true); - } - } - - if (!forcewrite) - { - string curval = NovetusFuncs.GenerateAndReturnTripcode(); - if (!GlobalVars.PlayerTripcode.Equals(curval)) - { - GlobalVars.PlayerTripcode = curval; - } - -#if !BASICLAUNCHER - if (!File.Exists(GlobalPaths.ConfigDir + "\\" + GlobalPaths.ConfigNameCustomization)) - { - Customization(GlobalPaths.ConfigDir + "\\" + GlobalPaths.ConfigNameCustomization, true); - } - else - { - Customization(GlobalPaths.ConfigDir + "\\" + GlobalPaths.ConfigNameCustomization, write); - } - - ReShade(GlobalPaths.ConfigDir, "ReShade.ini", write); -#endif - } - } - - public static bool ResetMapIfNecessary() - { - if (!File.Exists(GlobalVars.UserConfiguration.MapPath)) - { - GlobalVars.UserConfiguration.Map = GlobalVars.ProgramInformation.DefaultMap; - GlobalVars.UserConfiguration.MapPath = GlobalPaths.MapsDir + @"\\" + GlobalVars.ProgramInformation.DefaultMap; - GlobalVars.UserConfiguration.MapPathSnip = GlobalPaths.MapsDirBase + @"\\" + GlobalVars.ProgramInformation.DefaultMap; - return true; - } - - return false; - } - - public static void Customization(string cfgpath, bool write) - { - if (write) - { - //WRITE - INIFile ini = new INIFile(cfgpath); - - string section = "Items"; - - ini.IniWriteValue(section, "Hat1", GlobalVars.UserCustomization.Hat1.ToString()); - ini.IniWriteValue(section, "Hat2", GlobalVars.UserCustomization.Hat2.ToString()); - ini.IniWriteValue(section, "Hat3", GlobalVars.UserCustomization.Hat3.ToString()); - ini.IniWriteValue(section, "Face", GlobalVars.UserCustomization.Face.ToString()); - ini.IniWriteValue(section, "Head", GlobalVars.UserCustomization.Head.ToString()); - ini.IniWriteValue(section, "TShirt", GlobalVars.UserCustomization.TShirt.ToString()); - ini.IniWriteValue(section, "Shirt", GlobalVars.UserCustomization.Shirt.ToString()); - ini.IniWriteValue(section, "Pants", GlobalVars.UserCustomization.Pants.ToString()); - ini.IniWriteValue(section, "Icon", GlobalVars.UserCustomization.Icon.ToString()); - ini.IniWriteValue(section, "Extra", GlobalVars.UserCustomization.Extra.ToString()); - - string section2 = "Colors"; - - ini.IniWriteValue(section2, "HeadColorID", GlobalVars.UserCustomization.HeadColorID.ToString()); - ini.IniWriteValue(section2, "HeadColorString", GlobalVars.UserCustomization.HeadColorString.ToString()); - ini.IniWriteValue(section2, "TorsoColorID", GlobalVars.UserCustomization.TorsoColorID.ToString()); - ini.IniWriteValue(section2, "TorsoColorString", GlobalVars.UserCustomization.TorsoColorString.ToString()); - ini.IniWriteValue(section2, "LeftArmColorID", GlobalVars.UserCustomization.LeftArmColorID.ToString()); - ini.IniWriteValue(section2, "LeftArmColorString", GlobalVars.UserCustomization.LeftArmColorString.ToString()); - ini.IniWriteValue(section2, "RightArmColorID", GlobalVars.UserCustomization.RightArmColorID.ToString()); - ini.IniWriteValue(section2, "RightArmColorString", GlobalVars.UserCustomization.RightArmColorString.ToString()); - ini.IniWriteValue(section2, "LeftLegColorID", GlobalVars.UserCustomization.LeftLegColorID.ToString()); - ini.IniWriteValue(section2, "LeftLegColorString", GlobalVars.UserCustomization.LeftLegColorString.ToString()); - ini.IniWriteValue(section2, "RightLegColorID", GlobalVars.UserCustomization.RightLegColorID.ToString()); - ini.IniWriteValue(section2, "RightLegColorString", GlobalVars.UserCustomization.RightLegColorString.ToString()); - - string section3 = "Other"; - - ini.IniWriteValue(section3, "CharacterID", GlobalVars.UserCustomization.CharacterID.ToString()); - ini.IniWriteValue(section3, "ExtraSelectionIsHat", GlobalVars.UserCustomization.ExtraSelectionIsHat.ToString()); - ini.IniWriteValue(section3, "ShowHatsOnExtra", GlobalVars.UserCustomization.ShowHatsInExtra.ToString()); - } - else - { - //READ - - try - { - string hat1, hat2, hat3, face, - head, tshirt, shirt, pants, icon, - extra, headcolorid, headcolorstring, torsocolorid, torsocolorstring, - larmid, larmstring, rarmid, rarmstring, llegid, - llegstring, rlegid, rlegstring, characterid, extraishat, showhatsonextra; - - INIFile ini = new INIFile(cfgpath); - - string section = "Items"; - - hat1 = ini.IniReadValue(section, "Hat1", GlobalVars.UserCustomization.Hat1.ToString()); - hat2 = ini.IniReadValue(section, "Hat2", GlobalVars.UserCustomization.Hat2.ToString()); - hat3 = ini.IniReadValue(section, "Hat3", GlobalVars.UserCustomization.Hat3.ToString()); - face = ini.IniReadValue(section, "Face", GlobalVars.UserCustomization.Face.ToString()); - head = ini.IniReadValue(section, "Head", GlobalVars.UserCustomization.Head.ToString()); - tshirt = ini.IniReadValue(section, "TShirt", GlobalVars.UserCustomization.TShirt.ToString()); - shirt = ini.IniReadValue(section, "Shirt", GlobalVars.UserCustomization.Shirt.ToString()); - pants = ini.IniReadValue(section, "Pants", GlobalVars.UserCustomization.Pants.ToString()); - icon = ini.IniReadValue(section, "Icon", GlobalVars.UserCustomization.Icon.ToString()); - extra = ini.IniReadValue(section, "Extra", GlobalVars.UserCustomization.Extra.ToString()); - - string section2 = "Colors"; - - headcolorid = ini.IniReadValue(section2, "HeadColorID", GlobalVars.UserCustomization.HeadColorID.ToString()); - headcolorstring = ini.IniReadValue(section2, "HeadColorString", GlobalVars.UserCustomization.HeadColorString.ToString()); - torsocolorid = ini.IniReadValue(section2, "TorsoColorID", GlobalVars.UserCustomization.TorsoColorID.ToString()); - torsocolorstring = ini.IniReadValue(section2, "TorsoColorString", GlobalVars.UserCustomization.TorsoColorString.ToString()); - larmid = ini.IniReadValue(section2, "LeftArmColorID", GlobalVars.UserCustomization.LeftArmColorID.ToString()); - larmstring = ini.IniReadValue(section2, "LeftArmColorString", GlobalVars.UserCustomization.LeftArmColorString.ToString()); - rarmid = ini.IniReadValue(section2, "RightArmColorID", GlobalVars.UserCustomization.RightArmColorID.ToString()); - rarmstring = ini.IniReadValue(section2, "RightArmColorString", GlobalVars.UserCustomization.RightArmColorString.ToString()); - llegid = ini.IniReadValue(section2, "LeftLegColorID", GlobalVars.UserCustomization.LeftLegColorID.ToString()); - llegstring = ini.IniReadValue(section2, "LeftLegColorString", GlobalVars.UserCustomization.LeftLegColorString.ToString()); - rlegid = ini.IniReadValue(section2, "RightLegColorID", GlobalVars.UserCustomization.RightLegColorID.ToString()); - rlegstring = ini.IniReadValue(section2, "RightLegColorString", GlobalVars.UserCustomization.RightLegColorString.ToString()); - - string section3 = "Other"; - - characterid = ini.IniReadValue(section3, "CharacterID", GlobalVars.UserCustomization.CharacterID.ToString()); - extraishat = ini.IniReadValue(section3, "ExtraSelectionIsHat", GlobalVars.UserCustomization.ExtraSelectionIsHat.ToString()); - showhatsonextra = ini.IniReadValue(section3, "ShowHatsOnExtra", GlobalVars.UserCustomization.ShowHatsInExtra.ToString()); - - FileFormat.CustomizationConfig DefaultCustomization = new FileFormat.CustomizationConfig(); - - GlobalVars.UserCustomization.Hat1 = hat1; - GlobalVars.UserCustomization.Hat2 = hat2; - GlobalVars.UserCustomization.Hat3 = hat3; - - GlobalVars.UserCustomization.HeadColorID = ValueInt(headcolorid, DefaultCustomization.HeadColorID); - GlobalVars.UserCustomization.TorsoColorID = ValueInt(torsocolorid, DefaultCustomization.TorsoColorID); - GlobalVars.UserCustomization.LeftArmColorID = ValueInt(larmid, DefaultCustomization.LeftArmColorID); - GlobalVars.UserCustomization.RightArmColorID = ValueInt(rarmid, DefaultCustomization.RightArmColorID); - GlobalVars.UserCustomization.LeftLegColorID = ValueInt(llegid, DefaultCustomization.LeftLegColorID); - GlobalVars.UserCustomization.RightLegColorID = ValueInt(rlegid, DefaultCustomization.RightArmColorID); - - GlobalVars.UserCustomization.HeadColorString = headcolorstring; - GlobalVars.UserCustomization.TorsoColorString = torsocolorstring; - GlobalVars.UserCustomization.LeftArmColorString = larmstring; - GlobalVars.UserCustomization.RightArmColorString = rarmstring; - GlobalVars.UserCustomization.LeftLegColorString = llegstring; - GlobalVars.UserCustomization.RightLegColorString = rlegstring; - - GlobalVars.UserCustomization.Face = face; - GlobalVars.UserCustomization.Head = head; - GlobalVars.UserCustomization.TShirt = tshirt; - GlobalVars.UserCustomization.Shirt = shirt; - GlobalVars.UserCustomization.Pants = pants; - GlobalVars.UserCustomization.Icon = icon; - - GlobalVars.UserCustomization.CharacterID = characterid; - GlobalVars.UserCustomization.Extra = extra; - GlobalVars.UserCustomization.ExtraSelectionIsHat = ValueBool(extraishat, DefaultCustomization.ExtraSelectionIsHat); - GlobalVars.UserCustomization.ShowHatsInExtra = ValueBool(showhatsonextra, DefaultCustomization.ShowHatsInExtra); - } -#if URI || LAUNCHER || BASICLAUNCHER - catch (Exception ex) - { - Util.LogExceptions(ex); -#else - catch (Exception) - { -#endif - Customization(cfgpath, true); - } - } - - ReloadLoadoutValue(); - } - - public static void ReShade(string cfgpath, string cfgname, bool write) - { - string fullpath = cfgpath + "\\" + cfgname; - - if (!File.Exists(fullpath)) - { - Util.FixedFileCopy(GlobalPaths.ConfigDir + "\\ReShade_default.ini", fullpath, false); - ReShadeValues(fullpath, write, true); - } - else - { - ReShadeValues(fullpath, write, true); - } - - string clientdir = GlobalPaths.ClientDir; - DirectoryInfo dinfo = new DirectoryInfo(clientdir); - DirectoryInfo[] Dirs = dinfo.GetDirectories(); - foreach (DirectoryInfo dir in Dirs) - { - string fulldirpath = dir.FullName + @"\" + cfgname; - string dllfilename = "opengl32.dll"; - string fulldllpath = dir.FullName + @"\" + dllfilename; - - if (GlobalVars.UserConfiguration.ReShade) - { - if (!File.Exists(fulldirpath)) - { - Util.FixedFileCopy(fullpath, fulldirpath, false); - ReShadeValues(fulldirpath, write, false); - } - else - { - ReShadeValues(fulldirpath, write, false); - } - - if (!File.Exists(fulldllpath)) - { - Util.FixedFileCopy(GlobalPaths.DataDir + "\\" + dllfilename, fulldllpath, false); + // try again.... + Config(cfgpath, false, doubleCheck); } } else - { - Util.FixedFileDelete(fulldirpath); - - if (!GlobalVars.UserConfiguration.DisableReshadeDelete) - { - Util.FixedFileDelete(fulldllpath); - } - } - } - } - - public static void ReShadeValues(string cfgpath, bool write, bool setglobals) - { - if (write) - { - //WRITE - INIFile ini = new INIFile(cfgpath); - - string section = "GENERAL"; - string section2 = "OVERLAY"; - - int FPS = GlobalVars.UserConfiguration.ReShadeFPSDisplay ? 1 : 0; - ini.IniWriteValue(section2, "ShowFPS", FPS.ToString()); - ini.IniWriteValue(section2, "ShowFrameTime", FPS.ToString()); - int PerformanceMode = GlobalVars.UserConfiguration.ReShadePerformanceMode ? 1 : 0; - ini.IniWriteValue(section, "PerformanceMode", PerformanceMode.ToString()); - } - else - { - //READ - string framerate, frametime, performance; - - INIFile ini = new INIFile(cfgpath); - - string section = "GENERAL"; - string section2 = "OVERLAY"; - - int FPS = GlobalVars.UserConfiguration.ReShadeFPSDisplay ? 1 : 0; - framerate = ini.IniReadValue(section2, "ShowFPS", FPS.ToString()); - frametime = ini.IniReadValue(section2, "ShowFrameTime", FPS.ToString()); - int PerformanceMode = GlobalVars.UserConfiguration.ReShadePerformanceMode ? 1 : 0; - performance = ini.IniReadValue(section, "PerformanceMode", PerformanceMode.ToString()); - - if (setglobals) { try { - switch (ValueInt(framerate, 0)) + //READ + string closeonlaunch, userid, name, selectedclient, + map, port, limit, upnp, + disablehelpmessage, discord, mappath, mapsnip, + graphics, reshade, qualitylevel, style, savebackups, altIP, + disReshadeDel, showNotifs, SB_Name, SB_Address, priority, + firstServerLaunch, newgui, quickconfigure, bootstrapper, + webproxysetup, webproxy; + + INIFile ini = new INIFile(cfgpath); + + string section = "Config"; + + closeonlaunch = ini.IniReadValue(section, "CloseOnLaunch", GlobalVars.UserConfiguration.CloseOnLaunch.ToString()); + userid = ini.IniReadValue(section, "UserID", GlobalVars.UserConfiguration.UserID.ToString()); + name = ini.IniReadValue(section, "PlayerName", GlobalVars.UserConfiguration.PlayerName.ToString()); + selectedclient = ini.IniReadValue(section, "SelectedClient", GlobalVars.UserConfiguration.SelectedClient.ToString()); + map = ini.IniReadValue(section, "Map", GlobalVars.UserConfiguration.Map.ToString()); + port = ini.IniReadValue(section, "RobloxPort", GlobalVars.UserConfiguration.RobloxPort.ToString()); + limit = ini.IniReadValue(section, "PlayerLimit", GlobalVars.UserConfiguration.PlayerLimit.ToString()); + upnp = ini.IniReadValue(section, "UPnP", GlobalVars.UserConfiguration.UPnP.ToString()); + discord = ini.IniReadValue(section, "DiscordRichPresence", GlobalVars.UserConfiguration.DiscordPresence.ToString()); + mappath = ini.IniReadValue(section, "MapPath", GlobalVars.UserConfiguration.MapPath.ToString()); + mapsnip = ini.IniReadValue(section, "MapPathSnip", GlobalVars.UserConfiguration.MapPathSnip.ToString()); + graphics = ini.IniReadValue(section, "GraphicsMode", ((int)GlobalVars.UserConfiguration.GraphicsMode).ToString()); + reshade = ini.IniReadValue(section, "ReShade", GlobalVars.UserConfiguration.ReShade.ToString()); + qualitylevel = ini.IniReadValue(section, "QualityLevel", ((int)GlobalVars.UserConfiguration.QualityLevel).ToString()); + style = ini.IniReadValue(section, "Style", ((int)GlobalVars.UserConfiguration.LauncherStyle).ToString()); + altIP = ini.IniReadValue(section, "AlternateServerIP", GlobalVars.UserConfiguration.AlternateServerIP.ToString()); + disReshadeDel = ini.IniReadValue(section, "DisableReshadeDelete", GlobalVars.UserConfiguration.DisableReshadeDelete.ToString()); + showNotifs = ini.IniReadValue(section, "ShowServerNotifications", GlobalVars.UserConfiguration.ShowServerNotifications.ToString()); + SB_Name = ini.IniReadValue(section, "ServerBrowserServerName", GlobalVars.UserConfiguration.ServerBrowserServerName.ToString()); + SB_Address = ini.IniReadValue(section, "ServerBrowserServerAddress", GlobalVars.UserConfiguration.ServerBrowserServerAddress.ToString()); + priority = ini.IniReadValue(section, "ClientLaunchPriority", ((int)GlobalVars.UserConfiguration.Priority).ToString()); + firstServerLaunch = ini.IniReadValue(section, "FirstServerLaunch", GlobalVars.UserConfiguration.FirstServerLaunch.ToString()); + newgui = ini.IniReadValue(section, "NewGUI", GlobalVars.UserConfiguration.NewGUI.ToString()); + quickconfigure = ini.IniReadValue(section, "URIQuickConfigure", GlobalVars.UserConfiguration.URIQuickConfigure.ToString()); + bootstrapper = ini.IniReadValue(section, "BootstrapperShowUI", GlobalVars.UserConfiguration.BootstrapperShowUI.ToString()); + webproxysetup = ini.IniReadValue(section, "WebProxyInitialSetupRequired", GlobalVars.UserConfiguration.WebProxyInitialSetupRequired.ToString()); + webproxy = ini.IniReadValue(section, "WebProxyEnabled", GlobalVars.UserConfiguration.WebProxyEnabled.ToString()); + disablehelpmessage = ConfigUseOldValIfExists(ini, section, "ItemMakerDisableHelpMessage", "AssetSDKDisableHelpMessage", GlobalVars.UserConfiguration.DisabledAssetSDKHelp.ToString(), write); + savebackups = ConfigUseOldValIfExists(ini, section, "AssetLocalizerSaveBackups", "AssetSDKFixerSaveBackups", GlobalVars.UserConfiguration.AssetSDKFixerSaveBackups.ToString(), write); + + FileFormat.Config DefaultConfiguration = new FileFormat.Config(); + DefaultConfiguration.SelectedClient = GlobalVars.ProgramInformation.DefaultClient; + DefaultConfiguration.Map = GlobalVars.ProgramInformation.DefaultMap; + DefaultConfiguration.MapPath = GlobalPaths.MapsDir + @"\\" + GlobalVars.ProgramInformation.DefaultMap; + DefaultConfiguration.MapPathSnip = GlobalPaths.MapsDirBase + @"\\" + GlobalVars.ProgramInformation.DefaultMap; + + GlobalVars.UserConfiguration.CloseOnLaunch = ValueBool(closeonlaunch, DefaultConfiguration.CloseOnLaunch); + + if (userid.Equals("0")) { - case int showFPSLine when showFPSLine == 1 && Convert.ToInt32(frametime) == 1: - GlobalVars.UserConfiguration.ReShadeFPSDisplay = true; - break; - default: - GlobalVars.UserConfiguration.ReShadeFPSDisplay = false; - break; + NovetusFuncs.GeneratePlayerID(); + Config(cfgpath, true); + } + else + { + GlobalVars.UserConfiguration.UserID = ValueInt(userid, DefaultConfiguration.UserID); } - switch (ValueInt(performance, 0)) + GlobalVars.UserConfiguration.PlayerName = name; + GlobalVars.UserConfiguration.SelectedClient = selectedclient; + GlobalVars.UserConfiguration.Map = map; + GlobalVars.UserConfiguration.RobloxPort = ValueInt(port, DefaultConfiguration.RobloxPort); + GlobalVars.UserConfiguration.PlayerLimit = ValueInt(limit, DefaultConfiguration.PlayerLimit); + GlobalVars.UserConfiguration.UPnP = ValueBool(upnp, DefaultConfiguration.UPnP); + GlobalVars.UserConfiguration.DisabledAssetSDKHelp = ValueBool(disablehelpmessage, DefaultConfiguration.DisabledAssetSDKHelp); + GlobalVars.UserConfiguration.DiscordPresence = ValueBool(discord, DefaultConfiguration.DiscordPresence); + GlobalVars.UserConfiguration.MapPathSnip = mapsnip; + GlobalVars.UserConfiguration.GraphicsMode = (Settings.Mode)ValueInt(graphics, Convert.ToInt32(DefaultConfiguration.GraphicsMode)); + GlobalVars.UserConfiguration.ReShade = ValueBool(reshade, DefaultConfiguration.ReShade); + GlobalVars.UserConfiguration.QualityLevel = (Settings.Level)ValueInt(qualitylevel, Convert.ToInt32(DefaultConfiguration.QualityLevel)); + GlobalVars.UserConfiguration.LauncherStyle = (Settings.Style)ValueInt(style, Convert.ToInt32(DefaultConfiguration.LauncherStyle)); + GlobalVars.UserConfiguration.AssetSDKFixerSaveBackups = ValueBool(savebackups, DefaultConfiguration.AssetSDKFixerSaveBackups); + GlobalVars.UserConfiguration.AlternateServerIP = altIP; + GlobalVars.UserConfiguration.DisableReshadeDelete = ValueBool(disReshadeDel, DefaultConfiguration.DisableReshadeDelete); + GlobalVars.UserConfiguration.ShowServerNotifications = ValueBool(showNotifs, DefaultConfiguration.ShowServerNotifications); + GlobalVars.UserConfiguration.ServerBrowserServerName = SB_Name; + GlobalVars.UserConfiguration.ServerBrowserServerAddress = SB_Address; + GlobalVars.UserConfiguration.Priority = (ProcessPriorityClass)ValueInt(priority, Convert.ToInt32(DefaultConfiguration.Priority)); + GlobalVars.UserConfiguration.FirstServerLaunch = ValueBool(firstServerLaunch, DefaultConfiguration.FirstServerLaunch); + GlobalVars.UserConfiguration.NewGUI = ValueBool(newgui, DefaultConfiguration.NewGUI); + GlobalVars.UserConfiguration.URIQuickConfigure = ValueBool(quickconfigure, DefaultConfiguration.URIQuickConfigure); + GlobalVars.UserConfiguration.BootstrapperShowUI = ValueBool(bootstrapper, DefaultConfiguration.BootstrapperShowUI); + GlobalVars.UserConfiguration.WebProxyInitialSetupRequired = ValueBool(webproxysetup, DefaultConfiguration.WebProxyInitialSetupRequired); + GlobalVars.UserConfiguration.WebProxyEnabled = ValueBool(webproxy, DefaultConfiguration.WebProxyEnabled); + + string oldMapath = Path.GetDirectoryName(GlobalVars.UserConfiguration.MapPath); + //update the map path if the file doesn't exist and write to config. + if (oldMapath.Equals(GlobalPaths.MapsDir.Replace(@"\\", @"\")) && File.Exists(mappath)) { - case 1: - GlobalVars.UserConfiguration.ReShadePerformanceMode = true; - break; - default: - GlobalVars.UserConfiguration.ReShadePerformanceMode = false; - break; + GlobalVars.UserConfiguration.MapPath = mappath; + } + else + { + GlobalVars.UserConfiguration.MapPath = GlobalPaths.BasePath + @"\\" + GlobalVars.UserConfiguration.MapPathSnip; + Config(cfgpath, true); + } + + if (ResetMapIfNecessary()) + { + Config(cfgpath, true); } } #if URI || LAUNCHER || BASICLAUNCHER @@ -1252,254 +962,547 @@ public class FileManagement { Util.LogExceptions(ex); #else - catch (Exception) - { + catch (Exception) + { #endif - ReShadeValues(cfgpath, true, setglobals); + Config(cfgpath, true); } } - } - } - public static bool InitColors() - { - try - { - if (File.Exists(GlobalPaths.ConfigDir + "\\" + GlobalPaths.PartColorXMLName)) + if (!forcewrite) { - GlobalVars.PartColorList = PartColorLoader.GetPartColors(); - GlobalVars.PartColorListConv = new List(); - GlobalVars.PartColorListConv.AddRange(GlobalVars.PartColorList); + string curval = NovetusFuncs.GenerateAndReturnTripcode(); + if (!GlobalVars.PlayerTripcode.Equals(curval)) + { + GlobalVars.PlayerTripcode = curval; + } + +#if !BASICLAUNCHER + if (!File.Exists(GlobalPaths.ConfigDir + "\\" + GlobalPaths.ConfigNameCustomization)) + { + Customization(GlobalPaths.ConfigDir + "\\" + GlobalPaths.ConfigNameCustomization, true); + } + else + { + Customization(GlobalPaths.ConfigDir + "\\" + GlobalPaths.ConfigNameCustomization, write); + } + + ReShade(GlobalPaths.ConfigDir, "ReShade.ini", write); +#endif + } + } + + public static bool ResetMapIfNecessary() + { + if (!File.Exists(GlobalVars.UserConfiguration.MapPath)) + { + GlobalVars.UserConfiguration.Map = GlobalVars.ProgramInformation.DefaultMap; + GlobalVars.UserConfiguration.MapPath = GlobalPaths.MapsDir + @"\\" + GlobalVars.ProgramInformation.DefaultMap; + GlobalVars.UserConfiguration.MapPathSnip = GlobalPaths.MapsDirBase + @"\\" + GlobalVars.ProgramInformation.DefaultMap; return true; } + + return false; + } + + public static void Customization(string cfgpath, bool write) + { + if (write) + { + //WRITE + INIFile ini = new INIFile(cfgpath); + + string section = "Items"; + + ini.IniWriteValue(section, "Hat1", GlobalVars.UserCustomization.Hat1.ToString()); + ini.IniWriteValue(section, "Hat2", GlobalVars.UserCustomization.Hat2.ToString()); + ini.IniWriteValue(section, "Hat3", GlobalVars.UserCustomization.Hat3.ToString()); + ini.IniWriteValue(section, "Face", GlobalVars.UserCustomization.Face.ToString()); + ini.IniWriteValue(section, "Head", GlobalVars.UserCustomization.Head.ToString()); + ini.IniWriteValue(section, "TShirt", GlobalVars.UserCustomization.TShirt.ToString()); + ini.IniWriteValue(section, "Shirt", GlobalVars.UserCustomization.Shirt.ToString()); + ini.IniWriteValue(section, "Pants", GlobalVars.UserCustomization.Pants.ToString()); + ini.IniWriteValue(section, "Icon", GlobalVars.UserCustomization.Icon.ToString()); + ini.IniWriteValue(section, "Extra", GlobalVars.UserCustomization.Extra.ToString()); + + string section2 = "Colors"; + + ini.IniWriteValue(section2, "HeadColorID", GlobalVars.UserCustomization.HeadColorID.ToString()); + ini.IniWriteValue(section2, "HeadColorString", GlobalVars.UserCustomization.HeadColorString.ToString()); + ini.IniWriteValue(section2, "TorsoColorID", GlobalVars.UserCustomization.TorsoColorID.ToString()); + ini.IniWriteValue(section2, "TorsoColorString", GlobalVars.UserCustomization.TorsoColorString.ToString()); + ini.IniWriteValue(section2, "LeftArmColorID", GlobalVars.UserCustomization.LeftArmColorID.ToString()); + ini.IniWriteValue(section2, "LeftArmColorString", GlobalVars.UserCustomization.LeftArmColorString.ToString()); + ini.IniWriteValue(section2, "RightArmColorID", GlobalVars.UserCustomization.RightArmColorID.ToString()); + ini.IniWriteValue(section2, "RightArmColorString", GlobalVars.UserCustomization.RightArmColorString.ToString()); + ini.IniWriteValue(section2, "LeftLegColorID", GlobalVars.UserCustomization.LeftLegColorID.ToString()); + ini.IniWriteValue(section2, "LeftLegColorString", GlobalVars.UserCustomization.LeftLegColorString.ToString()); + ini.IniWriteValue(section2, "RightLegColorID", GlobalVars.UserCustomization.RightLegColorID.ToString()); + ini.IniWriteValue(section2, "RightLegColorString", GlobalVars.UserCustomization.RightLegColorString.ToString()); + + string section3 = "Other"; + + ini.IniWriteValue(section3, "CharacterID", GlobalVars.UserCustomization.CharacterID.ToString()); + ini.IniWriteValue(section3, "ExtraSelectionIsHat", GlobalVars.UserCustomization.ExtraSelectionIsHat.ToString()); + ini.IniWriteValue(section3, "ShowHatsOnExtra", GlobalVars.UserCustomization.ShowHatsInExtra.ToString()); + } else { - goto Failure; + //READ + + try + { + string hat1, hat2, hat3, face, + head, tshirt, shirt, pants, icon, + extra, headcolorid, headcolorstring, torsocolorid, torsocolorstring, + larmid, larmstring, rarmid, rarmstring, llegid, + llegstring, rlegid, rlegstring, characterid, extraishat, showhatsonextra; + + INIFile ini = new INIFile(cfgpath); + + string section = "Items"; + + hat1 = ini.IniReadValue(section, "Hat1", GlobalVars.UserCustomization.Hat1.ToString()); + hat2 = ini.IniReadValue(section, "Hat2", GlobalVars.UserCustomization.Hat2.ToString()); + hat3 = ini.IniReadValue(section, "Hat3", GlobalVars.UserCustomization.Hat3.ToString()); + face = ini.IniReadValue(section, "Face", GlobalVars.UserCustomization.Face.ToString()); + head = ini.IniReadValue(section, "Head", GlobalVars.UserCustomization.Head.ToString()); + tshirt = ini.IniReadValue(section, "TShirt", GlobalVars.UserCustomization.TShirt.ToString()); + shirt = ini.IniReadValue(section, "Shirt", GlobalVars.UserCustomization.Shirt.ToString()); + pants = ini.IniReadValue(section, "Pants", GlobalVars.UserCustomization.Pants.ToString()); + icon = ini.IniReadValue(section, "Icon", GlobalVars.UserCustomization.Icon.ToString()); + extra = ini.IniReadValue(section, "Extra", GlobalVars.UserCustomization.Extra.ToString()); + + string section2 = "Colors"; + + headcolorid = ini.IniReadValue(section2, "HeadColorID", GlobalVars.UserCustomization.HeadColorID.ToString()); + headcolorstring = ini.IniReadValue(section2, "HeadColorString", GlobalVars.UserCustomization.HeadColorString.ToString()); + torsocolorid = ini.IniReadValue(section2, "TorsoColorID", GlobalVars.UserCustomization.TorsoColorID.ToString()); + torsocolorstring = ini.IniReadValue(section2, "TorsoColorString", GlobalVars.UserCustomization.TorsoColorString.ToString()); + larmid = ini.IniReadValue(section2, "LeftArmColorID", GlobalVars.UserCustomization.LeftArmColorID.ToString()); + larmstring = ini.IniReadValue(section2, "LeftArmColorString", GlobalVars.UserCustomization.LeftArmColorString.ToString()); + rarmid = ini.IniReadValue(section2, "RightArmColorID", GlobalVars.UserCustomization.RightArmColorID.ToString()); + rarmstring = ini.IniReadValue(section2, "RightArmColorString", GlobalVars.UserCustomization.RightArmColorString.ToString()); + llegid = ini.IniReadValue(section2, "LeftLegColorID", GlobalVars.UserCustomization.LeftLegColorID.ToString()); + llegstring = ini.IniReadValue(section2, "LeftLegColorString", GlobalVars.UserCustomization.LeftLegColorString.ToString()); + rlegid = ini.IniReadValue(section2, "RightLegColorID", GlobalVars.UserCustomization.RightLegColorID.ToString()); + rlegstring = ini.IniReadValue(section2, "RightLegColorString", GlobalVars.UserCustomization.RightLegColorString.ToString()); + + string section3 = "Other"; + + characterid = ini.IniReadValue(section3, "CharacterID", GlobalVars.UserCustomization.CharacterID.ToString()); + extraishat = ini.IniReadValue(section3, "ExtraSelectionIsHat", GlobalVars.UserCustomization.ExtraSelectionIsHat.ToString()); + showhatsonextra = ini.IniReadValue(section3, "ShowHatsOnExtra", GlobalVars.UserCustomization.ShowHatsInExtra.ToString()); + + FileFormat.CustomizationConfig DefaultCustomization = new FileFormat.CustomizationConfig(); + + GlobalVars.UserCustomization.Hat1 = hat1; + GlobalVars.UserCustomization.Hat2 = hat2; + GlobalVars.UserCustomization.Hat3 = hat3; + + GlobalVars.UserCustomization.HeadColorID = ValueInt(headcolorid, DefaultCustomization.HeadColorID); + GlobalVars.UserCustomization.TorsoColorID = ValueInt(torsocolorid, DefaultCustomization.TorsoColorID); + GlobalVars.UserCustomization.LeftArmColorID = ValueInt(larmid, DefaultCustomization.LeftArmColorID); + GlobalVars.UserCustomization.RightArmColorID = ValueInt(rarmid, DefaultCustomization.RightArmColorID); + GlobalVars.UserCustomization.LeftLegColorID = ValueInt(llegid, DefaultCustomization.LeftLegColorID); + GlobalVars.UserCustomization.RightLegColorID = ValueInt(rlegid, DefaultCustomization.RightArmColorID); + + GlobalVars.UserCustomization.HeadColorString = headcolorstring; + GlobalVars.UserCustomization.TorsoColorString = torsocolorstring; + GlobalVars.UserCustomization.LeftArmColorString = larmstring; + GlobalVars.UserCustomization.RightArmColorString = rarmstring; + GlobalVars.UserCustomization.LeftLegColorString = llegstring; + GlobalVars.UserCustomization.RightLegColorString = rlegstring; + + GlobalVars.UserCustomization.Face = face; + GlobalVars.UserCustomization.Head = head; + GlobalVars.UserCustomization.TShirt = tshirt; + GlobalVars.UserCustomization.Shirt = shirt; + GlobalVars.UserCustomization.Pants = pants; + GlobalVars.UserCustomization.Icon = icon; + + GlobalVars.UserCustomization.CharacterID = characterid; + GlobalVars.UserCustomization.Extra = extra; + GlobalVars.UserCustomization.ExtraSelectionIsHat = ValueBool(extraishat, DefaultCustomization.ExtraSelectionIsHat); + GlobalVars.UserCustomization.ShowHatsInExtra = ValueBool(showhatsonextra, DefaultCustomization.ShowHatsInExtra); + } +#if URI || LAUNCHER || BASICLAUNCHER + catch (Exception ex) + { + Util.LogExceptions(ex); +#else + catch (Exception) + { +#endif + Customization(cfgpath, true); + } + } + + ReloadLoadoutValue(); + } + + public static void ReShade(string cfgpath, string cfgname, bool write) + { + string fullpath = cfgpath + "\\" + cfgname; + + if (!File.Exists(fullpath)) + { + Util.FixedFileCopy(GlobalPaths.ConfigDir + "\\ReShade_default.ini", fullpath, false); + ReShadeValues(fullpath, write, true); + } + else + { + ReShadeValues(fullpath, write, true); + } + + string clientdir = GlobalPaths.ClientDir; + DirectoryInfo dinfo = new DirectoryInfo(clientdir); + DirectoryInfo[] Dirs = dinfo.GetDirectories(); + foreach (DirectoryInfo dir in Dirs) + { + string fulldirpath = dir.FullName + @"\" + cfgname; + string dllfilename = "opengl32.dll"; + string fulldllpath = dir.FullName + @"\" + dllfilename; + + if (GlobalVars.UserConfiguration.ReShade) + { + if (!File.Exists(fulldirpath)) + { + Util.FixedFileCopy(fullpath, fulldirpath, false); + ReShadeValues(fulldirpath, write, false); + } + else + { + ReShadeValues(fulldirpath, write, false); + } + + if (!File.Exists(fulldllpath)) + { + Util.FixedFileCopy(GlobalPaths.DataDir + "\\" + dllfilename, fulldllpath, false); + } + } + else + { + Util.FixedFileDelete(fulldirpath); + + if (!GlobalVars.UserConfiguration.DisableReshadeDelete) + { + Util.FixedFileDelete(fulldllpath); + } + } } } -#if URI || LAUNCHER || BASICLAUNCHER - catch (Exception ex) + + public static void ReShadeValues(string cfgpath, bool write, bool setglobals) { - Util.LogExceptions(ex); + if (write) + { + //WRITE + INIFile ini = new INIFile(cfgpath); + + string section = "GENERAL"; + string section2 = "OVERLAY"; + + int FPS = GlobalVars.UserConfiguration.ReShadeFPSDisplay ? 1 : 0; + ini.IniWriteValue(section2, "ShowFPS", FPS.ToString()); + ini.IniWriteValue(section2, "ShowFrameTime", FPS.ToString()); + int PerformanceMode = GlobalVars.UserConfiguration.ReShadePerformanceMode ? 1 : 0; + ini.IniWriteValue(section, "PerformanceMode", PerformanceMode.ToString()); + } + else + { + //READ + string framerate, frametime, performance; + + INIFile ini = new INIFile(cfgpath); + + string section = "GENERAL"; + string section2 = "OVERLAY"; + + int FPS = GlobalVars.UserConfiguration.ReShadeFPSDisplay ? 1 : 0; + framerate = ini.IniReadValue(section2, "ShowFPS", FPS.ToString()); + frametime = ini.IniReadValue(section2, "ShowFrameTime", FPS.ToString()); + int PerformanceMode = GlobalVars.UserConfiguration.ReShadePerformanceMode ? 1 : 0; + performance = ini.IniReadValue(section, "PerformanceMode", PerformanceMode.ToString()); + + if (setglobals) + { + try + { + switch (ValueInt(framerate, 0)) + { + case int showFPSLine when showFPSLine == 1 && Convert.ToInt32(frametime) == 1: + GlobalVars.UserConfiguration.ReShadeFPSDisplay = true; + break; + default: + GlobalVars.UserConfiguration.ReShadeFPSDisplay = false; + break; + } + + switch (ValueInt(performance, 0)) + { + case 1: + GlobalVars.UserConfiguration.ReShadePerformanceMode = true; + break; + default: + GlobalVars.UserConfiguration.ReShadePerformanceMode = false; + break; + } + } +#if URI || LAUNCHER || BASICLAUNCHER + catch (Exception ex) + { + Util.LogExceptions(ex); #else - catch (Exception) - { + catch (Exception) + { #endif - goto Failure; + ReShadeValues(cfgpath, true, setglobals); + } + } + } } - Failure: - return false; - } - - public static bool HasColorsChanged() - { - try + public static bool InitColors() { - PartColor[] tempList; - - if (File.Exists(GlobalPaths.ConfigDir + "\\" + GlobalPaths.PartColorXMLName)) + try { - tempList = PartColorLoader.GetPartColors(); - if (tempList.Length != GlobalVars.PartColorList.Length) + if (File.Exists(GlobalPaths.ConfigDir + "\\" + GlobalPaths.PartColorXMLName)) { + GlobalVars.PartColorList = PartColorLoader.GetPartColors(); + GlobalVars.PartColorListConv = new List(); + GlobalVars.PartColorListConv.AddRange(GlobalVars.PartColorList); return true; } else { - return false; + goto Failure; } } - else - { - goto Failure; - } - } #if URI || LAUNCHER || BASICLAUNCHER - catch (Exception ex) - { - Util.LogExceptions(ex); + catch (Exception ex) + { + Util.LogExceptions(ex); #else catch (Exception) { #endif - goto Failure; + goto Failure; + } + + Failure: + return false; } - Failure: - return false; - } + public static bool HasColorsChanged() + { + try + { + PartColor[] tempList; + + if (File.Exists(GlobalPaths.ConfigDir + "\\" + GlobalPaths.PartColorXMLName)) + { + tempList = PartColorLoader.GetPartColors(); + if (tempList.Length != GlobalVars.PartColorList.Length) + { + return true; + } + else + { + return false; + } + } + else + { + goto Failure; + } + } +#if URI || LAUNCHER || BASICLAUNCHER + catch (Exception ex) + { + Util.LogExceptions(ex); +#else + catch (Exception) + { +#endif + goto Failure; + } + + Failure: + return false; + } #if LAUNCHER public static void ResetConfigValues(Settings.Style style) #else - public static void ResetConfigValues() + public static void ResetConfigValues() #endif - { - bool WebProxySetupComplete = GlobalVars.UserConfiguration.WebProxyInitialSetupRequired; - bool WebProxy = GlobalVars.UserConfiguration.WebProxyEnabled; + { + bool WebProxySetupComplete = GlobalVars.UserConfiguration.WebProxyInitialSetupRequired; + bool WebProxy = GlobalVars.UserConfiguration.WebProxyEnabled; - GlobalVars.UserConfiguration = new FileFormat.Config(); - GlobalVars.UserConfiguration.SelectedClient = GlobalVars.ProgramInformation.DefaultClient; - GlobalVars.UserConfiguration.Map = GlobalVars.ProgramInformation.DefaultMap; - GlobalVars.UserConfiguration.MapPath = GlobalPaths.MapsDir + @"\\" + GlobalVars.ProgramInformation.DefaultMap; - GlobalVars.UserConfiguration.MapPathSnip = GlobalPaths.MapsDirBase + @"\\" + GlobalVars.ProgramInformation.DefaultMap; + GlobalVars.UserConfiguration = new FileFormat.Config(); + GlobalVars.UserConfiguration.SelectedClient = GlobalVars.ProgramInformation.DefaultClient; + GlobalVars.UserConfiguration.Map = GlobalVars.ProgramInformation.DefaultMap; + GlobalVars.UserConfiguration.MapPath = GlobalPaths.MapsDir + @"\\" + GlobalVars.ProgramInformation.DefaultMap; + GlobalVars.UserConfiguration.MapPathSnip = GlobalPaths.MapsDirBase + @"\\" + GlobalVars.ProgramInformation.DefaultMap; #if LAUNCHER GlobalVars.UserConfiguration.LauncherStyle = style; #endif - GlobalVars.UserConfiguration.WebProxyInitialSetupRequired = WebProxySetupComplete; - GlobalVars.UserConfiguration.WebProxyEnabled = WebProxy; - NovetusFuncs.GeneratePlayerID(); - ResetCustomizationValues(); - } - - public static void ResetCustomizationValues() - { - GlobalVars.UserCustomization = new FileFormat.CustomizationConfig(); - ReloadLoadoutValue(); - } - - public static void ReloadLoadoutValue(bool localizeOnlineClothing = false) - { - string hat1 = (!GlobalVars.UserCustomization.Hat1.EndsWith("-Solo.rbxm")) ? GlobalVars.UserCustomization.Hat1 : "NoHat.rbxm"; - string hat2 = (!GlobalVars.UserCustomization.Hat2.EndsWith("-Solo.rbxm")) ? GlobalVars.UserCustomization.Hat2 : "NoHat.rbxm"; - string hat3 = (!GlobalVars.UserCustomization.Hat3.EndsWith("-Solo.rbxm")) ? GlobalVars.UserCustomization.Hat3 : "NoHat.rbxm"; - string extra = (!GlobalVars.UserCustomization.Extra.EndsWith("-Solo.rbxm")) ? GlobalVars.UserCustomization.Extra : "NoExtra.rbxm"; - - GlobalVars.Loadout = "'" + hat1 + "','" + - hat2 + "','" + - hat3 + "'," + - GlobalVars.UserCustomization.HeadColorID + "," + - GlobalVars.UserCustomization.TorsoColorID + "," + - GlobalVars.UserCustomization.LeftArmColorID + "," + - GlobalVars.UserCustomization.RightArmColorID + "," + - GlobalVars.UserCustomization.LeftLegColorID + "," + - GlobalVars.UserCustomization.RightLegColorID + ",'" + - GlobalVars.UserCustomization.TShirt + "','" + - GlobalVars.UserCustomization.Shirt + "','" + - GlobalVars.UserCustomization.Pants + "','" + - GlobalVars.UserCustomization.Face + "','" + - GlobalVars.UserCustomization.Head + "','" + - GlobalVars.UserCustomization.Icon + "','" + - extra + "'"; - - GlobalVars.soloLoadout = "'" + GlobalVars.UserCustomization.Hat1 + "','" + - GlobalVars.UserCustomization.Hat2 + "','" + - GlobalVars.UserCustomization.Hat3 + "'," + - GlobalVars.UserCustomization.HeadColorID + "," + - GlobalVars.UserCustomization.TorsoColorID + "," + - GlobalVars.UserCustomization.LeftArmColorID + "," + - GlobalVars.UserCustomization.RightArmColorID + "," + - GlobalVars.UserCustomization.LeftLegColorID + "," + - GlobalVars.UserCustomization.RightLegColorID + ",'" + - GlobalVars.UserCustomization.TShirt + "','" + - GlobalVars.UserCustomization.Shirt + "','" + - GlobalVars.UserCustomization.Pants + "','" + - GlobalVars.UserCustomization.Face + "','" + - GlobalVars.UserCustomization.Head + "','" + - GlobalVars.UserCustomization.Icon + "','" + - GlobalVars.UserCustomization.Extra + "'"; - - if (localizeOnlineClothing) - { - GlobalVars.TShirtTextureID = NovetusFuncs.GetItemTextureID(GlobalVars.UserCustomization.TShirt, "TShirt", new AssetCacheDefBasic("ShirtGraphic", new string[] { "Graphic" })); - GlobalVars.ShirtTextureID = NovetusFuncs.GetItemTextureID(GlobalVars.UserCustomization.Shirt, "Shirt", new AssetCacheDefBasic("Shirt", new string[] { "ShirtTemplate" })); - GlobalVars.PantsTextureID = NovetusFuncs.GetItemTextureID(GlobalVars.UserCustomization.Pants, "Pants", new AssetCacheDefBasic("Pants", new string[] { "PantsTemplate" })); - GlobalVars.FaceTextureID = NovetusFuncs.GetItemTextureID(GlobalVars.UserCustomization.Face, "Face", new AssetCacheDefBasic("Decal", new string[] { "Texture" })); - - GlobalVars.TShirtTextureLocal = NovetusFuncs.GetItemTextureLocalPath(GlobalVars.TShirtTextureID, "TShirt"); - GlobalVars.ShirtTextureLocal = NovetusFuncs.GetItemTextureLocalPath(GlobalVars.ShirtTextureID, "Shirt"); - GlobalVars.PantsTextureLocal = NovetusFuncs.GetItemTextureLocalPath(GlobalVars.PantsTextureID, "Pants"); - GlobalVars.FaceTextureLocal = NovetusFuncs.GetItemTextureLocalPath(GlobalVars.FaceTextureID, "Face"); + GlobalVars.UserConfiguration.WebProxyInitialSetupRequired = WebProxySetupComplete; + GlobalVars.UserConfiguration.WebProxyEnabled = WebProxy; + NovetusFuncs.GeneratePlayerID(); + ResetCustomizationValues(); } - } - public static void CreateAssetCacheDirectories() - { - if (!Directory.Exists(GlobalPaths.AssetCacheDirAssets)) + public static void ResetCustomizationValues() { - Directory.CreateDirectory(GlobalPaths.AssetCacheDirAssets); + GlobalVars.UserCustomization = new FileFormat.CustomizationConfig(); + ReloadLoadoutValue(); } - } - public static void CreateInitialFileListIfNeededMulti() - { - if (GlobalVars.NoFileList) - return; - - string filePath = GlobalPaths.ConfigDir + "\\InitialFileList.txt"; - - if (!File.Exists(filePath)) + public static void ReloadLoadoutValue(bool localizeOnlineClothing = false) { - Util.ConsolePrint("WARNING - No file list detected. Generating Initial File List.", 5); - Thread t = new Thread(CreateInitialFileList); - t.IsBackground = true; - t.Start(); - } - else - { - int lineCount = File.ReadLines(filePath).Count(); - int fileCount = 0; + string hat1 = (!GlobalVars.UserCustomization.Hat1.EndsWith("-Solo.rbxm")) ? GlobalVars.UserCustomization.Hat1 : "NoHat.rbxm"; + string hat2 = (!GlobalVars.UserCustomization.Hat2.EndsWith("-Solo.rbxm")) ? GlobalVars.UserCustomization.Hat2 : "NoHat.rbxm"; + string hat3 = (!GlobalVars.UserCustomization.Hat3.EndsWith("-Solo.rbxm")) ? GlobalVars.UserCustomization.Hat3 : "NoHat.rbxm"; + string extra = (!GlobalVars.UserCustomization.Extra.EndsWith("-Solo.rbxm")) ? GlobalVars.UserCustomization.Extra : "NoExtra.rbxm"; - string filterPath = GlobalPaths.ConfigDir + @"\\" + GlobalPaths.InitialFileListIgnoreFilterName; - string[] fileListToIgnore = File.ReadAllLines(filterPath); + GlobalVars.Loadout = "'" + hat1 + "','" + + hat2 + "','" + + hat3 + "'," + + GlobalVars.UserCustomization.HeadColorID + "," + + GlobalVars.UserCustomization.TorsoColorID + "," + + GlobalVars.UserCustomization.LeftArmColorID + "," + + GlobalVars.UserCustomization.RightArmColorID + "," + + GlobalVars.UserCustomization.LeftLegColorID + "," + + GlobalVars.UserCustomization.RightLegColorID + ",'" + + GlobalVars.UserCustomization.TShirt + "','" + + GlobalVars.UserCustomization.Shirt + "','" + + GlobalVars.UserCustomization.Pants + "','" + + GlobalVars.UserCustomization.Face + "','" + + GlobalVars.UserCustomization.Head + "','" + + GlobalVars.UserCustomization.Icon + "','" + + extra + "'"; - DirectoryInfo dinfo = new DirectoryInfo(GlobalPaths.RootPath); - FileInfo[] Files = dinfo.GetFiles("*.*", SearchOption.AllDirectories); - foreach (FileInfo file in Files) + GlobalVars.soloLoadout = "'" + GlobalVars.UserCustomization.Hat1 + "','" + + GlobalVars.UserCustomization.Hat2 + "','" + + GlobalVars.UserCustomization.Hat3 + "'," + + GlobalVars.UserCustomization.HeadColorID + "," + + GlobalVars.UserCustomization.TorsoColorID + "," + + GlobalVars.UserCustomization.LeftArmColorID + "," + + GlobalVars.UserCustomization.RightArmColorID + "," + + GlobalVars.UserCustomization.LeftLegColorID + "," + + GlobalVars.UserCustomization.RightLegColorID + ",'" + + GlobalVars.UserCustomization.TShirt + "','" + + GlobalVars.UserCustomization.Shirt + "','" + + GlobalVars.UserCustomization.Pants + "','" + + GlobalVars.UserCustomization.Face + "','" + + GlobalVars.UserCustomization.Head + "','" + + GlobalVars.UserCustomization.Icon + "','" + + GlobalVars.UserCustomization.Extra + "'"; + + if (localizeOnlineClothing) { - DirectoryInfo localdinfo = new DirectoryInfo(file.DirectoryName); - string directory = localdinfo.Name; - if (!fileListToIgnore.Contains(file.Name, StringComparer.InvariantCultureIgnoreCase) && !fileListToIgnore.Contains(directory, StringComparer.InvariantCultureIgnoreCase)) - { - fileCount++; - } - else - { - continue; - } + GlobalVars.TShirtTextureID = NovetusFuncs.GetItemTextureID(GlobalVars.UserCustomization.TShirt, "TShirt", new AssetCacheDefBasic("ShirtGraphic", new string[] { "Graphic" })); + GlobalVars.ShirtTextureID = NovetusFuncs.GetItemTextureID(GlobalVars.UserCustomization.Shirt, "Shirt", new AssetCacheDefBasic("Shirt", new string[] { "ShirtTemplate" })); + GlobalVars.PantsTextureID = NovetusFuncs.GetItemTextureID(GlobalVars.UserCustomization.Pants, "Pants", new AssetCacheDefBasic("Pants", new string[] { "PantsTemplate" })); + GlobalVars.FaceTextureID = NovetusFuncs.GetItemTextureID(GlobalVars.UserCustomization.Face, "Face", new AssetCacheDefBasic("Decal", new string[] { "Texture" })); + + GlobalVars.TShirtTextureLocal = NovetusFuncs.GetItemTextureLocalPath(GlobalVars.TShirtTextureID, "TShirt"); + GlobalVars.ShirtTextureLocal = NovetusFuncs.GetItemTextureLocalPath(GlobalVars.ShirtTextureID, "Shirt"); + GlobalVars.PantsTextureLocal = NovetusFuncs.GetItemTextureLocalPath(GlobalVars.PantsTextureID, "Pants"); + GlobalVars.FaceTextureLocal = NovetusFuncs.GetItemTextureLocalPath(GlobalVars.FaceTextureID, "Face"); } + } - //MessageBox.Show(lineCount + "\n" + fileCount); - - if (lineCount != fileCount) + public static void CreateAssetCacheDirectories() + { + if (!Directory.Exists(GlobalPaths.AssetCacheDirAssets)) { - Util.ConsolePrint("WARNING - Initial File List is not relevant to file path. Regenerating.", 5); + Directory.CreateDirectory(GlobalPaths.AssetCacheDirAssets); + } + } + + public static void CreateInitialFileListIfNeededMulti() + { + if (GlobalVars.NoFileList) + return; + + string filePath = GlobalPaths.ConfigDir + "\\InitialFileList.txt"; + + if (!File.Exists(filePath)) + { + Util.ConsolePrint("WARNING - No file list detected. Generating Initial File List.", 5); Thread t = new Thread(CreateInitialFileList); t.IsBackground = true; t.Start(); } - } - } - - private static void CreateInitialFileList() - { - string filterPath = GlobalPaths.ConfigDir + @"\\" + GlobalPaths.InitialFileListIgnoreFilterName; - string[] fileListToIgnore = File.ReadAllLines(filterPath); - string FileName = GlobalPaths.ConfigDir + "\\InitialFileList.txt"; - - File.Create(FileName).Close(); - - using (var txt = File.CreateText(FileName)) - { - DirectoryInfo dinfo = new DirectoryInfo(GlobalPaths.RootPath); - FileInfo[] Files = dinfo.GetFiles("*.*", SearchOption.AllDirectories); - foreach (FileInfo file in Files) + else { - DirectoryInfo localdinfo = new DirectoryInfo(file.DirectoryName); - string directory = localdinfo.Name; - if (!fileListToIgnore.Contains(file.Name, StringComparer.InvariantCultureIgnoreCase) && !fileListToIgnore.Contains(directory, StringComparer.InvariantCultureIgnoreCase)) + int lineCount = File.ReadLines(filePath).Count(); + int fileCount = 0; + + string filterPath = GlobalPaths.ConfigDir + @"\\" + GlobalPaths.InitialFileListIgnoreFilterName; + string[] fileListToIgnore = File.ReadAllLines(filterPath); + + DirectoryInfo dinfo = new DirectoryInfo(GlobalPaths.RootPath); + FileInfo[] Files = dinfo.GetFiles("*.*", SearchOption.AllDirectories); + foreach (FileInfo file in Files) { - txt.WriteLine(file.FullName); + DirectoryInfo localdinfo = new DirectoryInfo(file.DirectoryName); + string directory = localdinfo.Name; + if (!fileListToIgnore.Contains(file.Name, StringComparer.InvariantCultureIgnoreCase) && !fileListToIgnore.Contains(directory, StringComparer.InvariantCultureIgnoreCase)) + { + fileCount++; + } + else + { + continue; + } } - else + + //MessageBox.Show(lineCount + "\n" + fileCount); + + if (lineCount != fileCount) { - continue; + Util.ConsolePrint("WARNING - Initial File List is not relevant to file path. Regenerating.", 5); + Thread t = new Thread(CreateInitialFileList); + t.IsBackground = true; + t.Start(); } } } - Util.ConsolePrint("File list generation finished.", 4); + private static void CreateInitialFileList() + { + string filterPath = GlobalPaths.ConfigDir + @"\\" + GlobalPaths.InitialFileListIgnoreFilterName; + string[] fileListToIgnore = File.ReadAllLines(filterPath); + string FileName = GlobalPaths.ConfigDir + "\\InitialFileList.txt"; + + File.Create(FileName).Close(); + + using (var txt = File.CreateText(FileName)) + { + DirectoryInfo dinfo = new DirectoryInfo(GlobalPaths.RootPath); + FileInfo[] Files = dinfo.GetFiles("*.*", SearchOption.AllDirectories); + foreach (FileInfo file in Files) + { + DirectoryInfo localdinfo = new DirectoryInfo(file.DirectoryName); + string directory = localdinfo.Name; + if (!fileListToIgnore.Contains(file.Name, StringComparer.InvariantCultureIgnoreCase) && !fileListToIgnore.Contains(directory, StringComparer.InvariantCultureIgnoreCase)) + { + txt.WriteLine(file.FullName); + } + else + { + continue; + } + } + } + + Util.ConsolePrint("File list generation finished.", 4); + } } -} -#endregion \ No newline at end of file + #endregion +} \ No newline at end of file diff --git a/Novetus/NovetusCore/StorageAndFunctions/GlobalPaths.cs b/Novetus/NovetusCore/StorageAndFunctions/GlobalPaths.cs index bb357f5..6373c1f 100644 --- a/Novetus/NovetusCore/StorageAndFunctions/GlobalPaths.cs +++ b/Novetus/NovetusCore/StorageAndFunctions/GlobalPaths.cs @@ -3,116 +3,121 @@ using System.IO; using System.Reflection; #endregion -#region Global Paths - -public class GlobalPaths +namespace Novetus.Core { - #region Base Game Paths - public static readonly string RootPathLauncher = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); - public static readonly string BasePathLauncher = RootPathLauncher.Replace(@"\", @"\\"); - public static readonly string RootPath = Directory.GetParent(RootPathLauncher).ToString(); - public static readonly string BasePath = RootPath.Replace(@"\", @"\\"); - public static readonly string DataPath = BasePath + @"\\shareddata"; - public static readonly string BinDir = BasePath + @"\\bin"; - public static readonly string ConfigDir = BasePath + @"\\config"; - public static readonly string LogDir = BasePath + @"\\logs"; - public static readonly string ConfigDirClients = ConfigDir + @"\\clients"; - public static readonly string ConfigDirTemplates = ConfigDir + @"\\itemtemplates"; - public static readonly string DataDir = BinDir + @"\\data"; - public static readonly string ClientDir = BasePath + @"\\clients"; - public static readonly string MapsDir = BasePath + @"\\maps"; - public static readonly string AddonDir = BasePath + @"\\addons"; - public static readonly string AddonCoreDir = AddonDir + @"\\core"; - public static readonly string MapsDirCustom = MapsDir + @"\\Custom"; - public static readonly string MapsDirBase = "maps"; - public static readonly string BaseGameDir = "rbxasset://../../../"; - public static readonly string AltBaseGameDir = "rbxasset://"; - public static readonly string SharedDataGameDir = BaseGameDir + "shareddata/"; - #endregion + #region Global Paths - #region Customization Paths - public static readonly string CustomPlayerDir = DataPath + "\\charcustom"; - public static readonly string hatdir = CustomPlayerDir + "\\hats"; - public static readonly string facedir = CustomPlayerDir + "\\faces"; - public static readonly string headdir = CustomPlayerDir + "\\heads"; - public static readonly string tshirtdir = CustomPlayerDir + "\\tshirts"; - public static readonly string shirtdir = CustomPlayerDir + "\\shirts"; - public static readonly string pantsdir = CustomPlayerDir + "\\pants"; - public static readonly string extradir = CustomPlayerDir + "\\custom"; - public static readonly string extradirIcons = extradir + "\\icons"; + public class GlobalPaths + { + #region Base Game Paths + public static readonly string RootPathLauncher = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + public static readonly string BasePathLauncher = RootPathLauncher.Replace(@"\", @"\\"); + public static readonly string RootPath = Directory.GetParent(RootPathLauncher).ToString(); + public static readonly string BasePath = RootPath.Replace(@"\", @"\\"); + public static readonly string DataPath = BasePath + @"\\shareddata"; + public static readonly string BinDir = BasePath + @"\\bin"; + public static readonly string ConfigDir = BasePath + @"\\config"; + public static readonly string LogDir = BasePath + @"\\logs"; + public static readonly string ConfigDirClients = ConfigDir + @"\\clients"; + public static readonly string ConfigDirTemplates = ConfigDir + @"\\itemtemplates"; + public static readonly string DataDir = BinDir + @"\\data"; + public static readonly string ClientDir = BasePath + @"\\clients"; + public static readonly string MapsDir = BasePath + @"\\maps"; + public static readonly string AddonDir = BasePath + @"\\addons"; + public static readonly string AddonCoreDir = AddonDir + @"\\core"; + public static readonly string AddonNovetusExts = AddonDir + @"\\novetusexts"; + public static readonly string NovetusExtsWebProxy = AddonNovetusExts + @"\\webproxy"; + public static readonly string MapsDirCustom = MapsDir + @"\\Custom"; + public static readonly string MapsDirBase = "maps"; + public static readonly string BaseGameDir = "rbxasset://../../../"; + public static readonly string AltBaseGameDir = "rbxasset://"; + public static readonly string SharedDataGameDir = BaseGameDir + "shareddata/"; + #endregion - public static readonly string CharCustomGameDir = SharedDataGameDir + "charcustom/"; - public static readonly string hatGameDir = CharCustomGameDir + "hats/"; - public static readonly string faceGameDir = CharCustomGameDir + "faces/"; - public static readonly string headGameDir = CharCustomGameDir + "heads/"; - public static readonly string tshirtGameDir = CharCustomGameDir + "tshirts/"; - public static readonly string shirtGameDir = CharCustomGameDir + "shirts/"; - public static readonly string pantsGameDir = CharCustomGameDir + "pants/"; - public static readonly string extraGameDir = CharCustomGameDir + "custom/"; - #endregion + #region Customization Paths + public static readonly string CustomPlayerDir = DataPath + "\\charcustom"; + public static readonly string hatdir = CustomPlayerDir + "\\hats"; + public static readonly string facedir = CustomPlayerDir + "\\faces"; + public static readonly string headdir = CustomPlayerDir + "\\heads"; + public static readonly string tshirtdir = CustomPlayerDir + "\\tshirts"; + public static readonly string shirtdir = CustomPlayerDir + "\\shirts"; + public static readonly string pantsdir = CustomPlayerDir + "\\pants"; + public static readonly string extradir = CustomPlayerDir + "\\custom"; + public static readonly string extradirIcons = extradir + "\\icons"; - #region Asset Cache Paths + public static readonly string CharCustomGameDir = SharedDataGameDir + "charcustom/"; + public static readonly string hatGameDir = CharCustomGameDir + "hats/"; + public static readonly string faceGameDir = CharCustomGameDir + "faces/"; + public static readonly string headGameDir = CharCustomGameDir + "heads/"; + public static readonly string tshirtGameDir = CharCustomGameDir + "tshirts/"; + public static readonly string shirtGameDir = CharCustomGameDir + "shirts/"; + public static readonly string pantsGameDir = CharCustomGameDir + "pants/"; + public static readonly string extraGameDir = CharCustomGameDir + "custom/"; + #endregion - #region Base Paths - public static readonly string DirFonts = "\\fonts"; - public static readonly string DirSounds = "\\sounds"; - public static readonly string DirTextures = "\\textures"; - public static readonly string DirScripts = "\\scripts"; - public static readonly string FontsGameDir = "fonts/"; - public static readonly string SoundsGameDir = "sounds/"; - public static readonly string TexturesGameDir = "textures/"; - public static readonly string ScriptsGameDir = "scripts/"; - #endregion + #region Asset Cache Paths - #region Asset Dirs - public static string AssetCacheDir = DataPath + "\\assetcache"; - public static string AssetCacheDirAssets = AssetCacheDir + "\\assets"; + #region Base Paths + public static readonly string DirFonts = "\\fonts"; + public static readonly string DirSounds = "\\sounds"; + public static readonly string DirTextures = "\\textures"; + public static readonly string DirScripts = "\\scripts"; + public static readonly string FontsGameDir = "fonts/"; + public static readonly string SoundsGameDir = "sounds/"; + public static readonly string TexturesGameDir = "textures/"; + public static readonly string ScriptsGameDir = "scripts/"; + #endregion - public static string AssetCacheGameDir = SharedDataGameDir + "assetcache/"; - public static string AssetCacheAssetsGameDir = AssetCacheGameDir + "assets/"; - #endregion + #region Asset Dirs + public static string AssetCacheDir = DataPath + "\\assetcache"; + public static string AssetCacheDirAssets = AssetCacheDir + "\\assets"; - #region Item Dirs - public static readonly string hatdirFonts = hatdir + DirFonts; - public static readonly string hatdirTextures = hatdir + DirTextures; - public static readonly string hatdirSounds = hatdir + DirSounds; - public static readonly string hatdirScripts = hatdir + DirScripts; - public static readonly string facedirTextures = facedir; //+ DirTextures; - public static readonly string headdirFonts = headdir + DirFonts; - public static readonly string headdirTextures = headdir + DirTextures; - public static readonly string tshirtdirTextures = tshirtdir; //+ DirTextures; - public static readonly string shirtdirTextures = shirtdir + DirTextures; - public static readonly string pantsdirTextures = pantsdir + DirTextures; + public static string AssetCacheGameDir = SharedDataGameDir + "assetcache/"; + public static string AssetCacheAssetsGameDir = AssetCacheGameDir + "assets/"; + #endregion - public static readonly string hatGameDirFonts = hatGameDir + FontsGameDir; - public static readonly string hatGameDirTextures = hatGameDir + TexturesGameDir; - public static readonly string hatGameDirSounds = hatGameDir + SoundsGameDir; - public static readonly string hatGameDirScripts = hatGameDir + ScriptsGameDir; - public static readonly string faceGameDirTextures = faceGameDir; //+ TexturesGameDir; - public static readonly string headGameDirFonts = headGameDir + FontsGameDir; - public static readonly string headGameDirTextures = headGameDir + TexturesGameDir; - public static readonly string tshirtGameDirTextures = tshirtGameDir; //+ TexturesGameDir; - public static readonly string shirtGameDirTextures = shirtGameDir + TexturesGameDir; - public static readonly string pantsGameDirTextures = pantsGameDir + TexturesGameDir; - #endregion + #region Item Dirs + public static readonly string hatdirFonts = hatdir + DirFonts; + public static readonly string hatdirTextures = hatdir + DirTextures; + public static readonly string hatdirSounds = hatdir + DirSounds; + public static readonly string hatdirScripts = hatdir + DirScripts; + public static readonly string facedirTextures = facedir; //+ DirTextures; + public static readonly string headdirFonts = headdir + DirFonts; + public static readonly string headdirTextures = headdir + DirTextures; + public static readonly string tshirtdirTextures = tshirtdir; //+ DirTextures; + public static readonly string shirtdirTextures = shirtdir + DirTextures; + public static readonly string pantsdirTextures = pantsdir + DirTextures; - #endregion + public static readonly string hatGameDirFonts = hatGameDir + FontsGameDir; + public static readonly string hatGameDirTextures = hatGameDir + TexturesGameDir; + public static readonly string hatGameDirSounds = hatGameDir + SoundsGameDir; + public static readonly string hatGameDirScripts = hatGameDir + ScriptsGameDir; + public static readonly string faceGameDirTextures = faceGameDir; //+ TexturesGameDir; + public static readonly string headGameDirFonts = headGameDir + FontsGameDir; + public static readonly string headGameDirTextures = headGameDir + TexturesGameDir; + public static readonly string tshirtGameDirTextures = tshirtGameDir; //+ TexturesGameDir; + public static readonly string shirtGameDirTextures = shirtGameDir + TexturesGameDir; + public static readonly string pantsGameDirTextures = pantsGameDir + TexturesGameDir; + #endregion - #region File Names - public static readonly string ConfigName = "config.ini"; - public static string ConfigNameCustomization = "config_customization.ini"; - public static readonly string InfoName = "info.ini"; - public static readonly string ScriptName = "CSMPFunctions"; - public static readonly string ScriptGenName = "CSMPBoot"; - public static readonly string ContentProviderXMLName = "ContentProviders.xml"; - public static readonly string PartColorXMLName = "PartColors.xml"; - public static readonly string FileDeleteFilterName = "FileDeleteFilter.txt"; - public static readonly string InitialFileListIgnoreFilterName = "InitialFileListIgnoreFilter.txt"; - public static readonly string ServerInfoFileName = "serverinfo.txt"; - public static readonly string ConsoleHelpFileName = "consolehelp.txt"; - public static readonly string ClientScriptDocumentationFileName = "documentation.txt"; - public static readonly string AddonLoaderFileName = "AddonLoader.lua"; - public static readonly string AssetFixerPatternFileName = "assetfixer_pattern.txt"; + #endregion + + #region File Names + public static readonly string ConfigName = "config.ini"; + public static string ConfigNameCustomization = "config_customization.ini"; + public static readonly string InfoName = "info.ini"; + public static readonly string ScriptName = "CSMPFunctions"; + public static readonly string ScriptGenName = "CSMPBoot"; + public static readonly string ContentProviderXMLName = "ContentProviders.xml"; + public static readonly string PartColorXMLName = "PartColors.xml"; + public static readonly string FileDeleteFilterName = "FileDeleteFilter.txt"; + public static readonly string InitialFileListIgnoreFilterName = "InitialFileListIgnoreFilter.txt"; + public static readonly string ServerInfoFileName = "serverinfo.txt"; + public static readonly string ConsoleHelpFileName = "consolehelp.txt"; + public static readonly string ClientScriptDocumentationFileName = "documentation.txt"; + public static readonly string AddonLoaderFileName = "AddonLoader.lua"; + public static readonly string AssetFixerPatternFileName = "assetfixer_pattern.txt"; + #endregion + } #endregion } -#endregion diff --git a/Novetus/NovetusCore/StorageAndFunctions/GlobalVars.cs b/Novetus/NovetusCore/StorageAndFunctions/GlobalVars.cs index bf0ea19..1f7d1dd 100644 --- a/Novetus/NovetusCore/StorageAndFunctions/GlobalVars.cs +++ b/Novetus/NovetusCore/StorageAndFunctions/GlobalVars.cs @@ -14,140 +14,143 @@ using System.Diagnostics; using System.Windows.Forms; #endregion -#region Script Type -public enum ScriptType +namespace Novetus.Core { - Client = 0, - Server = 1, - Solo = 2, - Studio = 3, - EasterEgg = 4, - None = 5 -} -#endregion - -#region Game Server Definition -public class GameServer -{ - public GameServer(string ip, int port) + #region Script Type + public enum ScriptType { - ServerIP = ip; - ServerPort = port; + Client = 0, + Server = 1, + Solo = 2, + Studio = 3, + EasterEgg = 4, + None = 5 } + #endregion - public override string ToString() - { - return ServerIP + ":" + ServerPort.ToString(); - } - - public void SetValues(string input) + #region Game Server Definition + public class GameServer { - try + public GameServer(string ip, int port) { - string[] vals = input.Split(':'); - string ip = vals[0]; - int port = Convert.ToInt32(vals[1]); - ServerIP = ip; ServerPort = port; } - catch (Exception) + + public override string ToString() { - ServerIP = input; - ServerPort = GlobalVars.DefaultRobloxPort; + return ServerIP + ":" + ServerPort.ToString(); } + + public void SetValues(string input) + { + try + { + string[] vals = input.Split(':'); + string ip = vals[0]; + int port = Convert.ToInt32(vals[1]); + + ServerIP = ip; + ServerPort = port; + } + catch (Exception) + { + ServerIP = input; + ServerPort = GlobalVars.DefaultRobloxPort; + } + } + + public string ServerIP { get; set; } + public int ServerPort { get; set; } } + #endregion - public string ServerIP { get; set; } - public int ServerPort { get; set; } -} -#endregion - -#region Global Variables -public static class GlobalVars -{ - #region Discord - public enum LauncherState + #region Global Variables + public static class GlobalVars { - InLauncher = 0, - InMPGame = 1, - InSoloGame = 2, - InStudio = 3, - InCustomization = 4, - InEasterEggGame = 5, - LoadingURI = 6 - } + #region Discord + public enum LauncherState + { + InLauncher = 0, + InMPGame = 1, + InSoloGame = 2, + InStudio = 3, + InCustomization = 4, + InEasterEggGame = 5, + LoadingURI = 6 + } - public static DiscordRPC.EventHandlers handlers; - #endregion + public static DiscordRPC.EventHandlers handlers; + #endregion - #region Class definitions - public static FileFormat.ProgramInfo ProgramInformation = new FileFormat.ProgramInfo(); - public static FileFormat.Config UserConfiguration = new FileFormat.Config(); - public static FileFormat.ClientInfo SelectedClientInfo = new FileFormat.ClientInfo(); - public static FileFormat.CustomizationConfig UserCustomization = new FileFormat.CustomizationConfig(); - public static PartColor[] PartColorList; - public static List PartColorListConv; - #endregion + #region Class definitions + public static FileFormat.ProgramInfo ProgramInformation = new FileFormat.ProgramInfo(); + public static FileFormat.Config UserConfiguration = new FileFormat.Config(); + public static FileFormat.ClientInfo SelectedClientInfo = new FileFormat.ClientInfo(); + public static FileFormat.CustomizationConfig UserCustomization = new FileFormat.CustomizationConfig(); + public static PartColor[] PartColorList; + public static List PartColorListConv; + #endregion - #region Joining/Hosting - public static string DefaultIP = "localhost"; - public static int DefaultRobloxPort = 53640; - public static GameServer CurrentServer = new GameServer(DefaultIP, DefaultRobloxPort); - public static string ExternalIP = SecurityFuncs.GetExternalIPAddress(); - public static ScriptType GameOpened = ScriptType.None; - public static string PlayerTripcode = ""; + #region Joining/Hosting + public static string DefaultIP = "localhost"; + public static int DefaultRobloxPort = 53640; + public static GameServer CurrentServer = new GameServer(DefaultIP, DefaultRobloxPort); + public static string ExternalIP = SecurityFuncs.GetExternalIPAddress(); + public static ScriptType GameOpened = ScriptType.None; + public static string PlayerTripcode = ""; #if LAUNCHER || URI - public static int WebProxyPort = 0; - public static WebProxy Proxy = new WebProxy(); + public static int WebProxyPort = 0; + public static WebProxy Proxy = new WebProxy(); #endif -#endregion + #endregion #if LAUNCHER - #region Novetus Launcher + #region Novetus Launcher public static NovetusLauncher.NovetusConsole consoleForm = null; - #endregion + #endregion #endif - #region Customization - public static string Loadout = ""; - public static string soloLoadout = ""; - public static string TShirtTextureID = ""; - public static string ShirtTextureID = ""; - public static string PantsTextureID = ""; - public static string FaceTextureID = ""; - public static string TShirtTextureLocal = ""; - public static string ShirtTextureLocal = ""; - public static string PantsTextureLocal = ""; - public static string FaceTextureLocal = ""; - #endregion + #region Customization + public static string Loadout = ""; + public static string soloLoadout = ""; + public static string TShirtTextureID = ""; + public static string ShirtTextureID = ""; + public static string PantsTextureID = ""; + public static string FaceTextureID = ""; + public static string TShirtTextureLocal = ""; + public static string ShirtTextureLocal = ""; + public static string PantsTextureLocal = ""; + public static string FaceTextureLocal = ""; + #endregion - #region Discord Variables - //discord - public static DiscordRPC.RichPresence presence; - public static string appid = "505955125727330324"; - public static string imagekey_large = "novetus_large"; - public static string image_ingame = "ingame_small"; - public static string image_inlauncher = "inlauncher_small"; - public static string image_instudio = "instudio_small"; - public static string image_incustomization = "incustomization_small"; - #endregion + #region Discord Variables + //discord + public static DiscordRPC.RichPresence presence; + public static string appid = "505955125727330324"; + public static string imagekey_large = "novetus_large"; + public static string image_ingame = "ingame_small"; + public static string image_inlauncher = "inlauncher_small"; + public static string image_instudio = "instudio_small"; + public static string image_incustomization = "incustomization_small"; + #endregion - #region Other - public static bool ExtendedVersionNumber = false; - public static bool LocalPlayMode = false; - public static bool AdminMode = false; - public static bool ColorsLoaded = false; - public static int ValidatedExtraFiles = 0; - public static bool NoFileList = false; - public static string ServerID = "N/A"; - public static string PingURL = ""; - public static string Important = ""; - public static string Important2 = ""; - public static string NextCommand = ""; - public static bool AppClosed = false; - public static bool isConsoleOnly = false; - public static bool isMapCompressed = false; + #region Other + public static bool ExtendedVersionNumber = false; + public static bool LocalPlayMode = false; + public static bool AdminMode = false; + public static bool ColorsLoaded = false; + public static int ValidatedExtraFiles = 0; + public static bool NoFileList = false; + public static string ServerID = "N/A"; + public static string PingURL = ""; + public static string Important = ""; + public static string Important2 = ""; + public static string NextCommand = ""; + public static bool AppClosed = false; + public static bool isConsoleOnly = false; + public static bool isMapCompressed = false; + #endregion + } #endregion } -#endregion diff --git a/Novetus/NovetusCore/StorageAndFunctions/NetFuncs.cs b/Novetus/NovetusCore/StorageAndFunctions/NetFuncs.cs index dfd2057..7695849 100644 --- a/Novetus/NovetusCore/StorageAndFunctions/NetFuncs.cs +++ b/Novetus/NovetusCore/StorageAndFunctions/NetFuncs.cs @@ -4,50 +4,53 @@ using Mono.Nat; using System; #endregion -#region NetFuncs - -public static class NetFuncs +namespace Novetus.Core { - public static void InitUPnP(EventHandler DeviceFound, EventHandler DeviceLost) - { - if (GlobalVars.UserConfiguration.UPnP) - { - NatUtility.DeviceFound += DeviceFound; - NatUtility.StartDiscovery(); - } - } + #region NetFuncs - public static void StartUPnP(INatDevice device, Protocol protocol, int port) + public static class NetFuncs { - if (GlobalVars.UserConfiguration.UPnP) + public static void InitUPnP(EventHandler DeviceFound, EventHandler DeviceLost) { - Mapping checker = device.GetSpecificMapping(protocol, port); - int mapPublic = checker.PublicPort; - int mapPrivate = checker.PrivatePort; - - if (mapPublic == -1 && mapPrivate == -1) + if (GlobalVars.UserConfiguration.UPnP) { - Mapping portmap = new Mapping(protocol, port, port); - device.CreatePortMap(portmap); - } - } - } - - public static void StopUPnP(INatDevice device, Protocol protocol, int port) - { - if (GlobalVars.UserConfiguration.UPnP) - { - Mapping checker = device.GetSpecificMapping(protocol, port); - int mapPublic = checker.PublicPort; - int mapPrivate = checker.PrivatePort; - - if (mapPublic != -1 && mapPrivate != -1) - { - Mapping portmap = new Mapping(protocol, port, port); - device.DeletePortMap(portmap); + NatUtility.DeviceFound += DeviceFound; + NatUtility.StartDiscovery(); + } + } + + public static void StartUPnP(INatDevice device, Protocol protocol, int port) + { + if (GlobalVars.UserConfiguration.UPnP) + { + Mapping checker = device.GetSpecificMapping(protocol, port); + int mapPublic = checker.PublicPort; + int mapPrivate = checker.PrivatePort; + + if (mapPublic == -1 && mapPrivate == -1) + { + Mapping portmap = new Mapping(protocol, port, port); + device.CreatePortMap(portmap); + } + } + } + + public static void StopUPnP(INatDevice device, Protocol protocol, int port) + { + if (GlobalVars.UserConfiguration.UPnP) + { + Mapping checker = device.GetSpecificMapping(protocol, port); + int mapPublic = checker.PublicPort; + int mapPrivate = checker.PrivatePort; + + if (mapPublic != -1 && mapPrivate != -1) + { + Mapping portmap = new Mapping(protocol, port, port); + device.DeletePortMap(portmap); + } } } } + #endregion } -#endregion #endif diff --git a/Novetus/NovetusCore/StorageAndFunctions/NovetusFuncs.cs b/Novetus/NovetusCore/StorageAndFunctions/NovetusFuncs.cs index 0a5840e..dd5bb2e 100644 --- a/Novetus/NovetusCore/StorageAndFunctions/NovetusFuncs.cs +++ b/Novetus/NovetusCore/StorageAndFunctions/NovetusFuncs.cs @@ -10,188 +10,190 @@ using System.Windows.Forms; using System.Collections.Generic; #endregion -#region Novetus Functions -public class NovetusFuncs +namespace Novetus.Core { - public static string CopyMapToRBXAsset() + #region Novetus Functions + public class NovetusFuncs { - string clientcontentpath = GlobalPaths.ClientDir + @"\\" + GlobalVars.UserConfiguration.SelectedClient + @"\\content\\temp.rbxl"; - Util.FixedFileCopy(GlobalVars.UserConfiguration.MapPath, clientcontentpath, true); - return GlobalPaths.AltBaseGameDir + "temp.rbxl"; - } - - public static string GetItemTextureLocalPath(string item, string nameprefix) - { - //don't bother, we're offline. - if (GlobalVars.ExternalIP.Equals("localhost")) - return ""; - - if (!GlobalVars.SelectedClientInfo.CommandLineArgs.Contains("%localizeonlineclothing%")) - return ""; - - if (item.Contains("http://") || item.Contains("https://")) + public static string CopyMapToRBXAsset() { - string peram = "id="; - string fullname = nameprefix + "Temp.png"; + string clientcontentpath = GlobalPaths.ClientDir + @"\\" + GlobalVars.UserConfiguration.SelectedClient + @"\\content\\temp.rbxl"; + Util.FixedFileCopy(GlobalVars.UserConfiguration.MapPath, clientcontentpath, true); + return GlobalPaths.AltBaseGameDir + "temp.rbxl"; + } - if (item.Contains(peram)) + public static string GetItemTextureLocalPath(string item, string nameprefix) + { + //don't bother, we're offline. + if (GlobalVars.ExternalIP.Equals("localhost")) + return ""; + + if (!GlobalVars.SelectedClientInfo.CommandLineArgs.Contains("%localizeonlineclothing%")) + return ""; + + if (item.Contains("http://") || item.Contains("https://")) { - string id = item.After(peram); - fullname = id + ".png"; + string peram = "id="; + string fullname = nameprefix + "Temp.png"; + + if (item.Contains(peram)) + { + string id = item.After(peram); + fullname = id + ".png"; + } + else + { + return item; + } + + Downloader download = new Downloader(item, fullname, "", GlobalPaths.AssetCacheDirAssets); + + try + { + string path = download.GetFullDLPath(); + download.InitDownloadNoDialog(path); + return GlobalPaths.AssetCacheAssetsGameDir + download.fileName; + } +#if URI || LAUNCHER || BASICLAUNCHER + catch (Exception ex) + { + Util.LogExceptions(ex); +#else + catch (Exception) + { +#endif + } + } + + return ""; + } + + public static string GetItemTextureID(string item, string name, AssetCacheDefBasic assetCacheDef) + { + //don't bother, we're offline. + if (GlobalVars.ExternalIP.Equals("localhost")) + return ""; + + if (!GlobalVars.SelectedClientInfo.CommandLineArgs.Contains("%localizeonlineclothing%")) + return ""; + + if (item.Contains("http://") || item.Contains("https://")) + { + string peram = "id="; + if (!item.Contains(peram)) + { + return item; + } + + Downloader download = new Downloader(item, name + "Temp.rbxm", "", GlobalPaths.AssetCacheDirAssets); + + try + { + string path = download.GetFullDLPath(); + download.InitDownloadNoDialog(path); + string oldfile = File.ReadAllText(path); + string fixedfile = RobloxXML.RemoveInvalidXmlChars(RobloxXML.ReplaceHexadecimalSymbols(oldfile)).Replace(" ", "\t").Replace("#9;", "\t"); + XDocument doc = null; + XmlReaderSettings xmlReaderSettings = new XmlReaderSettings { CheckCharacters = false }; + Stream filestream = Util.GenerateStreamFromString(fixedfile); + using (XmlReader xmlReader = XmlReader.Create(filestream, xmlReaderSettings)) + { + xmlReader.MoveToContent(); + doc = XDocument.Load(xmlReader); + } + + return RobloxXML.GetURLInNodes(doc, assetCacheDef.Class, assetCacheDef.Id[0], item); + } +#if URI || LAUNCHER || BASICLAUNCHER + catch (Exception ex) + { + Util.LogExceptions(ex); +#else + catch (Exception) + { +#endif + } + } + + return ""; + } + + public static void GeneratePlayerID() + { + int randomID = SecurityFuncs.GenerateRandomNumber(); + //2147483647 is max id. + GlobalVars.UserConfiguration.UserID = randomID; + } + + public static string GenerateAndReturnTripcode() + { + //Powered by https://github.com/davcs86/csharp-uhwid + return UHWIDEngine.AdvancedUid; + } + + public static void PingMasterServer(bool online, string reason) + { + if (online) + { + GlobalVars.ServerID = SecurityFuncs.RandomString(30) + SecurityFuncs.GenerateRandomNumber(); + GlobalVars.PingURL = "http://" + GlobalVars.UserConfiguration.ServerBrowserServerAddress + + "/list.php?name=" + GlobalVars.UserConfiguration.ServerBrowserServerName + + "&ip=" + (!string.IsNullOrWhiteSpace(GlobalVars.UserConfiguration.AlternateServerIP) ? GlobalVars.UserConfiguration.AlternateServerIP : GlobalVars.ExternalIP) + + "&port=" + GlobalVars.UserConfiguration.RobloxPort + + "&client=" + GlobalVars.UserConfiguration.SelectedClient + + "&version=" + GlobalVars.ProgramInformation.Version + + "&id=" + GlobalVars.ServerID; } else { - return item; - } - - Downloader download = new Downloader(item, fullname, "", GlobalPaths.AssetCacheDirAssets); - - try - { - string path = download.GetFullDLPath(); - download.InitDownloadNoDialog(path); - return GlobalPaths.AssetCacheAssetsGameDir + download.fileName; - } -#if URI || LAUNCHER || BASICLAUNCHER - catch (Exception ex) - { - Util.LogExceptions(ex); -#else - catch (Exception) - { -#endif - } - } - - return ""; - } - - public static string GetItemTextureID(string item, string name, AssetCacheDefBasic assetCacheDef) - { - //don't bother, we're offline. - if (GlobalVars.ExternalIP.Equals("localhost")) - return ""; - - if (!GlobalVars.SelectedClientInfo.CommandLineArgs.Contains("%localizeonlineclothing%")) - return ""; - - if (item.Contains("http://") || item.Contains("https://")) - { - string peram = "id="; - if (!item.Contains(peram)) - { - return item; - } - - Downloader download = new Downloader(item, name + "Temp.rbxm", "", GlobalPaths.AssetCacheDirAssets); - - try - { - string path = download.GetFullDLPath(); - download.InitDownloadNoDialog(path); - string oldfile = File.ReadAllText(path); - string fixedfile = RobloxXML.RemoveInvalidXmlChars(RobloxXML.ReplaceHexadecimalSymbols(oldfile)).Replace(" ", "\t").Replace("#9;", "\t"); - XDocument doc = null; - XmlReaderSettings xmlReaderSettings = new XmlReaderSettings { CheckCharacters = false }; - Stream filestream = Util.GenerateStreamFromString(fixedfile); - using (XmlReader xmlReader = XmlReader.Create(filestream, xmlReaderSettings)) - { - xmlReader.MoveToContent(); - doc = XDocument.Load(xmlReader); - } - - return RobloxXML.GetURLInNodes(doc, assetCacheDef.Class, assetCacheDef.Id[0], item); - } -#if URI || LAUNCHER || BASICLAUNCHER - catch (Exception ex) - { - Util.LogExceptions(ex); -#else - catch (Exception) - { -#endif - } - } - - return ""; - } - - public static void GeneratePlayerID() - { - int randomID = SecurityFuncs.GenerateRandomNumber(); - //2147483647 is max id. - GlobalVars.UserConfiguration.UserID = randomID; - } - - public static string GenerateAndReturnTripcode() - { - //Powered by https://github.com/davcs86/csharp-uhwid - return UHWID.UHWIDEngine.AdvancedUid; - } - - public static void PingMasterServer(bool online, string reason) - { - if (online) - { - GlobalVars.ServerID = SecurityFuncs.RandomString(30) + SecurityFuncs.GenerateRandomNumber(); - GlobalVars.PingURL = "http://" + GlobalVars.UserConfiguration.ServerBrowserServerAddress + - "/list.php?name=" + GlobalVars.UserConfiguration.ServerBrowserServerName + - "&ip=" + (!string.IsNullOrWhiteSpace(GlobalVars.UserConfiguration.AlternateServerIP) ? GlobalVars.UserConfiguration.AlternateServerIP : GlobalVars.ExternalIP) + - "&port=" + GlobalVars.UserConfiguration.RobloxPort + - "&client=" + GlobalVars.UserConfiguration.SelectedClient + - "&version=" + GlobalVars.ProgramInformation.Version + - "&id=" + GlobalVars.ServerID; - } - else - { - GlobalVars.PingURL = "http://" + GlobalVars.UserConfiguration.ServerBrowserServerAddress + - "/delist.php?id=" + GlobalVars.ServerID; - GlobalVars.ServerID = "N/A"; - } - - Util.ConsolePrint("Pinging master server. " + reason, 4); - Task.Factory.StartNew(() => TryPing()); - } - - private static void TryPing() - { - string response = Util.HttpGet(GlobalVars.PingURL); - - if (!string.IsNullOrWhiteSpace(response)) - { - Util.ConsolePrint(response, response.Contains("ERROR:") ? 2 : 4); - - if (response.Contains("ERROR:")) - { + GlobalVars.PingURL = "http://" + GlobalVars.UserConfiguration.ServerBrowserServerAddress + + "/delist.php?id=" + GlobalVars.ServerID; GlobalVars.ServerID = "N/A"; } + + Util.ConsolePrint("Pinging master server. " + reason, 4); + Task.Factory.StartNew(() => TryPing()); } - if (!GlobalVars.ServerID.Equals("N/A")) + private static void TryPing() { - Util.ConsolePrint("Master server ping successful. Your server's ID is " + GlobalVars.ServerID, 4); + string response = Util.HttpGet(GlobalVars.PingURL); + + if (!string.IsNullOrWhiteSpace(response)) + { + Util.ConsolePrint(response, response.Contains("ERROR:") ? 2 : 4); + + if (response.Contains("ERROR:")) + { + GlobalVars.ServerID = "N/A"; + } + } + + if (!GlobalVars.ServerID.Equals("N/A")) + { + Util.ConsolePrint("Master server ping successful. Your server's ID is " + GlobalVars.ServerID, 4); + } + + GlobalVars.PingURL = ""; } - GlobalVars.PingURL = ""; - } - - public static string[] LoadServerInformation() - { - string[] lines1 = { + public static string[] LoadServerInformation() + { + string[] lines1 = { SecurityFuncs.Base64Encode(!string.IsNullOrWhiteSpace(GlobalVars.UserConfiguration.AlternateServerIP) ? GlobalVars.UserConfiguration.AlternateServerIP : GlobalVars.ExternalIP), SecurityFuncs.Base64Encode(GlobalVars.UserConfiguration.RobloxPort.ToString()), SecurityFuncs.Base64Encode(GlobalVars.UserConfiguration.SelectedClient) }; - string URI = "novetus://" + SecurityFuncs.Base64Encode(string.Join("|", lines1), true); - string[] lines2 = { + string URI = "novetus://" + SecurityFuncs.Base64Encode(string.Join("|", lines1), true); + string[] lines2 = { SecurityFuncs.Base64Encode("localhost"), SecurityFuncs.Base64Encode(GlobalVars.UserConfiguration.RobloxPort.ToString()), SecurityFuncs.Base64Encode(GlobalVars.UserConfiguration.SelectedClient) }; - string URI2 = "novetus://" + SecurityFuncs.Base64Encode(string.Join("|", lines2), true); - GameServer server = new GameServer((!string.IsNullOrWhiteSpace(GlobalVars.UserConfiguration.AlternateServerIP) ? GlobalVars.UserConfiguration.AlternateServerIP : GlobalVars.ExternalIP), - GlobalVars.UserConfiguration.RobloxPort); - string[] text = { + string URI2 = "novetus://" + SecurityFuncs.Base64Encode(string.Join("|", lines2), true); + GameServer server = new GameServer((!string.IsNullOrWhiteSpace(GlobalVars.UserConfiguration.AlternateServerIP) ? GlobalVars.UserConfiguration.AlternateServerIP : GlobalVars.ExternalIP), + GlobalVars.UserConfiguration.RobloxPort); + string[] text = { "Server IP Address: " + server.ToString(), "Client: " + GlobalVars.UserConfiguration.SelectedClient, "Map: " + GlobalVars.UserConfiguration.Map, @@ -203,436 +205,449 @@ public class NovetusFuncs URI2 }; - return text; - } + return text; + } - public static void CreateTXT() - { - List text = new List(); - text.AddRange(LoadServerInformation()); + public static void CreateTXT() + { + List text = new List(); + text.AddRange(LoadServerInformation()); - string txt = GlobalPaths.BasePath + "\\" + GlobalPaths.ServerInfoFileName; - File.WriteAllLines(txt, text); - Util.ConsolePrint("Server Information sent to file " + txt, 4); - } + string txt = GlobalPaths.BasePath + "\\" + GlobalPaths.ServerInfoFileName; + File.WriteAllLines(txt, text); + Util.ConsolePrint("Server Information sent to file " + txt, 4); + } #if LAUNCHER || URI - public static void LaunchCharacterCustomization() - { - //https://stackoverflow.com/questions/9029351/close-all-open-forms-except-the-main-menu-in-c-sharp - FormCollection fc = Application.OpenForms; - - foreach (Form frm in fc) + public static void LaunchCharacterCustomization() { - //iterate through - if (frm.Name == "CharacterCustomizationExtended" || - frm.Name == "CharacterCustomizationCompact") + //https://stackoverflow.com/questions/9029351/close-all-open-forms-except-the-main-menu-in-c-sharp + FormCollection fc = Application.OpenForms; + + foreach (Form frm in fc) { - frm.Close(); - break; + //iterate through + if (frm.Name == "CharacterCustomizationExtended" || + frm.Name == "CharacterCustomizationCompact") + { + frm.Close(); + break; + } + } + + switch (GlobalVars.UserConfiguration.LauncherStyle) + { + case Settings.Style.Extended: + CharacterCustomizationExtended ccustom = new CharacterCustomizationExtended(); + ccustom.Show(); + break; + case Settings.Style.Compact: + CharacterCustomizationCompact ccustom2 = new CharacterCustomizationCompact(); + ccustom2.Show(); + break; + case Settings.Style.Stylish: + default: + CharacterCustomizationExtended ccustom3 = new CharacterCustomizationExtended(); + ccustom3.Show(); + break; } } - - switch (GlobalVars.UserConfiguration.LauncherStyle) - { - case Settings.Style.Extended: - CharacterCustomizationExtended ccustom = new CharacterCustomizationExtended(); - ccustom.Show(); - break; - case Settings.Style.Compact: - CharacterCustomizationCompact ccustom2 = new CharacterCustomizationCompact(); - ccustom2.Show(); - break; - case Settings.Style.Stylish: - default: - CharacterCustomizationExtended ccustom3 = new CharacterCustomizationExtended(); - ccustom3.Show(); - break; - } - } #endif - public static string FixURLString(string str, string str2) - { - string fixedStr = str.ToLower().Replace("?version=1&id=", "?id=") - .Replace("?version=1&id=", "?id=") - .Replace("&", "&") - .Replace("amp;", "&"); - - string baseurl = fixedStr.Before("/asset/?id="); - - if (baseurl == "") + public static string FixURLString(string str, string str2) { - baseurl = fixedStr.Before("/asset?id="); + string fixedStr = str.ToLower().Replace("?version=1&id=", "?id=") + .Replace("?version=1&id=", "?id=") + .Replace("&", "&") + .Replace("amp;", "&"); + + string baseurl = fixedStr.Before("/asset/?id="); + if (baseurl == "") { - baseurl = fixedStr.Before("/item.aspx?id="); + baseurl = fixedStr.Before("/asset?id="); + if (baseurl == "") + { + baseurl = fixedStr.Before("/item.aspx?id="); + } + } + + string fixedUrl = fixedStr.Replace(baseurl + "/asset/?id=", str2) + .Replace(baseurl + "/asset?id=", str2) + .Replace(baseurl + "/item.aspx?id=", str2); + + //...because scripts mess it up. + + string id = fixedUrl.After("id="); + if (id.Contains("&version=")) + { + string ver = id.After("&version="); + id = id.Replace("&version=" + ver, ""); + } + + string fixedID = Regex.Replace(id, "[^0-9]", ""); + + //really fucking hacky. + string finalUrl = fixedUrl.Before("id=") + "id=" + fixedID; + + return finalUrl; + } + + public static void SetupAdminPassword() + { + CryptoRandom random = new CryptoRandom(); + string Name1 = SecurityFuncs.GenerateName(random.Next(4, 12)); + string Name2 = SecurityFuncs.GenerateName(random.Next(4, 12)); + GlobalVars.Important = Name1 + Name2; + GlobalVars.Important2 = SecurityFuncs.Encipher(GlobalVars.Important, random.Next(2, 13)); + } + } + #endregion + + #region Roblox Helpers + #region Vector3 + public class Vector3 + { + public double X; + public double Y; + public double Z; + + public Vector3(double aX, double aY, double aZ) + { + X = aX; + Y = aY; + Z = aZ; + } + } + #endregion + + #region Roblox File Types + public enum RobloxFileType + { + //RBXL and RBXM + RBXL, + RBXM, + //Items + Hat, + Head, + Face, + TShirt, + Shirt, + Pants, + Script, + HeadNoCustomMesh + } + #endregion + + #region Asset Cache Definition + public class AssetCacheDefBasic + { + public AssetCacheDefBasic(string clas, string[] id) + { + Class = clas; + Id = id; + } + + public string Class { get; set; } + public string[] Id { get; set; } + } + + public class AssetCacheDef : AssetCacheDefBasic + { + public AssetCacheDef(string clas, string[] id, string[] ext, + string[] dir, string[] gamedir) : base(clas, id) + { + Ext = ext; + Dir = dir; + GameDir = gamedir; + } + + public string[] Ext { get; set; } + public string[] Dir { get; set; } + public string[] GameDir { get; set; } + } + #endregion + + #region Roblox Type Definitions + public struct RobloxDefs + { + //item defs below + public static AssetCacheDef ItemHatFonts + { + get + { + return new AssetCacheDef("SpecialMesh", + new string[] { "MeshId", "TextureId" }, + new string[] { ".mesh", ".png" }, + new string[] { GlobalPaths.hatdirFonts, GlobalPaths.hatdirTextures }, + new string[] { GlobalPaths.hatGameDirFonts, GlobalPaths.hatGameDirTextures }); } } - string fixedUrl = fixedStr.Replace(baseurl + "/asset/?id=", str2) - .Replace(baseurl + "/asset?id=", str2) - .Replace(baseurl + "/item.aspx?id=", str2); - - //...because scripts mess it up. - - string id = fixedUrl.After("id="); - if (id.Contains("&version=")) + public static AssetCacheDef ItemHatSound { - string ver = id.After("&version="); - id = id.Replace("&version=" + ver, ""); - } - - string fixedID = Regex.Replace(id, "[^0-9]", ""); - - //really fucking hacky. - string finalUrl = fixedUrl.Before("id=") + "id=" + fixedID; - - return finalUrl; - } - - public static void SetupAdminPassword() - { - CryptoRandom random = new CryptoRandom(); - string Name1 = SecurityFuncs.GenerateName(random.Next(4, 12)); - string Name2 = SecurityFuncs.GenerateName(random.Next(4, 12)); - GlobalVars.Important = Name1 + Name2; - GlobalVars.Important2 = SecurityFuncs.Encipher(GlobalVars.Important, random.Next(2, 13)); - } -} -#endregion - -#region Roblox Helpers -#region Vector3 -public class Vector3 -{ - public double X; - public double Y; - public double Z; - - public Vector3(double aX, double aY, double aZ) - { - X = aX; - Y = aY; - Z = aZ; - } -} -#endregion - -#region Roblox File Types -public enum RobloxFileType -{ - //RBXL and RBXM - RBXL, - RBXM, - //Items - Hat, - Head, - Face, - TShirt, - Shirt, - Pants, - Script, - HeadNoCustomMesh -} -#endregion - -#region Asset Cache Definition -public class AssetCacheDefBasic -{ - public AssetCacheDefBasic(string clas, string[] id) - { - Class = clas; - Id = id; - } - - public string Class { get; set; } - public string[] Id { get; set; } -} - -public class AssetCacheDef : AssetCacheDefBasic -{ - public AssetCacheDef(string clas, string[] id, string[] ext, - string[] dir, string[] gamedir) : base(clas, id) - { - Ext = ext; - Dir = dir; - GameDir = gamedir; - } - - public string[] Ext { get; set; } - public string[] Dir { get; set; } - public string[] GameDir { get; set; } -} -#endregion - -#region Roblox Type Definitions -public struct RobloxDefs -{ - //item defs below - public static AssetCacheDef ItemHatFonts - { - get - { - return new AssetCacheDef("SpecialMesh", - new string[] { "MeshId", "TextureId" }, - new string[] { ".mesh", ".png" }, - new string[] { GlobalPaths.hatdirFonts, GlobalPaths.hatdirTextures }, - new string[] { GlobalPaths.hatGameDirFonts, GlobalPaths.hatGameDirTextures }); - } - } - - public static AssetCacheDef ItemHatSound - { - get - { - return new AssetCacheDef("Sound", - new string[] { "SoundId" }, - new string[] { ".wav" }, - new string[] { GlobalPaths.hatdirSounds }, - new string[] { GlobalPaths.hatGameDirSounds }); - } - } - - public static AssetCacheDef ItemHatScript - { - get - { - return new AssetCacheDef("Script", - new string[] { "LinkedSource" }, - new string[] { ".lua" }, - new string[] { GlobalPaths.hatdirScripts }, - new string[] { GlobalPaths.hatGameDirScripts }); - } - } - - public static AssetCacheDef ItemHatLocalScript - { - get - { - return new AssetCacheDef("LocalScript", - new string[] { "LinkedSource" }, - new string[] { ".lua" }, - new string[] { GlobalPaths.hatdirScripts }, - new string[] { GlobalPaths.hatGameDirScripts }); - } - } - - public static AssetCacheDef ItemHeadFonts - { - get - { - return new AssetCacheDef("SpecialMesh", - new string[] { "MeshId", "TextureId" }, - new string[] { ".mesh", ".png" }, - new string[] { GlobalPaths.headdirFonts, GlobalPaths.headdirTextures }, - new string[] { GlobalPaths.headGameDirFonts, GlobalPaths.headGameDirTextures }); - } - } - - public static AssetCacheDef ItemFaceTexture - { - get - { - return new AssetCacheDef("Decal", - new string[] { "Texture" }, - new string[] { ".png" }, - new string[] { GlobalPaths.facedirTextures }, - new string[] { GlobalPaths.faceGameDirTextures }); - } - } - - public static AssetCacheDef ItemShirtTexture - { - get - { - return new AssetCacheDef("Shirt", - new string[] { "ShirtTemplate" }, - new string[] { ".png" }, - new string[] { GlobalPaths.shirtdirTextures }, - new string[] { GlobalPaths.shirtGameDirTextures }); - } - } - - public static AssetCacheDef ItemTShirtTexture - { - get - { - return new AssetCacheDef("ShirtGraphic", - new string[] { "Graphic" }, - new string[] { ".png" }, - new string[] { GlobalPaths.tshirtdirTextures }, - new string[] { GlobalPaths.tshirtGameDirTextures }); - } - } - - public static AssetCacheDef ItemPantsTexture - { - get - { - return new AssetCacheDef("Pants", - new string[] { "PantsTemplate" }, - new string[] { ".png" }, - new string[] { GlobalPaths.pantsdirTextures }, - new string[] { GlobalPaths.pantsGameDirTextures }); - } - } -} -#endregion - -#region XML Types -public enum XMLTypes -{ - Token, - Bool, - Float, - String, - Vector2Int16, - Int -} -#endregion - -#region Roblox XML Parser -public static class RobloxXML -{ - public static void EditRenderSettings(XDocument doc, string setting, string value, XMLTypes type) - { - var v = from nodes in doc.Descendants("Item") - where nodes.Attribute("class").Value == "RenderSettings" - select nodes; - - foreach (var item in v) - { - var v2 = from nodes in item.Descendants((type != XMLTypes.Vector2Int16 ? type.ToString().ToLower() : "Vector2int16")) - where nodes.Attribute("name").Value == setting - select nodes; - - foreach (var item2 in v2) + get { - if (type != XMLTypes.Vector2Int16) - { - item2.Value = value; - } - else - { - string[] vals = value.Split('x'); - - var v3 = from nodes in item2.Descendants("X") - select nodes; - - foreach (var item3 in v3) - { - item3.Value = vals[0]; - } - - var v4 = from nodes in item2.Descendants("Y") - select nodes; - - foreach (var item4 in v4) - { - item4.Value = vals[1]; - } - } - } - } - } - - public static bool IsRenderSettingStringValid(XDocument doc, string setting, XMLTypes type) - { - if (type != XMLTypes.String) - return false; - - var v = from nodes in doc.Descendants("Item") - where nodes.Attribute("class").Value == "RenderSettings" - select nodes; - - foreach (var item in v) - { - var v2 = from nodes in item.Descendants(type.ToString().ToLower()) - where nodes.Attribute("name").Value == setting - select nodes; - - foreach (var item2 in v2) - { - return true; + return new AssetCacheDef("Sound", + new string[] { "SoundId" }, + new string[] { ".wav" }, + new string[] { GlobalPaths.hatdirSounds }, + new string[] { GlobalPaths.hatGameDirSounds }); } } - return false; - } - - public static string GetRenderSettings(XDocument doc, string setting, XMLTypes type) - { - var v = from nodes in doc.Descendants("Item") - where nodes.Attribute("class").Value == "RenderSettings" - select nodes; - - foreach (var item in v) + public static AssetCacheDef ItemHatScript { - var v2 = from nodes in item.Descendants((type != XMLTypes.Vector2Int16 ? type.ToString().ToLower() : "Vector2int16")) - where nodes.Attribute("name").Value == setting - select nodes; - - foreach (var item2 in v2) + get { - if (type != XMLTypes.Vector2Int16) - { - return item2.Value; - } - else - { - string ValX = ""; - string ValY = ""; - - var v3 = from nodes in item2.Descendants("X") - select nodes; - - foreach (var item3 in v3) - { - ValX = item3.Value; - } - - var v4 = from nodes in item2.Descendants("Y") - select nodes; - - foreach (var item4 in v4) - { - ValY = item4.Value; - } - - return ValX + "x" + ValY; - } + return new AssetCacheDef("Script", + new string[] { "LinkedSource" }, + new string[] { ".lua" }, + new string[] { GlobalPaths.hatdirScripts }, + new string[] { GlobalPaths.hatGameDirScripts }); } } - return ""; - } - - public static string GetURLInNodes(XDocument doc, string itemClassValue, string itemIdValue, string url) - { - var v = from nodes in doc.Descendants("Item") - where nodes.Attribute("class").Value == itemClassValue - select nodes; - - foreach (var item in v) + public static AssetCacheDef ItemHatLocalScript { - var v2 = from nodes in item.Descendants("Content") - where nodes.Attribute("name").Value == itemIdValue - select nodes; - - foreach (var item2 in v2) + get { - var v3 = from nodes in item2.Descendants("url") + return new AssetCacheDef("LocalScript", + new string[] { "LinkedSource" }, + new string[] { ".lua" }, + new string[] { GlobalPaths.hatdirScripts }, + new string[] { GlobalPaths.hatGameDirScripts }); + } + } + + public static AssetCacheDef ItemHeadFonts + { + get + { + return new AssetCacheDef("SpecialMesh", + new string[] { "MeshId", "TextureId" }, + new string[] { ".mesh", ".png" }, + new string[] { GlobalPaths.headdirFonts, GlobalPaths.headdirTextures }, + new string[] { GlobalPaths.headGameDirFonts, GlobalPaths.headGameDirTextures }); + } + } + + public static AssetCacheDef ItemFaceTexture + { + get + { + return new AssetCacheDef("Decal", + new string[] { "Texture" }, + new string[] { ".png" }, + new string[] { GlobalPaths.facedirTextures }, + new string[] { GlobalPaths.faceGameDirTextures }); + } + } + + public static AssetCacheDef ItemShirtTexture + { + get + { + return new AssetCacheDef("Shirt", + new string[] { "ShirtTemplate" }, + new string[] { ".png" }, + new string[] { GlobalPaths.shirtdirTextures }, + new string[] { GlobalPaths.shirtGameDirTextures }); + } + } + + public static AssetCacheDef ItemTShirtTexture + { + get + { + return new AssetCacheDef("ShirtGraphic", + new string[] { "Graphic" }, + new string[] { ".png" }, + new string[] { GlobalPaths.tshirtdirTextures }, + new string[] { GlobalPaths.tshirtGameDirTextures }); + } + } + + public static AssetCacheDef ItemPantsTexture + { + get + { + return new AssetCacheDef("Pants", + new string[] { "PantsTemplate" }, + new string[] { ".png" }, + new string[] { GlobalPaths.pantsdirTextures }, + new string[] { GlobalPaths.pantsGameDirTextures }); + } + } + } + #endregion + + #region XML Types + public enum XMLTypes + { + Token, + Bool, + Float, + String, + Vector2Int16, + Int + } + #endregion + + #region Roblox XML Parser + public static class RobloxXML + { + public static void EditRenderSettings(XDocument doc, string setting, string value, XMLTypes type) + { + var v = from nodes in doc.Descendants("Item") + where nodes.Attribute("class").Value == "RenderSettings" + select nodes; + + foreach (var item in v) + { + var v2 = from nodes in item.Descendants((type != XMLTypes.Vector2Int16 ? type.ToString().ToLower() : "Vector2int16")) + where nodes.Attribute("name").Value == setting select nodes; - foreach (var item3 in v3) + foreach (var item2 in v2) { - if (!item3.Value.Contains("rbxassetid")) + if (type != XMLTypes.Vector2Int16) { - if (!item3.Value.Contains("rbxasset")) + item2.Value = value; + } + else + { + string[] vals = value.Split('x'); + + var v3 = from nodes in item2.Descendants("X") + select nodes; + + foreach (var item3 in v3) + { + item3.Value = vals[0]; + } + + var v4 = from nodes in item2.Descendants("Y") + select nodes; + + foreach (var item4 in v4) + { + item4.Value = vals[1]; + } + } + } + } + } + + public static bool IsRenderSettingStringValid(XDocument doc, string setting, XMLTypes type) + { + if (type != XMLTypes.String) + return false; + + var v = from nodes in doc.Descendants("Item") + where nodes.Attribute("class").Value == "RenderSettings" + select nodes; + + foreach (var item in v) + { + var v2 = from nodes in item.Descendants(type.ToString().ToLower()) + where nodes.Attribute("name").Value == setting + select nodes; + + foreach (var item2 in v2) + { + return true; + } + } + + return false; + } + + public static string GetRenderSettings(XDocument doc, string setting, XMLTypes type) + { + var v = from nodes in doc.Descendants("Item") + where nodes.Attribute("class").Value == "RenderSettings" + select nodes; + + foreach (var item in v) + { + var v2 = from nodes in item.Descendants((type != XMLTypes.Vector2Int16 ? type.ToString().ToLower() : "Vector2int16")) + where nodes.Attribute("name").Value == setting + select nodes; + + foreach (var item2 in v2) + { + if (type != XMLTypes.Vector2Int16) + { + return item2.Value; + } + else + { + string ValX = ""; + string ValY = ""; + + var v3 = from nodes in item2.Descendants("X") + select nodes; + + foreach (var item3 in v3) + { + ValX = item3.Value; + } + + var v4 = from nodes in item2.Descendants("Y") + select nodes; + + foreach (var item4 in v4) + { + ValY = item4.Value; + } + + return ValX + "x" + ValY; + } + } + } + + return ""; + } + + public static string GetURLInNodes(XDocument doc, string itemClassValue, string itemIdValue, string url) + { + var v = from nodes in doc.Descendants("Item") + where nodes.Attribute("class").Value == itemClassValue + select nodes; + + foreach (var item in v) + { + var v2 = from nodes in item.Descendants("Content") + where nodes.Attribute("name").Value == itemIdValue + select nodes; + + foreach (var item2 in v2) + { + var v3 = from nodes in item2.Descendants("url") + select nodes; + + foreach (var item3 in v3) + { + if (!item3.Value.Contains("rbxassetid")) + { + if (!item3.Value.Contains("rbxasset")) + { + string oldurl = item3.Value; + string urlFixed = NovetusFuncs.FixURLString(oldurl, url); + string peram = "id="; + + if (urlFixed.Contains(peram)) + { + return urlFixed; + } + } + } + else { string oldurl = item3.Value; - string urlFixed = NovetusFuncs.FixURLString(oldurl, url); + string rbxassetid = "rbxassetid://"; + string urlFixed = url + oldurl.After(rbxassetid); string peram = "id="; if (urlFixed.Contains(peram)) @@ -641,35 +656,23 @@ public static class RobloxXML } } } - else - { - string oldurl = item3.Value; - string rbxassetid = "rbxassetid://"; - string urlFixed = url + oldurl.After(rbxassetid); - string peram = "id="; - - if (urlFixed.Contains(peram)) - { - return urlFixed; - } - } } } + + return ""; } - return ""; - } + public static string RemoveInvalidXmlChars(string content) + { + return new string(content.Where(ch => XmlConvert.IsXmlChar(ch)).ToArray()); + } - public static string RemoveInvalidXmlChars(string content) - { - return new string(content.Where(ch => XmlConvert.IsXmlChar(ch)).ToArray()); - } - - public static string ReplaceHexadecimalSymbols(string txt) - { - string r = "[\x00-\x08\x0B\x0C\x0E-\x1F]"; - return Regex.Replace(txt, r, "", RegexOptions.Compiled); + public static string ReplaceHexadecimalSymbols(string txt) + { + string r = "[\x00-\x08\x0B\x0C\x0E-\x1F]"; + return Regex.Replace(txt, r, "", RegexOptions.Compiled); + } } + #endregion + #endregion } -#endregion -#endregion diff --git a/Novetus/NovetusCore/StorageAndFunctions/SecurityFuncs.cs b/Novetus/NovetusCore/StorageAndFunctions/SecurityFuncs.cs index 4ac5072..0fe29f2 100644 --- a/Novetus/NovetusCore/StorageAndFunctions/SecurityFuncs.cs +++ b/Novetus/NovetusCore/StorageAndFunctions/SecurityFuncs.cs @@ -14,369 +14,376 @@ using System.Net; using System.Threading.Tasks; #endregion -#region Security Functions -public class SecurityFuncs +namespace Novetus.Core { - [DllImport("user32.dll")] - static extern int SetWindowText(IntPtr hWnd, string text); - - public static string RandomString(int length) + #region Security Functions + public class SecurityFuncs { - CryptoRandom random = new CryptoRandom(); - const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz"; - return new string(Enumerable.Repeat(chars, length) - .Select(s => s[random.Next(s.Length)]).ToArray()); - } + [DllImport("user32.dll")] + static extern int SetWindowText(IntPtr hWnd, string text); - public static int GenerateRandomNumber() - { - CryptoRandom random = new CryptoRandom(); - int randomID = 0; - int randIDmode = random.Next(0, 8); - int idlimit = 0; - - switch (randIDmode) + public static string RandomString(int length) { - case 0: - idlimit = 9; - break; - case 1: - idlimit = 99; - break; - case 2: - idlimit = 999; - break; - case 3: - idlimit = 9999; - break; - case 4: - idlimit = 99999; - break; - case 5: - idlimit = 999999; - break; - case 6: - idlimit = 9999999; - break; - case 7: - idlimit = 99999999; - break; - case 8: - default: - break; + CryptoRandom random = new CryptoRandom(); + const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz"; + return new string(Enumerable.Repeat(chars, length) + .Select(s => s[random.Next(s.Length)]).ToArray()); } - if (idlimit > 0) + public static int GenerateRandomNumber() { - randomID = random.Next(0, idlimit); - } - else - { - randomID = random.Next(); - } + CryptoRandom random = new CryptoRandom(); + int randomID = 0; + int randIDmode = random.Next(0, 8); + int idlimit = 0; - //2147483647 is max id. - return randomID; - } - - //these 2 methods are for the clientinfo creator. - public static string Base64DecodeNew(string base64EncodedData) - { - return base64EncodedData.Decrypt(); - } - - public static string Base64DecodeOld(string base64EncodedData) - { - var base64EncodedBytes = Convert.FromBase64String(base64EncodedData); - return System.Text.Encoding.UTF8.GetString(base64EncodedBytes); - } - - //this is for everything else - public static string Base64Decode(string base64EncodedData) - { - try - { - string decode = base64EncodedData.Decrypt(); - return decode; - } - catch(Exception) - { - var base64EncodedBytes = Convert.FromBase64String(base64EncodedData); - return System.Text.Encoding.UTF8.GetString(base64EncodedBytes); - } - } - - public static string Base64Encode(string plainText, bool oldVer = false) - { - if (oldVer) - { - var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText); - return System.Convert.ToBase64String(plainTextBytes); - } - else - { - return plainText.Crypt(); - } - } - - public static bool IsBase64String(string s) - { - s = s.Trim(); - return (s.Length % 4 == 0) && Regex.IsMatch(s, @"^[a-zA-Z0-9\+/]*={0,3}$", RegexOptions.None); - } - - public static long UnixTimeNow() - { - var timeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)); - return (long)timeSpan.TotalSeconds; - } - - public static bool checkClientMD5(string client) - { - if (!GlobalVars.AdminMode) - { - if (!GlobalVars.SelectedClientInfo.AlreadyHasSecurity) + switch (randIDmode) { - string rbxexe = ""; - string BasePath = GlobalPaths.BasePath + "\\clients\\" + client; - if (GlobalVars.SelectedClientInfo.LegacyMode) - { - rbxexe = BasePath + "\\RobloxApp.exe"; - } - else if (GlobalVars.SelectedClientInfo.SeperateFolders) - { - rbxexe = BasePath + "\\client\\RobloxApp_client.exe"; - } - else if (GlobalVars.SelectedClientInfo.UsesCustomClientEXEName) - { - rbxexe = BasePath + @"\\" + GlobalVars.SelectedClientInfo.CustomClientEXEName; - } - else - { - rbxexe = BasePath + "\\RobloxApp_client.exe"; - } - return CheckMD5(GlobalVars.SelectedClientInfo.ClientMD5, rbxexe); - } - else - { - return true; + case 0: + idlimit = 9; + break; + case 1: + idlimit = 99; + break; + case 2: + idlimit = 999; + break; + case 3: + idlimit = 9999; + break; + case 4: + idlimit = 99999; + break; + case 5: + idlimit = 999999; + break; + case 6: + idlimit = 9999999; + break; + case 7: + idlimit = 99999999; + break; + case 8: + default: + break; } - } - else - { - return true; - } - } - - public static bool checkScriptMD5(string client) - { - if (!GlobalVars.AdminMode) - { - if (!GlobalVars.SelectedClientInfo.AlreadyHasSecurity) + + if (idlimit > 0) { - string rbxscript = GlobalPaths.BasePath + "\\clients\\" + client + "\\content\\scripts\\" + GlobalPaths.ScriptName + ".lua"; - return CheckMD5(GlobalVars.SelectedClientInfo.ScriptMD5, rbxscript); - } else { - return true; + randomID = random.Next(0, idlimit); } - } else { - return true; - } - } - - public static bool CheckMD5(string MD5Hash, string path) - { - if (!File.Exists(path)) - return false; - - using (var md5 = MD5.Create()) - { - using (var stream = File.OpenRead(path)) + else { - byte[] hash = md5.ComputeHash(stream); - string clientMD5 = BitConverter.ToString(hash).Replace("-", ""); - if (clientMD5.Equals(MD5Hash)) + randomID = random.Next(); + } + + //2147483647 is max id. + return randomID; + } + + //these 2 methods are for the clientinfo creator. + public static string Base64DecodeNew(string base64EncodedData) + { + return base64EncodedData.Decrypt(); + } + + public static string Base64DecodeOld(string base64EncodedData) + { + var base64EncodedBytes = Convert.FromBase64String(base64EncodedData); + return System.Text.Encoding.UTF8.GetString(base64EncodedBytes); + } + + //this is for everything else + public static string Base64Decode(string base64EncodedData) + { + try + { + string decode = base64EncodedData.Decrypt(); + return decode; + } + catch (Exception) + { + var base64EncodedBytes = Convert.FromBase64String(base64EncodedData); + return System.Text.Encoding.UTF8.GetString(base64EncodedBytes); + } + } + + public static string Base64Encode(string plainText, bool oldVer = false) + { + if (oldVer) + { + var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText); + return System.Convert.ToBase64String(plainTextBytes); + } + else + { + return plainText.Crypt(); + } + } + + public static bool IsBase64String(string s) + { + s = s.Trim(); + return (s.Length % 4 == 0) && Regex.IsMatch(s, @"^[a-zA-Z0-9\+/]*={0,3}$", RegexOptions.None); + } + + public static long UnixTimeNow() + { + var timeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)); + return (long)timeSpan.TotalSeconds; + } + + public static bool checkClientMD5(string client) + { + if (!GlobalVars.AdminMode) + { + if (!GlobalVars.SelectedClientInfo.AlreadyHasSecurity) { - return true; + string rbxexe = ""; + string BasePath = GlobalPaths.BasePath + "\\clients\\" + client; + if (GlobalVars.SelectedClientInfo.LegacyMode) + { + rbxexe = BasePath + "\\RobloxApp.exe"; + } + else if (GlobalVars.SelectedClientInfo.SeperateFolders) + { + rbxexe = BasePath + "\\client\\RobloxApp_client.exe"; + } + else if (GlobalVars.SelectedClientInfo.UsesCustomClientEXEName) + { + rbxexe = BasePath + @"\\" + GlobalVars.SelectedClientInfo.CustomClientEXEName; + } + else + { + rbxexe = BasePath + "\\RobloxApp_client.exe"; + } + return CheckMD5(GlobalVars.SelectedClientInfo.ClientMD5, rbxexe); } else { - return false; + return true; } } - } - } - - public static string GenerateMD5(string filename) - { - using (var md5 = MD5.Create()) - { - using (var stream = new BufferedStream(File.OpenRead(filename), 1200000)) + else { - return BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", ""); + return true; } } - } - - public static bool IsElevated - { - get - { - return WindowsIdentity.GetCurrent().Owner.IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid); - } - } - - public static string RandomStringTitle() - { - CryptoRandom random = new CryptoRandom(); - return new String(' ', random.Next(20)); - } - public static void RenameWindow(Process exe, ScriptType type, string clientname, string mapname) - { - if (!GlobalVars.SelectedClientInfo.AlreadyHasSecurity) + public static bool checkScriptMD5(string client) { - int time = 500; - BackgroundWorker worker = new BackgroundWorker(); - worker.WorkerSupportsCancellation = true; - worker.DoWork += (obj, e) => WorkerDoWork(exe, type, time, worker, clientname, mapname); - worker.RunWorkerAsync(); - } - } - - private static void WorkerKill(Process exe, ScriptType type, int time, BackgroundWorker worker, string clientname, string mapname) - { - worker.DoWork -= (obj, e) => WorkerDoWork(exe, type, time, worker, clientname, mapname); - worker.CancelAsync(); - worker.Dispose(); - } - - private static void WorkerDoWork(Process exe, ScriptType type, int time, BackgroundWorker worker, string clientname, string mapname) - { - DateTime StartTimeAfterMinute = exe.StartTime.AddMinutes(1); - - if (exe.IsRunning()) - { - while (exe.IsRunning()) + if (!GlobalVars.AdminMode) { - if (exe.MainWindowHandle == null && DateTime.Now > StartTimeAfterMinute) - { - exe.Kill(); - WorkerKill(exe, type, time, worker, clientname, mapname); - break; - } - - switch (type) + if (!GlobalVars.SelectedClientInfo.AlreadyHasSecurity) { - case ScriptType.Client: - SetWindowText(exe.MainWindowHandle, "Novetus " - + GlobalVars.ProgramInformation.Version + " - " - + clientname + " " - + ScriptFuncs.Generator.GetNameForType(type) - + " [" + GlobalVars.CurrentServer.ToString() + "]" - + RandomStringTitle()); - break; - case ScriptType.Server: - case ScriptType.Solo: - SetWindowText(exe.MainWindowHandle, "Novetus " - + GlobalVars.ProgramInformation.Version + " - " - + clientname + " " - + ScriptFuncs.Generator.GetNameForType(type) - + (string.IsNullOrWhiteSpace(mapname) ? " [Place1]" : " [" + mapname + "]") - + RandomStringTitle()); - break; - case ScriptType.Studio: - SetWindowText(exe.MainWindowHandle, "Novetus Studio " - + GlobalVars.ProgramInformation.Version + " - " - + clientname - + (string.IsNullOrWhiteSpace(mapname) ? " [Place1]" : " [" + mapname + "]") - + RandomStringTitle()); - break; - case ScriptType.EasterEgg: - default: - SetWindowText(exe.MainWindowHandle, ScriptFuncs.Generator.GetNameForType(type) - + RandomStringTitle()); - break; + string rbxscript = GlobalPaths.BasePath + "\\clients\\" + client + "\\content\\scripts\\" + GlobalPaths.ScriptName + ".lua"; + return CheckMD5(GlobalVars.SelectedClientInfo.ScriptMD5, rbxscript); + } + else + { + return true; } - - Thread.Sleep(time); } - } - else + else + { + return true; + } + } + + public static bool CheckMD5(string MD5Hash, string path) { - Thread.Sleep(time); - RenameWindow(exe, type, clientname, mapname); - } - } + if (!File.Exists(path)) + return false; - public static string GetExternalIPAddress() - { - string ipAddress; - - try - { - ipAddress = new WebClient().DownloadString("https://ipv4.icanhazip.com/").TrimEnd(); + using (var md5 = MD5.Create()) + { + using (var stream = File.OpenRead(path)) + { + byte[] hash = md5.ComputeHash(stream); + string clientMD5 = BitConverter.ToString(hash).Replace("-", ""); + if (clientMD5.Equals(MD5Hash)) + { + return true; + } + else + { + return false; + } + } + } } + + public static string GenerateMD5(string filename) + { + using (var md5 = MD5.Create()) + { + using (var stream = new BufferedStream(File.OpenRead(filename), 1200000)) + { + return BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", ""); + } + } + } + + public static bool IsElevated + { + get + { + return WindowsIdentity.GetCurrent().Owner.IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid); + } + } + + public static string RandomStringTitle() + { + CryptoRandom random = new CryptoRandom(); + return new String(' ', random.Next(20)); + } + + public static void RenameWindow(Process exe, ScriptType type, string clientname, string mapname) + { + if (!GlobalVars.SelectedClientInfo.AlreadyHasSecurity) + { + int time = 500; + BackgroundWorker worker = new BackgroundWorker(); + worker.WorkerSupportsCancellation = true; + worker.DoWork += (obj, e) => WorkerDoWork(exe, type, time, worker, clientname, mapname); + worker.RunWorkerAsync(); + } + } + + private static void WorkerKill(Process exe, ScriptType type, int time, BackgroundWorker worker, string clientname, string mapname) + { + worker.DoWork -= (obj, e) => WorkerDoWork(exe, type, time, worker, clientname, mapname); + worker.CancelAsync(); + worker.Dispose(); + } + + private static void WorkerDoWork(Process exe, ScriptType type, int time, BackgroundWorker worker, string clientname, string mapname) + { + DateTime StartTimeAfterMinute = exe.StartTime.AddMinutes(1); + + if (exe.IsRunning()) + { + while (exe.IsRunning()) + { + if (exe.MainWindowHandle == null && DateTime.Now > StartTimeAfterMinute) + { + exe.Kill(); + WorkerKill(exe, type, time, worker, clientname, mapname); + break; + } + + switch (type) + { + case ScriptType.Client: + SetWindowText(exe.MainWindowHandle, "Novetus " + + GlobalVars.ProgramInformation.Version + " - " + + clientname + " " + + ScriptFuncs.Generator.GetNameForType(type) + + " [" + GlobalVars.CurrentServer.ToString() + "]" + + RandomStringTitle()); + break; + case ScriptType.Server: + case ScriptType.Solo: + SetWindowText(exe.MainWindowHandle, "Novetus " + + GlobalVars.ProgramInformation.Version + " - " + + clientname + " " + + ScriptFuncs.Generator.GetNameForType(type) + + (string.IsNullOrWhiteSpace(mapname) ? " [Place1]" : " [" + mapname + "]") + + RandomStringTitle()); + break; + case ScriptType.Studio: + SetWindowText(exe.MainWindowHandle, "Novetus Studio " + + GlobalVars.ProgramInformation.Version + " - " + + clientname + + (string.IsNullOrWhiteSpace(mapname) ? " [Place1]" : " [" + mapname + "]") + + RandomStringTitle()); + break; + case ScriptType.EasterEgg: + default: + SetWindowText(exe.MainWindowHandle, ScriptFuncs.Generator.GetNameForType(type) + + RandomStringTitle()); + break; + } + + Thread.Sleep(time); + } + } + else + { + Thread.Sleep(time); + RenameWindow(exe, type, clientname, mapname); + } + } + + public static string GetExternalIPAddress() + { + string ipAddress; + + try + { + ipAddress = new WebClient().DownloadString("https://ipv4.icanhazip.com/").TrimEnd(); + } #if URI || LAUNCHER || BASICLAUNCHER - catch (Exception ex) - { - Util.LogExceptions(ex); + catch (Exception ex) + { + Util.LogExceptions(ex); #else catch (Exception) { #endif - ipAddress = "localhost"; - } + ipAddress = "localhost"; + } - return ipAddress; - } + return ipAddress; + } - //modified from https://stackoverflow.com/questions/14687658/random-name-generator-in-c-sharp - public static string GenerateName(int len) - { - CryptoRandom r = new CryptoRandom(); - string[] consonants = { "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "l", "n", "p", "q", "r", "s", "sh", "zh", "t", "v", "w", "x" }; - string[] vowels = { "a", "e", "i", "o", "u", "ae", "y" }; - string Name = ""; - Name += consonants[r.Next(consonants.Length)].ToUpper(); - Name += vowels[r.Next(vowels.Length)]; - int b = 2; //b tells how many times a new letter has been added. It's 2 right now because the first two letters are already in the name. - while (b < len) + //modified from https://stackoverflow.com/questions/14687658/random-name-generator-in-c-sharp + public static string GenerateName(int len) { - Name += consonants[r.Next(consonants.Length)]; - b++; + CryptoRandom r = new CryptoRandom(); + string[] consonants = { "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "l", "n", "p", "q", "r", "s", "sh", "zh", "t", "v", "w", "x" }; + string[] vowels = { "a", "e", "i", "o", "u", "ae", "y" }; + string Name = ""; + Name += consonants[r.Next(consonants.Length)].ToUpper(); Name += vowels[r.Next(vowels.Length)]; - b++; + int b = 2; //b tells how many times a new letter has been added. It's 2 right now because the first two letters are already in the name. + while (b < len) + { + Name += consonants[r.Next(consonants.Length)]; + b++; + Name += vowels[r.Next(vowels.Length)]; + b++; + } + + return Name; } - return Name; - } - - //https://www.c-sharpcorner.com/article/caesar-cipher-in-c-sharp/ - public static char cipher(char ch, int key) - { - if (!char.IsLetter(ch)) + //https://www.c-sharpcorner.com/article/caesar-cipher-in-c-sharp/ + public static char cipher(char ch, int key) { - return ch; + if (!char.IsLetter(ch)) + { + return ch; + } + + char d = char.IsUpper(ch) ? 'A' : 'a'; + return (char)((((ch + key) - d) % 26) + d); } - char d = char.IsUpper(ch) ? 'A' : 'a'; - return (char)((((ch + key) - d) % 26) + d); + public static string Encipher(string input, int key) + { + string output = string.Empty; + + foreach (char ch in input) + output += cipher(ch, key); + + return output; + } + + public static string Decipher(string input, int key) + { + return Encipher(input, 26 - key); + } } - - public static string Encipher(string input, int key) - { - string output = string.Empty; - - foreach (char ch in input) - output += cipher(ch, key); - - return output; - } - - public static string Decipher(string input, int key) - { - return Encipher(input, 26 - key); - } -} -#endregion \ No newline at end of file + #endregion +} \ No newline at end of file diff --git a/Novetus/NovetusCore/StorageAndFunctions/Util.cs b/Novetus/NovetusCore/StorageAndFunctions/Util.cs index 73bb7cf..e0237d7 100644 --- a/Novetus/NovetusCore/StorageAndFunctions/Util.cs +++ b/Novetus/NovetusCore/StorageAndFunctions/Util.cs @@ -20,342 +20,306 @@ using Mono.Nat; #endif #endregion -#region Utils - -public static class Util +namespace Novetus.Core { - #region Extensions - //This code was brought to you by: - //https://stackoverflow.com/questions/1926264/color-different-parts-of-a-richtextbox-string - //https://stackoverflow.com/questions/262280/how-can-i-know-if-a-process-is-running - //https://stackoverflow.com/questions/444798/case-insensitive-containsstring - //https://stackoverflow.com/questions/6084940/how-do-i-search-a-multi-dimensional-array - //https://www.dotnetperls.com/between-before-after - //https://stackoverflow.com/questions/12422619/can-i-disable-the-close-button-of-a-form-using-c - //https://stackoverflow.com/questions/9031537/really-simple-encryption-with-c-sharp-and-symmetricalgorithm + #region Utils - #region Rich Text Box Extensions - public static void AppendText(this RichTextBox box, string text, Color color) + public static class Util { - box.SelectionStart = box.TextLength; - box.SelectionLength = 0; + #region Extensions + //This code was brought to you by: + //https://stackoverflow.com/questions/1926264/color-different-parts-of-a-richtextbox-string + //https://stackoverflow.com/questions/262280/how-can-i-know-if-a-process-is-running + //https://stackoverflow.com/questions/444798/case-insensitive-containsstring + //https://stackoverflow.com/questions/6084940/how-do-i-search-a-multi-dimensional-array + //https://www.dotnetperls.com/between-before-after + //https://stackoverflow.com/questions/12422619/can-i-disable-the-close-button-of-a-form-using-c + //https://stackoverflow.com/questions/9031537/really-simple-encryption-with-c-sharp-and-symmetricalgorithm - box.SelectionColor = color; - box.AppendText(text); - box.SelectionColor = box.ForeColor; - } - #endregion - - #region Process Extensions - public static bool IsRunning(this Process process) - { - try + #region Rich Text Box Extensions + public static void AppendText(this RichTextBox box, string text, Color color) { - Process.GetProcessById(process.Id); + box.SelectionStart = box.TextLength; + box.SelectionLength = 0; + + box.SelectionColor = color; + box.AppendText(text); + box.SelectionColor = box.ForeColor; } - catch (InvalidOperationException) + #endregion + + #region Process Extensions + public static bool IsRunning(this Process process) { - return false; - } - catch (ArgumentException) - { - return false; - } - return true; - } - #endregion - - #region String Extensions - public static bool Contains(this string source, string toCheck, StringComparison comp) - { - if (source == null) - return false; - return source.IndexOf(toCheck, comp) >= 0; - } - #endregion - - #region Substring Extensions - /// - /// Get string value between [first] a and [last] b. - /// - public static string Between(this string value, string a, string b) - { - int posA = value.IndexOf(a); - int posB = value.LastIndexOf(b); - if (posA == -1) - { - return ""; - } - if (posB == -1) - { - return ""; - } - int adjustedPosA = posA + a.Length; - if (adjustedPosA >= posB) - { - return ""; - } - return value.Substring(adjustedPosA, posB - adjustedPosA); - } - - /// - /// Get string value after [first] a. - /// - public static string Before(this string value, string a) - { - int posA = value.IndexOf(a); - if (posA == -1) - { - return ""; - } - return value.Substring(0, posA); - } - - /// - /// Get string value after [last] a. - /// - public static string After(this string value, string a) - { - int posA = value.LastIndexOf(a); - if (posA == -1) - { - return ""; - } - int adjustedPosA = posA + a.Length; - if (adjustedPosA >= value.Length) - { - return ""; - } - return value.Substring(adjustedPosA); - } - #endregion - - #region String Utilities - private static byte[] key = new byte[8] { 1, 2, 3, 4, 5, 6, 7, 8 }; - private static byte[] iv = new byte[8] { 1, 2, 3, 4, 5, 6, 7, 8 }; - - public static string Crypt(this string text) - { - SymmetricAlgorithm algorithm = DES.Create(); - ICryptoTransform transform = algorithm.CreateEncryptor(key, iv); - byte[] inputbuffer = Encoding.Unicode.GetBytes(text); - byte[] outputBuffer = transform.TransformFinalBlock(inputbuffer, 0, inputbuffer.Length); - return Convert.ToBase64String(outputBuffer); - } - - public static string Decrypt(this string text) - { - SymmetricAlgorithm algorithm = DES.Create(); - ICryptoTransform transform = algorithm.CreateDecryptor(key, iv); - byte[] inputbuffer = Convert.FromBase64String(text); - byte[] outputBuffer = transform.TransformFinalBlock(inputbuffer, 0, inputbuffer.Length); - return Encoding.Unicode.GetString(outputBuffer); - } - #endregion - - #region Exception Helpers - //https://github.com/AlexMelw/EasySharp/blob/master/NHelpers/ExceptionsDealing/Extensions/ExceptionExtensions.cs - /// - /// Gets the entire stack trace consisting of exception's footprints (File, Method, LineNumber) - /// - /// Source - /// - /// that represents the entire stack trace consisting of exception's footprints (File, - /// Method, LineNumber) - /// - public static string GetExceptionFootprints(this Exception exception) - { - StackTrace stackTrace = new StackTrace(exception, true); - StackFrame[] frames = stackTrace.GetFrames(); - - if (ReferenceEquals(frames, null)) - { - return string.Empty; - } - - var traceStringBuilder = new StringBuilder(); - - for (var i = 0; i < frames.Length; i++) - { - StackFrame frame = frames[i]; - - if (frame.GetFileLineNumber() < 1) - continue; - - traceStringBuilder.AppendLine($"File: {frame.GetFileName()}"); - traceStringBuilder.AppendLine($"Method: {frame.GetMethod().Name}"); - traceStringBuilder.AppendLine($"LineNumber: {frame.GetFileLineNumber()}"); - - if (i == frames.Length - 1) - break; - - traceStringBuilder.AppendLine(" ---> "); - } - - string stackTraceFootprints = traceStringBuilder.ToString(); - - if (string.IsNullOrWhiteSpace(stackTraceFootprints)) - return "NO DETECTED FOOTPRINTS"; - - return stackTraceFootprints; - } - #endregion - - #region DirectoryInfo Extensions - public static IEnumerable GetFilesByExtensions(this DirectoryInfo dir, params string[] extensions) - { - if (extensions == null) - throw new ArgumentNullException("extensions"); - IEnumerable files = dir.EnumerateFiles(); - return files.Where(f => extensions.Contains(f.Extension)); - } - #endregion - - #region DateTime Extensions - //https://stackoverflow.com/questions/5672862/check-if-datetime-instance-falls-in-between-other-two-datetime-objects - public static bool IsBetweenTwoDates(this DateTime dt, DateTime start, DateTime end) - { - return dt >= start && dt <= end; - } - #endregion - - #region Form Extensions - [DllImport("user32")] - public static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert); - - [DllImport("user32")] - public static extern bool EnableMenuItem(IntPtr hMenu, uint itemId, uint uEnable); - - public static void DisableCloseButton(this Form form) - { - // The 1 parameter means to gray out. 0xF060 is SC_CLOSE. - EnableMenuItem(GetSystemMenu(form.Handle, false), 0xF060, 1); - } - - public static void EnableCloseButton(this Form form) - { - // The zero parameter means to enable. 0xF060 is SC_CLOSE. - EnableMenuItem(GetSystemMenu(form.Handle, false), 0xF060, 0); - } - #endregion - - #region Process Extensions - //https://stackoverflow.com/questions/2633628/can-i-get-command-line-arguments-of-other-processes-from-net-c - // Define an extension method for type System.Process that returns the command - // line via WMI. - public static string GetCommandLine(this Process process) - { - string cmdLine = null; - using (var searcher = new ManagementObjectSearcher( - $"SELECT CommandLine FROM Win32_Process WHERE ProcessId = {process.Id}")) - { - // By definition, the query returns at most 1 match, because the process - // is looked up by ID (which is unique by definition). - using (var matchEnum = searcher.Get().GetEnumerator()) + try { - if (matchEnum.MoveNext()) // Move to the 1st item. - { - cmdLine = matchEnum.Current["CommandLine"]?.ToString(); - } + Process.GetProcessById(process.Id); } - } - if (cmdLine == null) - { - // Not having found a command line implies 1 of 2 exceptions, which the - // WMI query masked: - // An "Access denied" exception due to lack of privileges. - // A "Cannot process request because the process () has exited." - // exception due to the process having terminated. - // We provoke the same exception again simply by accessing process.MainModule. - var dummy = process.MainModule; // Provoke exception. - } - return cmdLine; - } - - // based off the above function - public static string GetFilePath(this Process process) - { - string path = null; - using (var searcher = new ManagementObjectSearcher( - $"SELECT ExecutablePath FROM Win32_Process WHERE ProcessId = {process.Id}")) - { - // By definition, the query returns at most 1 match, because the process - // is looked up by ID (which is unique by definition). - using (var matchEnum = searcher.Get().GetEnumerator()) + catch (InvalidOperationException) { - if (matchEnum.MoveNext()) // Move to the 1st item. - { - path = matchEnum.Current["ExecutablePath"]?.ToString(); - } + return false; } - } - if (path == null) - { - // Not having found a command line implies 1 of 2 exceptions, which the - // WMI query masked: - // An "Access denied" exception due to lack of privileges. - // A "Cannot process request because the process () has exited." - // exception due to the process having terminated. - // We provoke the same exception again simply by accessing process.MainModule. - var dummy = process.MainModule; // Provoke exception. - } - return path; - } - #endregion - #endregion - - #region Utility Functions - private static DialogResult ShowOverrideWarning(string dest) - { - DialogResult box = MessageBox.Show("A file with a similar name was detected in the directory as '" + dest + - "'.\n\nWould you like to override it?", "Novetus - Override Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); - - return box; - } - - public static void FixedFileCopy(string src, string dest, bool overwrite, bool overwritewarning = false) - { - if (File.Exists(dest)) - { - if (overwrite && overwritewarning) + catch (ArgumentException) { - if (ShowOverrideWarning(dest) == DialogResult.No) - { - return; - } + return false; + } + return true; + } + #endregion + + #region String Extensions + public static bool Contains(this string source, string toCheck, StringComparison comp) + { + if (source == null) + return false; + return source.IndexOf(toCheck, comp) >= 0; + } + #endregion + + #region Substring Extensions + /// + /// Get string value between [first] a and [last] b. + /// + public static string Between(this string value, string a, string b) + { + int posA = value.IndexOf(a); + int posB = value.LastIndexOf(b); + if (posA == -1) + { + return ""; + } + if (posB == -1) + { + return ""; + } + int adjustedPosA = posA + a.Length; + if (adjustedPosA >= posB) + { + return ""; + } + return value.Substring(adjustedPosA, posB - adjustedPosA); + } + + /// + /// Get string value after [first] a. + /// + public static string Before(this string value, string a) + { + int posA = value.IndexOf(a); + if (posA == -1) + { + return ""; + } + return value.Substring(0, posA); + } + + /// + /// Get string value after [last] a. + /// + public static string After(this string value, string a) + { + int posA = value.LastIndexOf(a); + if (posA == -1) + { + return ""; + } + int adjustedPosA = posA + a.Length; + if (adjustedPosA >= value.Length) + { + return ""; + } + return value.Substring(adjustedPosA); + } + #endregion + + #region String Utilities + private static byte[] key = new byte[8] { 1, 2, 3, 4, 5, 6, 7, 8 }; + private static byte[] iv = new byte[8] { 1, 2, 3, 4, 5, 6, 7, 8 }; + + public static string Crypt(this string text) + { + SymmetricAlgorithm algorithm = DES.Create(); + ICryptoTransform transform = algorithm.CreateEncryptor(key, iv); + byte[] inputbuffer = Encoding.Unicode.GetBytes(text); + byte[] outputBuffer = transform.TransformFinalBlock(inputbuffer, 0, inputbuffer.Length); + return Convert.ToBase64String(outputBuffer); + } + + public static string Decrypt(this string text) + { + SymmetricAlgorithm algorithm = DES.Create(); + ICryptoTransform transform = algorithm.CreateDecryptor(key, iv); + byte[] inputbuffer = Convert.FromBase64String(text); + byte[] outputBuffer = transform.TransformFinalBlock(inputbuffer, 0, inputbuffer.Length); + return Encoding.Unicode.GetString(outputBuffer); + } + #endregion + + #region Exception Helpers + //https://github.com/AlexMelw/EasySharp/blob/master/NHelpers/ExceptionsDealing/Extensions/ExceptionExtensions.cs + /// + /// Gets the entire stack trace consisting of exception's footprints (File, Method, LineNumber) + /// + /// Source + /// + /// that represents the entire stack trace consisting of exception's footprints (File, + /// Method, LineNumber) + /// + public static string GetExceptionFootprints(this Exception exception) + { + StackTrace stackTrace = new StackTrace(exception, true); + StackFrame[] frames = stackTrace.GetFrames(); + + if (ReferenceEquals(frames, null)) + { + return string.Empty; } - File.SetAttributes(dest, FileAttributes.Normal); - } + var traceStringBuilder = new StringBuilder(); - File.Copy(src, dest, overwrite); - File.SetAttributes(dest, FileAttributes.Normal); - } - - public static void FixedFileDelete(string src) - { - if (File.Exists(src)) - { - File.SetAttributes(src, FileAttributes.Normal); - File.Delete(src); - } - } - - public static void FixedFileMove(string src, string dest, bool overwrite, bool overwritewarning = false) - { - if (src.Equals(dest)) - return; - - if (!File.Exists(dest)) - { - File.SetAttributes(src, FileAttributes.Normal); - File.Move(src, dest); - } - else - { - if (overwrite) + for (var i = 0; i < frames.Length; i++) { - if (overwritewarning) + StackFrame frame = frames[i]; + + if (frame.GetFileLineNumber() < 1) + continue; + + traceStringBuilder.AppendLine($"File: {frame.GetFileName()}"); + traceStringBuilder.AppendLine($"Method: {frame.GetMethod().Name}"); + traceStringBuilder.AppendLine($"LineNumber: {frame.GetFileLineNumber()}"); + + if (i == frames.Length - 1) + break; + + traceStringBuilder.AppendLine(" ---> "); + } + + string stackTraceFootprints = traceStringBuilder.ToString(); + + if (string.IsNullOrWhiteSpace(stackTraceFootprints)) + return "NO DETECTED FOOTPRINTS"; + + return stackTraceFootprints; + } + #endregion + + #region DirectoryInfo Extensions + public static IEnumerable GetFilesByExtensions(this DirectoryInfo dir, params string[] extensions) + { + if (extensions == null) + throw new ArgumentNullException("extensions"); + IEnumerable files = dir.EnumerateFiles(); + return files.Where(f => extensions.Contains(f.Extension)); + } + #endregion + + #region DateTime Extensions + //https://stackoverflow.com/questions/5672862/check-if-datetime-instance-falls-in-between-other-two-datetime-objects + public static bool IsBetweenTwoDates(this DateTime dt, DateTime start, DateTime end) + { + return dt >= start && dt <= end; + } + #endregion + + #region Form Extensions + [DllImport("user32")] + public static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert); + + [DllImport("user32")] + public static extern bool EnableMenuItem(IntPtr hMenu, uint itemId, uint uEnable); + + public static void DisableCloseButton(this Form form) + { + // The 1 parameter means to gray out. 0xF060 is SC_CLOSE. + EnableMenuItem(GetSystemMenu(form.Handle, false), 0xF060, 1); + } + + public static void EnableCloseButton(this Form form) + { + // The zero parameter means to enable. 0xF060 is SC_CLOSE. + EnableMenuItem(GetSystemMenu(form.Handle, false), 0xF060, 0); + } + #endregion + + #region Process Extensions + //https://stackoverflow.com/questions/2633628/can-i-get-command-line-arguments-of-other-processes-from-net-c + // Define an extension method for type System.Process that returns the command + // line via WMI. + public static string GetCommandLine(this Process process) + { + string cmdLine = null; + using (var searcher = new ManagementObjectSearcher( + $"SELECT CommandLine FROM Win32_Process WHERE ProcessId = {process.Id}")) + { + // By definition, the query returns at most 1 match, because the process + // is looked up by ID (which is unique by definition). + using (var matchEnum = searcher.Get().GetEnumerator()) + { + if (matchEnum.MoveNext()) // Move to the 1st item. + { + cmdLine = matchEnum.Current["CommandLine"]?.ToString(); + } + } + } + if (cmdLine == null) + { + // Not having found a command line implies 1 of 2 exceptions, which the + // WMI query masked: + // An "Access denied" exception due to lack of privileges. + // A "Cannot process request because the process () has exited." + // exception due to the process having terminated. + // We provoke the same exception again simply by accessing process.MainModule. + var dummy = process.MainModule; // Provoke exception. + } + return cmdLine; + } + + // based off the above function + public static string GetFilePath(this Process process) + { + string path = null; + using (var searcher = new ManagementObjectSearcher( + $"SELECT ExecutablePath FROM Win32_Process WHERE ProcessId = {process.Id}")) + { + // By definition, the query returns at most 1 match, because the process + // is looked up by ID (which is unique by definition). + using (var matchEnum = searcher.Get().GetEnumerator()) + { + if (matchEnum.MoveNext()) // Move to the 1st item. + { + path = matchEnum.Current["ExecutablePath"]?.ToString(); + } + } + } + if (path == null) + { + // Not having found a command line implies 1 of 2 exceptions, which the + // WMI query masked: + // An "Access denied" exception due to lack of privileges. + // A "Cannot process request because the process () has exited." + // exception due to the process having terminated. + // We provoke the same exception again simply by accessing process.MainModule. + var dummy = process.MainModule; // Provoke exception. + } + return path; + } + #endregion + #endregion + + #region Utility Functions + private static DialogResult ShowOverrideWarning(string dest) + { + DialogResult box = MessageBox.Show("A file with a similar name was detected in the directory as '" + dest + + "'.\n\nWould you like to override it?", "Novetus - Override Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); + + return box; + } + + public static void FixedFileCopy(string src, string dest, bool overwrite, bool overwritewarning = false) + { + if (File.Exists(dest)) + { + if (overwrite && overwritewarning) { if (ShowOverrideWarning(dest) == DialogResult.No) { @@ -363,467 +327,505 @@ public static class Util } } - FixedFileDelete(dest); + File.SetAttributes(dest, FileAttributes.Normal); + } + + File.Copy(src, dest, overwrite); + File.SetAttributes(dest, FileAttributes.Normal); + } + + public static void FixedFileDelete(string src) + { + if (File.Exists(src)) + { + File.SetAttributes(src, FileAttributes.Normal); + File.Delete(src); + } + } + + public static void FixedFileMove(string src, string dest, bool overwrite, bool overwritewarning = false) + { + if (src.Equals(dest)) + return; + + if (!File.Exists(dest)) + { File.SetAttributes(src, FileAttributes.Normal); File.Move(src, dest); } else { - throw new IOException("Cannot create a file when that file already exists. FixedFileMove cannot override files with overwrite disabled."); + if (overwrite) + { + if (overwritewarning) + { + if (ShowOverrideWarning(dest) == DialogResult.No) + { + return; + } + } + + FixedFileDelete(dest); + File.SetAttributes(src, FileAttributes.Normal); + File.Move(src, dest); + } + else + { + throw new IOException("Cannot create a file when that file already exists. FixedFileMove cannot override files with overwrite disabled."); + } } } - } - //modified from the following: - //https://stackoverflow.com/questions/28887314/performance-of-image-loading - //https://stackoverflow.com/questions/2479771/c-why-am-i-getting-the-process-cannot-access-the-file-because-it-is-being-u - public static Image LoadImage(string fileFullName, string fallbackFileFullName = "") - { - if (string.IsNullOrWhiteSpace(fileFullName)) - return null; - - Image image = null; - - try + //modified from the following: + //https://stackoverflow.com/questions/28887314/performance-of-image-loading + //https://stackoverflow.com/questions/2479771/c-why-am-i-getting-the-process-cannot-access-the-file-because-it-is-being-u + public static Image LoadImage(string fileFullName, string fallbackFileFullName = "") { - using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(fileFullName))) - { - image = Image.FromStream(ms); - } + if (string.IsNullOrWhiteSpace(fileFullName)) + return null; - // PropertyItems seem to get lost when fileStream is closed to quickly (?); perhaps - // this is the reason Microsoft didn't want to close it in the first place. - PropertyItem[] items = image.PropertyItems; - - foreach (PropertyItem item in items) - { - image.SetPropertyItem(item); - } - } -#if URI || LAUNCHER || BASICLAUNCHER - catch (Exception ex) - { - LogExceptions(ex); -#else - catch (Exception) - { -#endif - if (!string.IsNullOrWhiteSpace(fallbackFileFullName)) - image = LoadImage(fallbackFileFullName); - } - - return image; - } - - //https://social.msdn.microsoft.com/Forums/vstudio/en-US/b0c31115-f6f0-4de5-a62d-d766a855d4d1/directorygetfiles-with-searchpattern-to-get-all-dll-and-exe-files-in-one-call?forum=netfxbcl - public static string[] GetFiles(string path, string searchPattern, SearchOption searchOption) - { - string[] searchPatterns = searchPattern.Split('|'); - List files = new List(); - foreach (string sp in searchPatterns) - files.AddRange(System.IO.Directory.GetFiles(path, sp, searchOption)); - files.Sort(); - return files.ToArray(); - } - - // Credit to Carrot for the original code. Rewote it to be smaller. - public static string CryptStringWithByte(string word) - { - byte[] bytes = Encoding.ASCII.GetBytes(word); - string result = ""; - for (int i = 0; i < bytes.Length; i++) { result += Convert.ToChar(0x55 ^ bytes[i]); } - return result; - } - - //https://stackoverflow.com/questions/1879395/how-do-i-generate-a-stream-from-a-string - public static Stream GenerateStreamFromString(string s) - { - var stream = new MemoryStream(); - var writer = new StreamWriter(stream); - writer.Write(s); - writer.Flush(); - stream.Position = 0; - return stream; - } - - //https://stackoverflow.com/questions/14488796/does-net-provide-an-easy-way-convert-bytes-to-kb-mb-gb-etc - private static readonly string[] SizeSuffixes = - { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" }; - public static string SizeSuffix(Int64 value, int decimalPlaces = 1) - { - if (decimalPlaces < 0) { throw new ArgumentOutOfRangeException("decimalPlaces"); } - if (value < 0) { return "-" + SizeSuffix(-value, decimalPlaces); } - if (value == 0) { return string.Format("{0:n" + decimalPlaces + "} bytes", 0); } - - // mag is 0 for bytes, 1 for KB, 2, for MB, etc. - int mag = (int)Math.Log(value, 1024); - - // 1L << (mag * 10) == 2 ^ (10 * mag) - // [i.e. the number of bytes in the unit corresponding to mag] - decimal adjustedSize = (decimal)value / (1L << (mag * 10)); - - // make adjustment when the value is large enough that - // it would round up to 1000 or more - if (Math.Round(adjustedSize, decimalPlaces) >= 1000) - { - mag += 1; - adjustedSize /= 1024; - } - - return string.Format("{0:n" + decimalPlaces + "} {1}", - adjustedSize, - SizeSuffixes[mag]); - } - - //https://stackoverflow.com/questions/11927116/getting-files-recursively-skip-files-directories-that-cannot-be-read - public static string[] FindAllFiles(string rootDir) - { - var pathsToSearch = new Queue(); - var foundFiles = new List(); - - pathsToSearch.Enqueue(rootDir); - - while (pathsToSearch.Count > 0) - { - var dir = pathsToSearch.Dequeue(); + Image image = null; try { - var files = Directory.GetFiles(dir); - foreach (var file in Directory.GetFiles(dir)) + using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(fileFullName))) { - foundFiles.Add(file); + image = Image.FromStream(ms); } - foreach (var subDir in Directory.GetDirectories(dir)) - { - pathsToSearch.Enqueue(subDir); - } + // PropertyItems seem to get lost when fileStream is closed to quickly (?); perhaps + // this is the reason Microsoft didn't want to close it in the first place. + PropertyItem[] items = image.PropertyItems; + foreach (PropertyItem item in items) + { + image.SetPropertyItem(item); + } } #if URI || LAUNCHER || BASICLAUNCHER catch (Exception ex) { LogExceptions(ex); +#else + catch (Exception) + { +#endif + if (!string.IsNullOrWhiteSpace(fallbackFileFullName)) + image = LoadImage(fallbackFileFullName); + } + + return image; + } + + //https://social.msdn.microsoft.com/Forums/vstudio/en-US/b0c31115-f6f0-4de5-a62d-d766a855d4d1/directorygetfiles-with-searchpattern-to-get-all-dll-and-exe-files-in-one-call?forum=netfxbcl + public static string[] GetFiles(string path, string searchPattern, SearchOption searchOption) + { + string[] searchPatterns = searchPattern.Split('|'); + List files = new List(); + foreach (string sp in searchPatterns) + files.AddRange(System.IO.Directory.GetFiles(path, sp, searchOption)); + files.Sort(); + return files.ToArray(); + } + + // Credit to Carrot for the original code. Rewote it to be smaller. + public static string CryptStringWithByte(string word) + { + byte[] bytes = Encoding.ASCII.GetBytes(word); + string result = ""; + for (int i = 0; i < bytes.Length; i++) { result += Convert.ToChar(0x55 ^ bytes[i]); } + return result; + } + + //https://stackoverflow.com/questions/1879395/how-do-i-generate-a-stream-from-a-string + public static Stream GenerateStreamFromString(string s) + { + var stream = new MemoryStream(); + var writer = new StreamWriter(stream); + writer.Write(s); + writer.Flush(); + stream.Position = 0; + return stream; + } + + //https://stackoverflow.com/questions/14488796/does-net-provide-an-easy-way-convert-bytes-to-kb-mb-gb-etc + private static readonly string[] SizeSuffixes = + { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" }; + public static string SizeSuffix(Int64 value, int decimalPlaces = 1) + { + if (decimalPlaces < 0) { throw new ArgumentOutOfRangeException("decimalPlaces"); } + if (value < 0) { return "-" + SizeSuffix(-value, decimalPlaces); } + if (value == 0) { return string.Format("{0:n" + decimalPlaces + "} bytes", 0); } + + // mag is 0 for bytes, 1 for KB, 2, for MB, etc. + int mag = (int)Math.Log(value, 1024); + + // 1L << (mag * 10) == 2 ^ (10 * mag) + // [i.e. the number of bytes in the unit corresponding to mag] + decimal adjustedSize = (decimal)value / (1L << (mag * 10)); + + // make adjustment when the value is large enough that + // it would round up to 1000 or more + if (Math.Round(adjustedSize, decimalPlaces) >= 1000) + { + mag += 1; + adjustedSize /= 1024; + } + + return string.Format("{0:n" + decimalPlaces + "} {1}", + adjustedSize, + SizeSuffixes[mag]); + } + + //https://stackoverflow.com/questions/11927116/getting-files-recursively-skip-files-directories-that-cannot-be-read + public static string[] FindAllFiles(string rootDir) + { + var pathsToSearch = new Queue(); + var foundFiles = new List(); + + pathsToSearch.Enqueue(rootDir); + + while (pathsToSearch.Count > 0) + { + var dir = pathsToSearch.Dequeue(); + + try + { + var files = Directory.GetFiles(dir); + foreach (var file in Directory.GetFiles(dir)) + { + foundFiles.Add(file); + } + + foreach (var subDir in Directory.GetDirectories(dir)) + { + pathsToSearch.Enqueue(subDir); + } + + } +#if URI || LAUNCHER || BASICLAUNCHER + catch (Exception ex) + { + LogExceptions(ex); #else catch (Exception) { #endif + } } + + return foundFiles.ToArray(); } - return foundFiles.ToArray(); - } + //https://stackoverflow.com/questions/66667263/i-want-to-remove-special-characters-from-file-name-without-affecting-extension-i + //https://stackoverflow.com/questions/3218910/rename-a-file-in-c-sharp - //https://stackoverflow.com/questions/66667263/i-want-to-remove-special-characters-from-file-name-without-affecting-extension-i - //https://stackoverflow.com/questions/3218910/rename-a-file-in-c-sharp - - public static bool FileHasInvalidChars(string path) - { - string fileName = Path.GetFileName(path); - - if (Regex.Match(fileName, @"[^\w-.'_!()& ]") != Match.Empty) + public static bool FileHasInvalidChars(string path) { - return true; - } - - return false; - } - - public static void RenameFileWithInvalidChars(string path) - { - try - { - if (!FileHasInvalidChars(path)) - return; - - string pathWithoutFilename = Path.GetDirectoryName(path); string fileName = Path.GetFileName(path); - fileName = Regex.Replace(fileName, @"[^\w-.'_!()& ]", ""); - string finalPath = pathWithoutFilename + "\\" + fileName; - FixedFileMove(path, finalPath, File.Exists(finalPath)); + if (Regex.Match(fileName, @"[^\w-.'_!()& ]") != Match.Empty) + { + return true; + } + + return false; } -#if URI || LAUNCHER || BASICLAUNCHER - catch (Exception ex) + + public static void RenameFileWithInvalidChars(string path) { - LogExceptions(ex); + try + { + if (!FileHasInvalidChars(path)) + return; + + string pathWithoutFilename = Path.GetDirectoryName(path); + string fileName = Path.GetFileName(path); + fileName = Regex.Replace(fileName, @"[^\w-.'_!()& ]", ""); + string finalPath = pathWithoutFilename + "\\" + fileName; + + FixedFileMove(path, finalPath, File.Exists(finalPath)); + } +#if URI || LAUNCHER || BASICLAUNCHER + catch (Exception ex) + { + LogExceptions(ex); #else catch (Exception) { #endif + } } - } - //http://stevenhollidge.blogspot.com/2012/06/async-taskdelay.html - public static Task Delay(int milliseconds) - { + //http://stevenhollidge.blogspot.com/2012/06/async-taskdelay.html + public static Task Delay(int milliseconds) + { #if NET4 var tcs = new TaskCompletionSource(); new System.Threading.Timer(_ => tcs.SetResult(null)).Change(milliseconds, -1); return tcs.Task; #elif NET481 - return Task.Delay(milliseconds); + return Task.Delay(milliseconds); #endif - } - - public static void LogPrint(string text, int type = 1) - { - Logger log = LogManager.GetCurrentClassLogger(); - - switch (type) - { - case 2: - log.Error(text); - break; - case 3: - log.Warn(text); - break; - default: - log.Info(text); - break; - } - } - -#if LAUNCHER || URI || BASICLAUNCHER - public static void LogExceptions(Exception ex) - { - string message = (ex.Message != null ? ex.Message.ToString() : "N/A"); - - ConsolePrint(ex.Source + " Exception: " + message, 2, false, true); - - LogPrint("EXCEPTION|MESSAGE: " + message, 2); - LogPrint("EXCEPTION|STACK TRACE: " + (!string.IsNullOrWhiteSpace(ex.StackTrace) ? ex.StackTrace : "N/A"), 2); - LogPrint("EXCEPTION|ADDITIONAL INFO: " + (ex != null ? ex.ToString() : "N/A"), 2); - } -#endif - - //https://stackoverflow.com/questions/27108264/how-to-properly-make-a-http-web-get-request - - private static string HttpGetInternal(string uri) - { - HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); - request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; - - using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) - { - using (Stream stream = response.GetResponseStream()) - { - using (StreamReader reader = new StreamReader(stream)) - { - return reader.ReadToEnd(); - } - } - } - } - public static string HttpGet(string uri) - { - int tries = 0; - int triesMax = 5; - string exceptionMessage = ""; - - while (tries < triesMax) - { - tries++; - try - { - return HttpGetInternal(uri); - } - catch (Exception ex) - { -#if URI || LAUNCHER || BASICLAUNCHER - LogExceptions(ex); -#endif - exceptionMessage = ex.Message; - continue; - } } - return "ERROR: " + exceptionMessage; - } - - public static void DrawBorderSimple(Graphics graphics, Rectangle bounds, Color color, ButtonBorderStyle style, int width) - { - //AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA - ControlPaint.DrawBorder(graphics, bounds, - color, width, style, - color, width, style, - color, width, style, - color, width, style); - } - - public static bool IsIPValid(string IP) - { - IPAddress address; - if (IPAddress.TryParse(IP, out address)) + public static void LogPrint(string text, int type = 1) { - switch (address.AddressFamily) + Logger log = LogManager.GetCurrentClassLogger(); + + switch (type) { - case System.Net.Sockets.AddressFamily.InterNetwork: - return true; - case System.Net.Sockets.AddressFamily.InterNetworkV6: + case 2: + log.Error(text); + break; + case 3: + log.Warn(text); + break; default: + log.Info(text); break; } } - return false; - } - - //converted from https://facreationz.wordpress.com/2014/12/11/c-know-if-running-under-wine/ - public static bool IsWineRunning() - { - string processName = "winlogon"; - var p = Process.GetProcessesByName(processName).Count(); - return (p <= 0); - } - - public static void ConsolePrint(string text, int type = 1, bool notime = false, bool noLog = false) - { - if (!notime) +#if LAUNCHER || URI || BASICLAUNCHER + public static void LogExceptions(Exception ex) { - ConsoleText("[" + DateTime.Now.ToShortTimeString() + "] - ", ConsoleColor.White); + string message = (ex.Message != null ? ex.Message.ToString() : "N/A"); + + ConsolePrint(ex.Source + " Exception: " + message, 2, false, true); + + LogPrint("EXCEPTION|MESSAGE: " + message, 2); + LogPrint("EXCEPTION|STACK TRACE: " + (!string.IsNullOrWhiteSpace(ex.StackTrace) ? ex.StackTrace : "N/A"), 2); + LogPrint("EXCEPTION|ADDITIONAL INFO: " + (ex != null ? ex.ToString() : "N/A"), 2); + } +#endif + + //https://stackoverflow.com/questions/27108264/how-to-properly-make-a-http-web-get-request + + private static string HttpGetInternal(string uri) + { + HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); + request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; + + using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) + { + using (Stream stream = response.GetResponseStream()) + { + using (StreamReader reader = new StreamReader(stream)) + { + return reader.ReadToEnd(); + } + } + } + } + public static string HttpGet(string uri) + { + int tries = 0; + int triesMax = 5; + string exceptionMessage = ""; + + while (tries < triesMax) + { + tries++; + try + { + return HttpGetInternal(uri); + } + catch (Exception ex) + { +#if URI || LAUNCHER || BASICLAUNCHER + LogExceptions(ex); +#endif + exceptionMessage = ex.Message; + continue; + } + } + + return "ERROR: " + exceptionMessage; } - switch (type) + public static void DrawBorderSimple(Graphics graphics, Rectangle bounds, Color color, ButtonBorderStyle style, int width) { - case 0: - ConsoleText(text, ConsoleColor.Black, true); - break; - case 2: - ConsoleText(text, ConsoleColor.Red, true); - if (!noLog) - LogPrint(text, 2); - break; - case 3: - ConsoleText(text, ConsoleColor.Green, true); - if (!noLog) - LogPrint(text); - break; - case 4: - ConsoleText(text, ConsoleColor.Cyan, true); - if (!noLog) - LogPrint(text); - break; - case 5: - ConsoleText(text, ConsoleColor.Yellow, true); - if (!noLog) - LogPrint(text, 3); - break; - case 1: - default: - ConsoleText(text, ConsoleColor.White, true); - if (!noLog) - LogPrint(text); - break; + //AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + ControlPaint.DrawBorder(graphics, bounds, + color, width, style, + color, width, style, + color, width, style, + color, width, style); } + public static bool IsIPValid(string IP) + { + IPAddress address; + if (IPAddress.TryParse(IP, out address)) + { + switch (address.AddressFamily) + { + case System.Net.Sockets.AddressFamily.InterNetwork: + return true; + case System.Net.Sockets.AddressFamily.InterNetworkV6: + default: + break; + } + } + + return false; + } + + //converted from https://facreationz.wordpress.com/2014/12/11/c-know-if-running-under-wine/ + public static bool IsWineRunning() + { + string processName = "winlogon"; + var p = Process.GetProcessesByName(processName).Count(); + return (p <= 0); + } + + public static void ConsolePrint(string text, int type = 1, bool notime = false, bool noLog = false) + { + if (!notime) + { + ConsoleText("[" + DateTime.Now.ToShortTimeString() + "] - ", ConsoleColor.White); + } + + switch (type) + { + case 0: + ConsoleText(text, ConsoleColor.Black, true); + break; + case 2: + ConsoleText(text, ConsoleColor.Red, true); + if (!noLog) + LogPrint(text, 2); + break; + case 3: + ConsoleText(text, ConsoleColor.Green, true); + if (!noLog) + LogPrint(text); + break; + case 4: + ConsoleText(text, ConsoleColor.Cyan, true); + if (!noLog) + LogPrint(text); + break; + case 5: + ConsoleText(text, ConsoleColor.Yellow, true); + if (!noLog) + LogPrint(text, 3); + break; + case 1: + default: + ConsoleText(text, ConsoleColor.White, true); + if (!noLog) + LogPrint(text); + break; + } + #if LAUNCHER if (GlobalVars.consoleForm != null) { FormPrint(text, type, GlobalVars.consoleForm.ConsoleBox, notime); } #endif - } - - public static void ConsolePrintMultiLine(string text, int type = 1, bool notime = false, bool noLog = false) - { - try - { - string[] NewlineChars = {Environment.NewLine, "\n"}; - string[] lines = text.Split(NewlineChars, StringSplitOptions.None); - ConsolePrintMultiLine(lines, type, notime, noLog); - } - catch (Exception e) - { -#if URI || LAUNCHER || BASICLAUNCHER - LogExceptions(e); -#endif - } - } - - public static void ConsolePrintMultiLine(ICollection textColection, int type = 1, bool notime = false, bool noLog = false) - { - if (!textColection.Any()) - return; - - if (textColection.Count == 1) - { - ConsolePrint(textColection.First(), type, notime, noLog); - return; } - foreach (string text in textColection) - { - ConsolePrint(text, type, notime, noLog); - } - } - - private static void FormPrint(string text, int type, RichTextBox box, bool noTime = false) - { - if (box == null) - return; - - if (!noTime) - { - box.AppendText("[" + DateTime.Now.ToShortTimeString() + "] - ", Color.White); - } - - switch (type) - { - case 1: - box.AppendText(text, Color.White); - break; - case 2: - box.AppendText(text, Color.Red); - break; - case 3: - box.AppendText(text, Color.Lime); - break; - case 4: - box.AppendText(text, Color.Aqua); - break; - case 5: - box.AppendText(text, Color.Yellow); - break; - case 0: - default: - box.AppendText(text, Color.Black); - break; - } - - box.AppendText(Environment.NewLine, Color.White); - } - - private static void ConsoleText(string text, ConsoleColor color, bool newLine = false) - { - Console.ForegroundColor = color; - if (newLine) - { - Console.WriteLine(text); - } - else - { - Console.Write(text); - } - } - - public static void ReadTextFileWithColor(string path) - { - var lines = File.ReadLines(path); - foreach (var line in lines) + public static void ConsolePrintMultiLine(string text, int type = 1, bool notime = false, bool noLog = false) { try { - string[] vals = line.Split('|'); - ConsolePrint(vals[0], Convert.ToInt32(vals[1]), true, true); + string[] NewlineChars = { Environment.NewLine, "\n" }; + string[] lines = text.Split(NewlineChars, StringSplitOptions.None); + ConsolePrintMultiLine(lines, type, notime, noLog); } - catch (Exception) + catch (Exception e) { - ConsolePrint(line, 1, true, true); +#if URI || LAUNCHER || BASICLAUNCHER + LogExceptions(e); +#endif + } + } + + public static void ConsolePrintMultiLine(ICollection textColection, int type = 1, bool notime = false, bool noLog = false) + { + if (!textColection.Any()) + return; + + if (textColection.Count == 1) + { + ConsolePrint(textColection.First(), type, notime, noLog); + return; + } + + foreach (string text in textColection) + { + ConsolePrint(text, type, notime, noLog); + } + } + + private static void FormPrint(string text, int type, RichTextBox box, bool noTime = false) + { + if (box == null) + return; + + if (!noTime) + { + box.AppendText("[" + DateTime.Now.ToShortTimeString() + "] - ", Color.White); + } + + switch (type) + { + case 1: + box.AppendText(text, Color.White); + break; + case 2: + box.AppendText(text, Color.Red); + break; + case 3: + box.AppendText(text, Color.Lime); + break; + case 4: + box.AppendText(text, Color.Aqua); + break; + case 5: + box.AppendText(text, Color.Yellow); + break; + case 0: + default: + box.AppendText(text, Color.Black); + break; + } + + box.AppendText(Environment.NewLine, Color.White); + } + + private static void ConsoleText(string text, ConsoleColor color, bool newLine = false) + { + Console.ForegroundColor = color; + if (newLine) + { + Console.WriteLine(text); + } + else + { + Console.Write(text); + } + } + + public static void ReadTextFileWithColor(string path) + { + var lines = File.ReadLines(path); + foreach (var line in lines) + { + try + { + string[] vals = line.Split('|'); + ConsolePrint(vals[0], Convert.ToInt32(vals[1]), true, true); + } + catch (Exception) + { + ConsolePrint(line, 1, true, true); + } } } - } #if LAUNCHER //https://stackoverflow.com/questions/30687987/unable-to-decompress-bz2-file-has-orginal-file-using-dotnetzip-library @@ -903,164 +905,165 @@ public static class Util dest.Write(buffer, 0, n); } #endif - #endregion + #endregion #if !BASICLAUNCHER - #region UPnP - public static void InitUPnP() - { - if (GlobalVars.UserConfiguration.UPnP) + #region UPnP + public static void InitUPnP() { - try + if (GlobalVars.UserConfiguration.UPnP) { - NetFuncs.InitUPnP(DeviceFound, DeviceLost); - ConsolePrint("UPnP: Service initialized", 3); - } - catch (Exception ex) - { - LogExceptions(ex); - ConsolePrint("UPnP: Unable to initialize UPnP. Reason - " + ex.Message, 2); + try + { + NetFuncs.InitUPnP(DeviceFound, DeviceLost); + ConsolePrint("UPnP: Service initialized", 3); + } + catch (Exception ex) + { + LogExceptions(ex); + ConsolePrint("UPnP: Unable to initialize UPnP. Reason - " + ex.Message, 2); + } } } - } - public static void StartUPnP(INatDevice device, Protocol protocol, int port) - { - if (GlobalVars.UserConfiguration.UPnP) + public static void StartUPnP(INatDevice device, Protocol protocol, int port) + { + if (GlobalVars.UserConfiguration.UPnP) + { + try + { + NetFuncs.StartUPnP(device, protocol, port); + string IP = !string.IsNullOrWhiteSpace(GlobalVars.UserConfiguration.AlternateServerIP) ? GlobalVars.UserConfiguration.AlternateServerIP : device.GetExternalIP().ToString(); + ConsolePrint("UPnP: Port " + port + " opened on '" + IP + "' (" + protocol.ToString() + ")", 3); + } + catch (Exception ex) + { + LogExceptions(ex); + ConsolePrint("UPnP: Unable to open port mapping. Reason - " + ex.Message, 2); + } + } + } + + public static void StopUPnP(INatDevice device, Protocol protocol, int port) + { + if (GlobalVars.UserConfiguration.UPnP) + { + try + { + NetFuncs.StopUPnP(device, protocol, port); + string IP = !string.IsNullOrWhiteSpace(GlobalVars.UserConfiguration.AlternateServerIP) ? GlobalVars.UserConfiguration.AlternateServerIP : device.GetExternalIP().ToString(); + ConsolePrint("UPnP: Port " + port + " closed on '" + IP + "' (" + protocol.ToString() + ")", 3); + } + catch (Exception ex) + { + LogExceptions(ex); + ConsolePrint("UPnP: Unable to close port mapping. Reason - " + ex.Message, 2); + } + } + } + + public static void DeviceFound(object sender, DeviceEventArgs args) { try { - NetFuncs.StartUPnP(device, protocol, port); + INatDevice device = args.Device; string IP = !string.IsNullOrWhiteSpace(GlobalVars.UserConfiguration.AlternateServerIP) ? GlobalVars.UserConfiguration.AlternateServerIP : device.GetExternalIP().ToString(); - ConsolePrint("UPnP: Port " + port + " opened on '" + IP + "' (" + protocol.ToString() + ")", 3); + ConsolePrint("UPnP: Device '" + IP + "' registered.", 3); + StartUPnP(device, Protocol.Udp, GlobalVars.UserConfiguration.RobloxPort); + StartUPnP(device, Protocol.Tcp, GlobalVars.UserConfiguration.RobloxPort); } catch (Exception ex) { LogExceptions(ex); - ConsolePrint("UPnP: Unable to open port mapping. Reason - " + ex.Message, 2); + ConsolePrint("UPnP: Unable to register device. Reason - " + ex.Message, 2); } } - } - public static void StopUPnP(INatDevice device, Protocol protocol, int port) - { - if (GlobalVars.UserConfiguration.UPnP) + public static void DeviceLost(object sender, DeviceEventArgs args) { try { - NetFuncs.StopUPnP(device, protocol, port); + INatDevice device = args.Device; string IP = !string.IsNullOrWhiteSpace(GlobalVars.UserConfiguration.AlternateServerIP) ? GlobalVars.UserConfiguration.AlternateServerIP : device.GetExternalIP().ToString(); - ConsolePrint("UPnP: Port " + port + " closed on '" + IP + "' (" + protocol.ToString() + ")", 3); + ConsolePrint("UPnP: Device '" + IP + "' disconnected.", 3); + StopUPnP(device, Protocol.Udp, GlobalVars.UserConfiguration.RobloxPort); + StopUPnP(device, Protocol.Tcp, GlobalVars.UserConfiguration.RobloxPort); } catch (Exception ex) { LogExceptions(ex); - ConsolePrint("UPnP: Unable to close port mapping. Reason - " + ex.Message, 2); + ConsolePrint("UPnP: Unable to disconnect device. Reason - " + ex.Message, 2); } } - } + #endregion - public static void DeviceFound(object sender, DeviceEventArgs args) - { - try + #region Discord + public static void ReadyCallback() { - INatDevice device = args.Device; - string IP = !string.IsNullOrWhiteSpace(GlobalVars.UserConfiguration.AlternateServerIP) ? GlobalVars.UserConfiguration.AlternateServerIP : device.GetExternalIP().ToString(); - ConsolePrint("UPnP: Device '" + IP + "' registered.", 3); - StartUPnP(device, Protocol.Udp, GlobalVars.UserConfiguration.RobloxPort); - StartUPnP(device, Protocol.Tcp, GlobalVars.UserConfiguration.RobloxPort); + ConsolePrint("Discord RPC: Ready", 3); } - catch (Exception ex) + + public static void DisconnectedCallback(int errorCode, string message) { - LogExceptions(ex); - ConsolePrint("UPnP: Unable to register device. Reason - " + ex.Message, 2); + ConsolePrint("Discord RPC: Disconnected. Reason - " + errorCode + ": " + message, 2); } - } - public static void DeviceLost(object sender, DeviceEventArgs args) - { - try + public static void ErrorCallback(int errorCode, string message) { - INatDevice device = args.Device; - string IP = !string.IsNullOrWhiteSpace(GlobalVars.UserConfiguration.AlternateServerIP) ? GlobalVars.UserConfiguration.AlternateServerIP : device.GetExternalIP().ToString(); - ConsolePrint("UPnP: Device '" + IP + "' disconnected.", 3); - StopUPnP(device, Protocol.Udp, GlobalVars.UserConfiguration.RobloxPort); - StopUPnP(device, Protocol.Tcp, GlobalVars.UserConfiguration.RobloxPort); + ConsolePrint("Discord RPC: Error. Reason - " + errorCode + ": " + message, 2); } - catch (Exception ex) + + public static void JoinCallback(string secret) { - LogExceptions(ex); - ConsolePrint("UPnP: Unable to disconnect device. Reason - " + ex.Message, 2); } - } - #endregion - #region Discord - public static void ReadyCallback() - { - ConsolePrint("Discord RPC: Ready", 3); - } - - public static void DisconnectedCallback(int errorCode, string message) - { - ConsolePrint("Discord RPC: Disconnected. Reason - " + errorCode + ": " + message, 2); - } - - public static void ErrorCallback(int errorCode, string message) - { - ConsolePrint("Discord RPC: Error. Reason - " + errorCode + ": " + message, 2); - } - - public static void JoinCallback(string secret) - { - } - - public static void SpectateCallback(string secret) - { - } - - public static void RequestCallback(DiscordRPC.JoinRequest request) - { - } - - public static void StartDiscord() - { - if (GlobalVars.UserConfiguration.DiscordPresence) + public static void SpectateCallback(string secret) { - GlobalVars.handlers = new DiscordRPC.EventHandlers(); - GlobalVars.handlers.readyCallback = ReadyCallback; - GlobalVars.handlers.disconnectedCallback += DisconnectedCallback; - GlobalVars.handlers.errorCallback += ErrorCallback; - GlobalVars.handlers.joinCallback += JoinCallback; - GlobalVars.handlers.spectateCallback += SpectateCallback; - GlobalVars.handlers.requestCallback += RequestCallback; - DiscordRPC.Initialize(GlobalVars.appid, ref GlobalVars.handlers, true, ""); - ConsolePrint("Discord RPC: Initalized", 3); - - ClientManagement.UpdateRichPresence(ClientManagement.GetStateForType(GlobalVars.GameOpened), true); } - } - #endregion + + public static void RequestCallback(DiscordRPC.JoinRequest request) + { + } + + public static void StartDiscord() + { + if (GlobalVars.UserConfiguration.DiscordPresence) + { + GlobalVars.handlers = new DiscordRPC.EventHandlers(); + GlobalVars.handlers.readyCallback = ReadyCallback; + GlobalVars.handlers.disconnectedCallback += DisconnectedCallback; + GlobalVars.handlers.errorCallback += ErrorCallback; + GlobalVars.handlers.joinCallback += JoinCallback; + GlobalVars.handlers.spectateCallback += SpectateCallback; + GlobalVars.handlers.requestCallback += RequestCallback; + DiscordRPC.Initialize(GlobalVars.appid, ref GlobalVars.handlers, true, ""); + ConsolePrint("Discord RPC: Initalized", 3); + + ClientManagement.UpdateRichPresence(ClientManagement.GetStateForType(GlobalVars.GameOpened), true); + } + } + #endregion #endif -} -#endregion - -#region Tab Control without Header -//https://stackoverflow.com/questions/23247941/c-sharp-how-to-remove-tabcontrol-border - -public partial class TabControlWithoutHeader : TabControl -{ - public TabControlWithoutHeader() - { - if (!DesignMode) Multiline = true; } + #endregion - protected override void WndProc(ref Message m) + #region Tab Control without Header + //https://stackoverflow.com/questions/23247941/c-sharp-how-to-remove-tabcontrol-border + + public partial class TabControlWithoutHeader : TabControl { - if (m.Msg == 0x1328 && !DesignMode) - m.Result = new IntPtr(1); - else - base.WndProc(ref m); + public TabControlWithoutHeader() + { + if (!DesignMode) Multiline = true; + } + + protected override void WndProc(ref Message m) + { + if (m.Msg == 0x1328 && !DesignMode) + m.Result = new IntPtr(1); + else + base.WndProc(ref m); + } } -} -#endregion \ No newline at end of file + #endregion +} \ No newline at end of file diff --git a/Novetus/NovetusLauncher/Classes/Launcher/ModManager.cs b/Novetus/NovetusLauncher/Classes/Launcher/ModManager.cs index bf9be1c..498b709 100644 --- a/Novetus/NovetusLauncher/Classes/Launcher/ModManager.cs +++ b/Novetus/NovetusLauncher/Classes/Launcher/ModManager.cs @@ -1,5 +1,6 @@ #region Usings using Ionic.Zip; +using Novetus.Core; using System; using System.Collections.Generic; using System.IO; diff --git a/Novetus/NovetusLauncher/Classes/Launcher/SplashLoader.cs b/Novetus/NovetusLauncher/Classes/Launcher/SplashLoader.cs index 6630afb..f94c366 100644 --- a/Novetus/NovetusLauncher/Classes/Launcher/SplashLoader.cs +++ b/Novetus/NovetusLauncher/Classes/Launcher/SplashLoader.cs @@ -1,4 +1,5 @@ #region Usings +using Novetus.Core; using System; using System.Collections.Generic; using System.Globalization; diff --git a/Novetus/NovetusLauncher/Classes/Launcher/TreeNodeHelper.cs b/Novetus/NovetusLauncher/Classes/Launcher/TreeNodeHelper.cs index fc2445f..c037963 100644 --- a/Novetus/NovetusLauncher/Classes/Launcher/TreeNodeHelper.cs +++ b/Novetus/NovetusLauncher/Classes/Launcher/TreeNodeHelper.cs @@ -1,4 +1,5 @@ #region Usings +using Novetus.Core; using System; using System.Collections.Generic; using System.IO; diff --git a/Novetus/NovetusLauncher/Forms/CustomGraphicsOptions.cs b/Novetus/NovetusLauncher/Forms/CustomGraphicsOptions.cs index 6018ab7..50d46e5 100644 --- a/Novetus/NovetusLauncher/Forms/CustomGraphicsOptions.cs +++ b/Novetus/NovetusLauncher/Forms/CustomGraphicsOptions.cs @@ -1,4 +1,5 @@ #region Usings +using Novetus.Core; using System; using System.Diagnostics; using System.IO; diff --git a/Novetus/NovetusLauncher/Forms/Decoder.cs b/Novetus/NovetusLauncher/Forms/Decoder.cs index bb10e48..8fdbd29 100644 --- a/Novetus/NovetusLauncher/Forms/Decoder.cs +++ b/Novetus/NovetusLauncher/Forms/Decoder.cs @@ -1,4 +1,5 @@ -using System.Windows.Forms; +using Novetus.Core; +using System.Windows.Forms; namespace NovetusLauncher { diff --git a/Novetus/NovetusLauncher/Forms/LauncherForm/Compact/LauncherFormCompact.Designer.cs b/Novetus/NovetusLauncher/Forms/LauncherForm/Compact/LauncherFormCompact.Designer.cs index e5b3597..c9d1138 100644 --- a/Novetus/NovetusLauncher/Forms/LauncherForm/Compact/LauncherFormCompact.Designer.cs +++ b/Novetus/NovetusLauncher/Forms/LauncherForm/Compact/LauncherFormCompact.Designer.cs @@ -6,6 +6,8 @@ * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ +using Novetus.Core; + namespace NovetusLauncher { partial class LauncherFormCompact diff --git a/Novetus/NovetusLauncher/Forms/LauncherForm/Compact/LauncherFormCompact.cs b/Novetus/NovetusLauncher/Forms/LauncherForm/Compact/LauncherFormCompact.cs index 63e2e34..94ed02a 100644 --- a/Novetus/NovetusLauncher/Forms/LauncherForm/Compact/LauncherFormCompact.cs +++ b/Novetus/NovetusLauncher/Forms/LauncherForm/Compact/LauncherFormCompact.cs @@ -1,5 +1,6 @@ #region Usings using Mono.Nat; +using Novetus.Core; using System; using System.Collections.Generic; using System.ComponentModel; diff --git a/Novetus/NovetusLauncher/Forms/LauncherForm/Extended/LauncherFormExtended.Designer.cs b/Novetus/NovetusLauncher/Forms/LauncherForm/Extended/LauncherFormExtended.Designer.cs index cbdd906..a70ad78 100644 --- a/Novetus/NovetusLauncher/Forms/LauncherForm/Extended/LauncherFormExtended.Designer.cs +++ b/Novetus/NovetusLauncher/Forms/LauncherForm/Extended/LauncherFormExtended.Designer.cs @@ -6,6 +6,8 @@ * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ +using Novetus.Core; + namespace NovetusLauncher { partial class LauncherFormExtended diff --git a/Novetus/NovetusLauncher/Forms/LauncherForm/Extended/LauncherFormExtended.cs b/Novetus/NovetusLauncher/Forms/LauncherForm/Extended/LauncherFormExtended.cs index 2c77821..3a8d06c 100644 --- a/Novetus/NovetusLauncher/Forms/LauncherForm/Extended/LauncherFormExtended.cs +++ b/Novetus/NovetusLauncher/Forms/LauncherForm/Extended/LauncherFormExtended.cs @@ -10,6 +10,7 @@ using System.Reflection; using Mono.Nat; using System.Globalization; using System.Linq; +using Novetus.Core; #endregion namespace NovetusLauncher diff --git a/Novetus/NovetusLauncher/Forms/LauncherForm/LauncherFormShared.cs b/Novetus/NovetusLauncher/Forms/LauncherForm/LauncherFormShared.cs index 7ca63ac..8ae7da9 100644 --- a/Novetus/NovetusLauncher/Forms/LauncherForm/LauncherFormShared.cs +++ b/Novetus/NovetusLauncher/Forms/LauncherForm/LauncherFormShared.cs @@ -1,5 +1,6 @@ #region Usings using Mono.Nat; +using Novetus.Core; using System; using System.Collections.Generic; using System.ComponentModel; diff --git a/Novetus/NovetusLauncher/Forms/LauncherForm/Stylish/LauncherFormStylish.cs b/Novetus/NovetusLauncher/Forms/LauncherForm/Stylish/LauncherFormStylish.cs index 412afbc..81849fe 100644 --- a/Novetus/NovetusLauncher/Forms/LauncherForm/Stylish/LauncherFormStylish.cs +++ b/Novetus/NovetusLauncher/Forms/LauncherForm/Stylish/LauncherFormStylish.cs @@ -1,4 +1,5 @@ #region Usings +using Novetus.Core; using System; using System.Collections.Generic; using System.ComponentModel; diff --git a/Novetus/NovetusLauncher/Forms/LauncherForm/Stylish/LauncherFormStylishInterface.xaml.cs b/Novetus/NovetusLauncher/Forms/LauncherForm/Stylish/LauncherFormStylishInterface.xaml.cs index 5aa55c0..ea892f6 100644 --- a/Novetus/NovetusLauncher/Forms/LauncherForm/Stylish/LauncherFormStylishInterface.xaml.cs +++ b/Novetus/NovetusLauncher/Forms/LauncherForm/Stylish/LauncherFormStylishInterface.xaml.cs @@ -1,4 +1,5 @@ #region Usings +using Novetus.Core; using System; using System.Collections.Generic; using System.IO; diff --git a/Novetus/NovetusLauncher/Forms/LauncherFormSettings.cs b/Novetus/NovetusLauncher/Forms/LauncherFormSettings.cs index d1beb4f..47fa25c 100644 --- a/Novetus/NovetusLauncher/Forms/LauncherFormSettings.cs +++ b/Novetus/NovetusLauncher/Forms/LauncherFormSettings.cs @@ -1,4 +1,5 @@ #region Usings +using Novetus.Core; using System; using System.Diagnostics; using System.Windows.Forms; diff --git a/Novetus/NovetusLauncher/Forms/NovetusConsole.cs b/Novetus/NovetusLauncher/Forms/NovetusConsole.cs index 57096aa..3d11775 100644 --- a/Novetus/NovetusLauncher/Forms/NovetusConsole.cs +++ b/Novetus/NovetusLauncher/Forms/NovetusConsole.cs @@ -10,6 +10,7 @@ using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using NLog; +using Novetus.Core; namespace NovetusLauncher { diff --git a/Novetus/NovetusLauncher/Forms/SDK/AssetDownloader.cs b/Novetus/NovetusLauncher/Forms/SDK/AssetDownloader.cs index d56fc14..c83b2c5 100644 --- a/Novetus/NovetusLauncher/Forms/SDK/AssetDownloader.cs +++ b/Novetus/NovetusLauncher/Forms/SDK/AssetDownloader.cs @@ -1,4 +1,5 @@ #region Usings +using Novetus.Core; using System; using System.Collections.Generic; using System.ComponentModel; diff --git a/Novetus/NovetusLauncher/Forms/SDK/AssetFixer.cs b/Novetus/NovetusLauncher/Forms/SDK/AssetFixer.cs index 3570ba5..fd8b1c0 100644 --- a/Novetus/NovetusLauncher/Forms/SDK/AssetFixer.cs +++ b/Novetus/NovetusLauncher/Forms/SDK/AssetFixer.cs @@ -1,4 +1,5 @@ #region Usings +using Novetus.Core; using System; using System.Collections.Generic; using System.ComponentModel; diff --git a/Novetus/NovetusLauncher/Forms/SDK/ClientScriptDocumentation.cs b/Novetus/NovetusLauncher/Forms/SDK/ClientScriptDocumentation.cs index bea14d0..76f4103 100644 --- a/Novetus/NovetusLauncher/Forms/SDK/ClientScriptDocumentation.cs +++ b/Novetus/NovetusLauncher/Forms/SDK/ClientScriptDocumentation.cs @@ -2,10 +2,11 @@ using System; using System.Windows.Forms; using System.IO; +using Novetus.Core; #endregion #region ClientScriptDocumentation - public partial class ClientScriptDocumentation : Form +public partial class ClientScriptDocumentation : Form { #region Constructor public ClientScriptDocumentation() diff --git a/Novetus/NovetusLauncher/Forms/SDK/ClientinfoCreator.cs b/Novetus/NovetusLauncher/Forms/SDK/ClientinfoCreator.cs index 16a2905..387d3c4 100644 --- a/Novetus/NovetusLauncher/Forms/SDK/ClientinfoCreator.cs +++ b/Novetus/NovetusLauncher/Forms/SDK/ClientinfoCreator.cs @@ -4,6 +4,7 @@ using System.Windows.Forms; using System.IO; using System.Globalization; using System.Collections.Generic; +using Novetus.Core; #endregion #region Client SDK diff --git a/Novetus/NovetusLauncher/Forms/SDK/DiogenesEditor.cs b/Novetus/NovetusLauncher/Forms/SDK/DiogenesEditor.cs index ba88b93..210fc6b 100644 --- a/Novetus/NovetusLauncher/Forms/SDK/DiogenesEditor.cs +++ b/Novetus/NovetusLauncher/Forms/SDK/DiogenesEditor.cs @@ -1,4 +1,5 @@ #region Usings +using Novetus.Core; using System; using System.IO; using System.Text; diff --git a/Novetus/NovetusLauncher/Forms/SDK/ItemCreationSDK.cs b/Novetus/NovetusLauncher/Forms/SDK/ItemCreationSDK.cs index 962c673..11aea90 100644 --- a/Novetus/NovetusLauncher/Forms/SDK/ItemCreationSDK.cs +++ b/Novetus/NovetusLauncher/Forms/SDK/ItemCreationSDK.cs @@ -1,4 +1,5 @@ #region Usings +using Novetus.Core; using System; using System.Collections.Generic; using System.Drawing; diff --git a/Novetus/NovetusLauncher/Forms/SDK/ItemCreationSDKColorMenu.cs b/Novetus/NovetusLauncher/Forms/SDK/ItemCreationSDKColorMenu.cs index 1975604..2e03d2f 100644 --- a/Novetus/NovetusLauncher/Forms/SDK/ItemCreationSDKColorMenu.cs +++ b/Novetus/NovetusLauncher/Forms/SDK/ItemCreationSDKColorMenu.cs @@ -1,4 +1,5 @@ #region Usings +using Novetus.Core; using System; using System.Windows.Forms; #endregion diff --git a/Novetus/NovetusLauncher/Forms/SDK/MeshConverter.cs b/Novetus/NovetusLauncher/Forms/SDK/MeshConverter.cs index 3253719..cc7d8a2 100644 --- a/Novetus/NovetusLauncher/Forms/SDK/MeshConverter.cs +++ b/Novetus/NovetusLauncher/Forms/SDK/MeshConverter.cs @@ -1,4 +1,5 @@ #region Usings +using Novetus.Core; using System; using System.Collections.Generic; using System.ComponentModel; diff --git a/Novetus/NovetusLauncher/Forms/SDK/ModCreator.cs b/Novetus/NovetusLauncher/Forms/SDK/ModCreator.cs index b7d3167..60e4a3f 100644 --- a/Novetus/NovetusLauncher/Forms/SDK/ModCreator.cs +++ b/Novetus/NovetusLauncher/Forms/SDK/ModCreator.cs @@ -1,4 +1,5 @@ -using System; +using Novetus.Core; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; diff --git a/Novetus/NovetusLauncher/Forms/SDK/NovetusSDK.cs b/Novetus/NovetusLauncher/Forms/SDK/NovetusSDK.cs index bb29d2a..58263f7 100644 --- a/Novetus/NovetusLauncher/Forms/SDK/NovetusSDK.cs +++ b/Novetus/NovetusLauncher/Forms/SDK/NovetusSDK.cs @@ -1,4 +1,5 @@ #region Usings +using Novetus.Core; using System; using System.Collections.Generic; using System.ComponentModel; diff --git a/Novetus/NovetusLauncher/Forms/SDK/SplashTester.cs b/Novetus/NovetusLauncher/Forms/SDK/SplashTester.cs index efde336..265b9f5 100644 --- a/Novetus/NovetusLauncher/Forms/SDK/SplashTester.cs +++ b/Novetus/NovetusLauncher/Forms/SDK/SplashTester.cs @@ -1,4 +1,5 @@ #region Usings +using Novetus.Core; using System; using System.Drawing; using System.Linq; diff --git a/Novetus/NovetusLauncher/Forms/SDK/XMLContentEditor.cs b/Novetus/NovetusLauncher/Forms/SDK/XMLContentEditor.cs index 08e6018..fe06ed8 100644 --- a/Novetus/NovetusLauncher/Forms/SDK/XMLContentEditor.cs +++ b/Novetus/NovetusLauncher/Forms/SDK/XMLContentEditor.cs @@ -1,4 +1,5 @@ #region Usings +using Novetus.Core; using System; using System.Collections.Generic; using System.IO; diff --git a/Novetus/NovetusLauncher/Forms/ServerBrowser.cs b/Novetus/NovetusLauncher/Forms/ServerBrowser.cs index 150f28f..6e0d7eb 100644 --- a/Novetus/NovetusLauncher/Forms/ServerBrowser.cs +++ b/Novetus/NovetusLauncher/Forms/ServerBrowser.cs @@ -1,4 +1,5 @@ #region Usings +using Novetus.Core; using System; using System.Collections.Generic; using System.Drawing; diff --git a/Novetus/NovetusLauncher/NovetusLauncherEntryPoint.cs b/Novetus/NovetusLauncher/NovetusLauncherEntryPoint.cs index 44e7fb1..c2f0efb 100644 --- a/Novetus/NovetusLauncher/NovetusLauncherEntryPoint.cs +++ b/Novetus/NovetusLauncher/NovetusLauncherEntryPoint.cs @@ -1,5 +1,6 @@ #region Usings using NLog; +using Novetus.Core; using System; using System.Diagnostics; using System.Globalization; diff --git a/Novetus/NovetusURI/Classes/LocalFuncs.cs b/Novetus/NovetusURI/Classes/LocalFuncs.cs index af16a46..eb5c888 100644 --- a/Novetus/NovetusURI/Classes/LocalFuncs.cs +++ b/Novetus/NovetusURI/Classes/LocalFuncs.cs @@ -1,5 +1,6 @@ #region Usings using Microsoft.Win32; +using Novetus.Core; using System; using System.IO; using System.Windows.Forms; diff --git a/Novetus/NovetusURI/Forms/InstallForm.cs b/Novetus/NovetusURI/Forms/InstallForm.cs index 7962a0f..0904332 100644 --- a/Novetus/NovetusURI/Forms/InstallForm.cs +++ b/Novetus/NovetusURI/Forms/InstallForm.cs @@ -1,4 +1,5 @@ #region Usings +using Novetus.Core; using System; using System.Windows.Forms; #endregion diff --git a/Novetus/NovetusURI/Forms/LoaderForm.cs b/Novetus/NovetusURI/Forms/LoaderForm.cs index 6ebc1da..29cba58 100644 --- a/Novetus/NovetusURI/Forms/LoaderForm.cs +++ b/Novetus/NovetusURI/Forms/LoaderForm.cs @@ -5,6 +5,7 @@ using System.Diagnostics; using System.Threading; using System.Windows.Forms; using NLog; +using Novetus.Core; #endregion namespace NovetusURI diff --git a/Novetus/NovetusURI/Forms/QuickConfigure.cs b/Novetus/NovetusURI/Forms/QuickConfigure.cs index 76ba01e..cbb8507 100644 --- a/Novetus/NovetusURI/Forms/QuickConfigure.cs +++ b/Novetus/NovetusURI/Forms/QuickConfigure.cs @@ -3,6 +3,7 @@ using System; using System.Windows.Forms; using System.ComponentModel; using System.Drawing; +using Novetus.Core; #endregion namespace NovetusURI diff --git a/Novetus/NovetusURI/NovetusURI.cs b/Novetus/NovetusURI/NovetusURI.cs index f4bdc65..f5b0483 100644 --- a/Novetus/NovetusURI/NovetusURI.cs +++ b/Novetus/NovetusURI/NovetusURI.cs @@ -1,5 +1,6 @@ #region Usings using NLog; +using Novetus.Core; using System; using System.IO; using System.Threading;