From 87823a15789c08323d6cfe6f17d0ccb939fabf02 Mon Sep 17 00:00:00 2001 From: Bitl Date: Mon, 12 Sep 2022 14:06:54 -0700 Subject: [PATCH] refactoring --- .../CharCustom/ContentProviders.cs | 69 - Novetus/NovetusCore/CharCustom/IconLoader.cs | 66 - Novetus/NovetusCore/Classes/FileFormat.cs | 199 -- Novetus/NovetusCore/Classes/PartColors.cs | 185 - Novetus/NovetusCore/Classes/ROBLOXHelpers.cs | 332 -- Novetus/NovetusCore/Classes/RobloxXML.cs | 217 -- Novetus/NovetusCore/Classes/Settings.cs | 91 - .../{Imported => Classes}/UHWIDEngine.cs | 0 Novetus/NovetusCore/NovetusCore.projitems | 20 +- .../StorageAndFunctions/ClientManagement.cs | 1828 ++++++++++ .../StorageAndFunctions/FileManagement.cs | 1509 ++++++++ .../StorageAndFunctions/GlobalFuncs.cs | 3068 ----------------- .../NovetusCore/StorageAndFunctions/NETExt.cs | 213 -- .../StorageAndFunctions/NovetusFuncs.cs | 852 +++++ .../StorageAndFunctions/ScriptFuncs.cs | 454 --- .../NovetusCore/StorageAndFunctions/Util.cs | 725 ++++ .../WinForms/CustomFormControls.cs | 27 - Novetus/NovetusCore/WinForms/FormExt.cs | 28 - 18 files changed, 4919 insertions(+), 4964 deletions(-) delete mode 100644 Novetus/NovetusCore/CharCustom/ContentProviders.cs delete mode 100644 Novetus/NovetusCore/CharCustom/IconLoader.cs delete mode 100644 Novetus/NovetusCore/Classes/FileFormat.cs delete mode 100644 Novetus/NovetusCore/Classes/PartColors.cs delete mode 100644 Novetus/NovetusCore/Classes/ROBLOXHelpers.cs delete mode 100644 Novetus/NovetusCore/Classes/RobloxXML.cs delete mode 100644 Novetus/NovetusCore/Classes/Settings.cs rename Novetus/NovetusCore/{Imported => Classes}/UHWIDEngine.cs (100%) create mode 100644 Novetus/NovetusCore/StorageAndFunctions/ClientManagement.cs create mode 100644 Novetus/NovetusCore/StorageAndFunctions/FileManagement.cs delete mode 100644 Novetus/NovetusCore/StorageAndFunctions/GlobalFuncs.cs delete mode 100644 Novetus/NovetusCore/StorageAndFunctions/NETExt.cs create mode 100644 Novetus/NovetusCore/StorageAndFunctions/NovetusFuncs.cs delete mode 100644 Novetus/NovetusCore/StorageAndFunctions/ScriptFuncs.cs create mode 100644 Novetus/NovetusCore/StorageAndFunctions/Util.cs delete mode 100644 Novetus/NovetusCore/WinForms/CustomFormControls.cs delete mode 100644 Novetus/NovetusCore/WinForms/FormExt.cs diff --git a/Novetus/NovetusCore/CharCustom/ContentProviders.cs b/Novetus/NovetusCore/CharCustom/ContentProviders.cs deleted file mode 100644 index 5d0488f..0000000 --- a/Novetus/NovetusCore/CharCustom/ContentProviders.cs +++ /dev/null @@ -1,69 +0,0 @@ -#region Usings -using System.IO; -using System.Linq; -using System.Xml; -using System.Xml.Serialization; -#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 diff --git a/Novetus/NovetusCore/CharCustom/IconLoader.cs b/Novetus/NovetusCore/CharCustom/IconLoader.cs deleted file mode 100644 index 3192951..0000000 --- a/Novetus/NovetusCore/CharCustom/IconLoader.cs +++ /dev/null @@ -1,66 +0,0 @@ -#region Usings -using System; -using System.IO; -using System.Windows.Forms; -#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 - { - GlobalFuncs.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 || CMD - GlobalFuncs.LogExceptions(ex); -#endif - } - } - } -} -#endregion \ No newline at end of file diff --git a/Novetus/NovetusCore/Classes/FileFormat.cs b/Novetus/NovetusCore/Classes/FileFormat.cs deleted file mode 100644 index afaf589..0000000 --- a/Novetus/NovetusCore/Classes/FileFormat.cs +++ /dev/null @@ -1,199 +0,0 @@ -#region File Formats - -using System.Diagnostics; - -public class FileFormat -{ - #region Client Information - public class ClientInfo - { - 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 - - #region Configuration - public class Config - { - 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; - } - - 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; } - } - #endregion - - #region Customization Configuration - public class CustomizationConfig - { - 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 - - #region Program Information - public class ProgramInfo - { - public ProgramInfo() - { - Version = ""; - Branch = ""; - DefaultClient = ""; - RegisterClient1 = ""; - RegisterClient2 = ""; - DefaultMap = ""; - IsLite = false; - 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 bool IsLite { get; set; } - public bool InitialBootup { get; set; } - } - #endregion -} -#endregion diff --git a/Novetus/NovetusCore/Classes/PartColors.cs b/Novetus/NovetusCore/Classes/PartColors.cs deleted file mode 100644 index 696dd38..0000000 --- a/Novetus/NovetusCore/Classes/PartColors.cs +++ /dev/null @@ -1,185 +0,0 @@ -#region Usings -using System; -using System.Drawing; -using System.Drawing.Imaging; -using System.IO; -using System.Linq; -using System.Text.RegularExpressions; -using System.Windows.Forms; -using System.Xml.Serialization; -#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() - { - if (File.Exists(GlobalPaths.ConfigDir + "\\" + GlobalPaths.PartColorXMLName)) - { - XmlSerializer serializer = new XmlSerializer(typeof(PartColors)); - PartColors colors; - - using (FileStream fs = new FileStream(GlobalPaths.ConfigDir + "\\" + GlobalPaths.PartColorXMLName, FileMode.Open)) - { - colors = (PartColors)serializer.Deserialize(fs); - } - - 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("]"))) - { - item.ColorRawName = item.ColorName; - item.ColorName = "[Uncategorized]" + item.ColorName; - } - else - { - item.ColorRawName = item.ColorName; - } - - 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) - { - 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) - { - GlobalFuncs.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) - { - GlobalFuncs.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 diff --git a/Novetus/NovetusCore/Classes/ROBLOXHelpers.cs b/Novetus/NovetusCore/Classes/ROBLOXHelpers.cs deleted file mode 100644 index abb2872..0000000 --- a/Novetus/NovetusCore/Classes/ROBLOXHelpers.cs +++ /dev/null @@ -1,332 +0,0 @@ -#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 -{ - public static AssetCacheDef Fonts - { - get - { - return new AssetCacheDef("SpecialMesh", - new string[] { "MeshId", "TextureId" }, - new string[] { ".mesh", ".png" }, - new string[] { GlobalPaths.AssetCacheDirFonts, GlobalPaths.AssetCacheDirTextures }, - new string[] { GlobalPaths.AssetCacheFontsGameDir, GlobalPaths.AssetCacheTexturesGameDir }); - } - } - - public static AssetCacheDef Sky - { - get - { - return new AssetCacheDef("Sky", - new string[] { "SkyboxBk", "SkyboxDn", "SkyboxFt", "SkyboxLf", "SkyboxRt", "SkyboxUp" }, - new string[] { ".png" }, - new string[] { GlobalPaths.AssetCacheDirSky }, - new string[] { GlobalPaths.AssetCacheSkyGameDir }); - } - } - - public static AssetCacheDef Decal - { - get - { - return new AssetCacheDef("Decal", - new string[] { "Texture" }, - new string[] { ".png" }, - new string[] { GlobalPaths.AssetCacheDirTextures }, - new string[] { GlobalPaths.AssetCacheTexturesGameDir }); - } - } - - public static AssetCacheDef Texture - { - get - { - return new AssetCacheDef("Texture", - new string[] { "Texture" }, - new string[] { ".png" }, - new string[] { GlobalPaths.AssetCacheDirTextures }, - new string[] { GlobalPaths.AssetCacheTexturesGameDir }); - } - } - - public static AssetCacheDef HopperBin - { - get - { - return new AssetCacheDef("HopperBin", - new string[] { "TextureId" }, - new string[] { ".png" }, - new string[] { GlobalPaths.AssetCacheDirTextures }, - new string[] { GlobalPaths.AssetCacheTexturesGameDir }); - } - } - - public static AssetCacheDef Tool - { - get - { - return new AssetCacheDef("Tool", - new string[] { "TextureId" }, - new string[] { ".png" }, - new string[] { GlobalPaths.AssetCacheDirTextures }, - new string[] { GlobalPaths.AssetCacheTexturesGameDir }); - } - } - - public static AssetCacheDef Sound - { - get - { - return new AssetCacheDef("Sound", - new string[] { "SoundId" }, - new string[] { ".wav" }, - new string[] { GlobalPaths.AssetCacheDirSounds }, - new string[] { GlobalPaths.AssetCacheSoundsGameDir }); - } - } - - public static AssetCacheDef ImageLabel - { - get - { - return new AssetCacheDef("ImageLabel", - new string[] { "Image" }, - new string[] { ".png" }, - new string[] { GlobalPaths.AssetCacheDirTextures }, - new string[] { GlobalPaths.AssetCacheTexturesGameDir }); - } - } - - public static AssetCacheDef Shirt - { - get - { - return new AssetCacheDef("Shirt", - new string[] { "ShirtTemplate" }, - new string[] { ".png" }, - new string[] { GlobalPaths.AssetCacheDirTextures }, - new string[] { GlobalPaths.AssetCacheTexturesGameDir }); - } - } - - public static AssetCacheDef ShirtGraphic - { - get - { - return new AssetCacheDef("ShirtGraphic", - new string[] { "Graphic" }, - new string[] { ".png" }, - new string[] { GlobalPaths.AssetCacheDirTextures }, - new string[] { GlobalPaths.AssetCacheTexturesGameDir }); - } - } - - public static AssetCacheDef Pants - { - get - { - return new AssetCacheDef("Pants", - new string[] { "PantsTemplate" }, - new string[] { ".png" }, - new string[] { GlobalPaths.AssetCacheDirTextures }, - new string[] { GlobalPaths.AssetCacheTexturesGameDir }); - } - } - - public static AssetCacheDef Script - { - get - { - return new AssetCacheDef("Script", - new string[] { "LinkedSource" }, - new string[] { ".lua" }, - new string[] { GlobalPaths.AssetCacheDirScripts }, - new string[] { GlobalPaths.AssetCacheScriptsGameDir }); - } - } - - public static AssetCacheDef LocalScript - { - get - { - return new AssetCacheDef("LocalScript", - new string[] { "LinkedSource" }, - new string[] { ".lua" }, - new string[] { GlobalPaths.AssetCacheDirScripts }, - new string[] { GlobalPaths.AssetCacheScriptsGameDir }); - } - } - - //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 diff --git a/Novetus/NovetusCore/Classes/RobloxXML.cs b/Novetus/NovetusCore/Classes/RobloxXML.cs deleted file mode 100644 index 6b9183c..0000000 --- a/Novetus/NovetusCore/Classes/RobloxXML.cs +++ /dev/null @@ -1,217 +0,0 @@ -#region Usings -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; -using System.Windows.Forms; -using System.Xml; -using System.Xml.Linq; -#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) - { - 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 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 void DownloadFilesFromNode(string url, string path, string fileext, string id) - { - if (!string.IsNullOrWhiteSpace(id)) - { - Downloader download = new Downloader(url, id); - download.InitDownload(path, fileext, "", true, false); - if (download.getDownloadOutcome().Contains("Error")) - { - throw new IOException(download.getDownloadOutcome()); - } - } - } - - 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 = GlobalFuncs.FixURLString(oldurl, url); - string peram = "id="; - - if (urlFixed.Contains(peram)) - { - return urlFixed; - } - } - } - else - { - string oldurl = item3.Value; - string rbxassetid = "rbxassetid://"; - string urlFixed = url + oldurl.After(rbxassetid); - string peram = "id="; - - if (urlFixed.Contains(peram)) - { - return urlFixed; - } - } - } - } - } - - return ""; - } - - 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); - } -} -#endregion diff --git a/Novetus/NovetusCore/Classes/Settings.cs b/Novetus/NovetusCore/Classes/Settings.cs deleted file mode 100644 index ab22401..0000000 --- a/Novetus/NovetusCore/Classes/Settings.cs +++ /dev/null @@ -1,91 +0,0 @@ -#region Usings -using System; -using System.Diagnostics; -using System.IO; -#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 \ No newline at end of file diff --git a/Novetus/NovetusCore/Imported/UHWIDEngine.cs b/Novetus/NovetusCore/Classes/UHWIDEngine.cs similarity index 100% rename from Novetus/NovetusCore/Imported/UHWIDEngine.cs rename to Novetus/NovetusCore/Classes/UHWIDEngine.cs diff --git a/Novetus/NovetusCore/NovetusCore.projitems b/Novetus/NovetusCore/NovetusCore.projitems index 832a81d..ae91e91 100644 --- a/Novetus/NovetusCore/NovetusCore.projitems +++ b/Novetus/NovetusCore/NovetusCore.projitems @@ -9,30 +9,20 @@ NovetusCore + - - - - + - - - - - + + - + - - - - Component - \ No newline at end of file diff --git a/Novetus/NovetusCore/StorageAndFunctions/ClientManagement.cs b/Novetus/NovetusCore/StorageAndFunctions/ClientManagement.cs new file mode 100644 index 0000000..885e233 --- /dev/null +++ b/Novetus/NovetusCore/StorageAndFunctions/ClientManagement.cs @@ -0,0 +1,1828 @@ +#region Usings +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Windows.Forms; +using System.Xml.Linq; +using System.Security.Cryptography; +#endregion + +#region Client Management +public class ClientManagement +{ +#if LAUNCHER + public static void ReadClientValues(RichTextBox box, bool initial = false) +#else + public static void ReadClientValues(bool initial = false) +#endif + { +#if LAUNCHER + ReadClientValues(GlobalVars.UserConfiguration.SelectedClient, box, initial); +#else + ReadClientValues(GlobalVars.UserConfiguration.SelectedClient, initial); +#endif + } + +#if LAUNCHER + public static void ReadClientValues(string ClientName, RichTextBox box, bool initial = false) +#else + public static void ReadClientValues(string ClientName, bool initial = false) +#endif + { + string name = ClientName; + if (string.IsNullOrWhiteSpace(name)) + { + if (!string.IsNullOrWhiteSpace(GlobalVars.ProgramInformation.DefaultClient)) + { + name = GlobalVars.ProgramInformation.DefaultClient; + } + else + { + return; + } + } + + string clientpath = GlobalPaths.ClientDir + @"\\" + name + @"\\clientinfo.nov"; + + if (!File.Exists(clientpath)) + { + try + { +#if LAUNCHER + 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, box); +#elif CMD + 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); +#endif + GenerateDefaultClientInfo(Path.GetDirectoryName(clientpath)); + +#if LAUNCHER + ReadClientValues(name, box, initial); +#else + ReadClientValues(name, initial); +#endif + } +#if URI || LAUNCHER || CMD || BASICLAUNCHER + catch (Exception ex) + { + Util.LogExceptions(ex); +#else + catch (Exception) + { +#endif + +#if LAUNCHER + ConsolePrint("ERROR - Failed to generate default clientinfo.nov. Info: " + ex.Message, 2, box); + ConsolePrint("Loading default client '" + GlobalVars.ProgramInformation.DefaultClient + "'", 4, box); +#elif CMD + ConsolePrint("ERROR - Failed to generate default clientinfo.nov. Info: " + ex.Message, 2); + ConsolePrint("Loading default client '" + GlobalVars.ProgramInformation.DefaultClient + "'", 4); +#endif + name = GlobalVars.ProgramInformation.DefaultClient; +#if LAUNCHER + ReadClientValues(name, box, initial); +#else + ReadClientValues(name, initial); +#endif + } + } + else + { + LoadClientValues(clientpath); + + if (initial) + { +#if LAUNCHER + ConsolePrint("Client '" + name + "' successfully loaded.", 3, box); +#elif CMD + ConsolePrint("Client '" + name + "' successfully loaded.", 3); +#endif + } + } + + 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); + } + + //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", + "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; + + StringBuilder result = new StringBuilder(); + + for (int p = 0; p < numParagraphs; p++) + { + result.Append("lorem ipsum "); + for (int s = 0; s < numSentences; s++) + { + for (int w = 0; w < numWords; w++) + { + if (w > 0) { result.Append(" "); } + result.Append(words[rand.Next(words.Length)]); + } + result.Append(". "); + } + } + + 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")) + { + 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 ClientMD5 = File.Exists(path + ClientName) ? SecurityFuncs.GenerateMD5(path + ClientName) : ""; + + 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 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()), + SecurityFuncs.Base64Encode(DefaultClientInfo.LegacyMode.ToString()), + SecurityFuncs.Base64Encode(DefaultClientInfo.ClientMD5.ToString()), + SecurityFuncs.Base64Encode(DefaultClientInfo.ScriptMD5.ToString()), + SecurityFuncs.Base64Encode(DefaultClientInfo.Description.ToString()), + SecurityFuncs.Base64Encode(placeholder.ToString()), + SecurityFuncs.Base64Encode(DefaultClientInfo.Fix2007.ToString()), + SecurityFuncs.Base64Encode(DefaultClientInfo.AlreadyHasSecurity.ToString()), + SecurityFuncs.Base64Encode(((int)DefaultClientInfo.ClientLoadOptions).ToString()), + SecurityFuncs.Base64Encode(DefaultClientInfo.SeperateFolders.ToString()), + SecurityFuncs.Base64Encode(DefaultClientInfo.UsesCustomClientEXEName.ToString()), + SecurityFuncs.Base64Encode(DefaultClientInfo.CustomClientEXEName.ToString().Replace("\\", "")), + 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; + } +#if URI || LAUNCHER || CMD || 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(); + } + + 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)) + { + folders = SecurityFuncs.Base64Decode(result[11]); + commandlineargs = SecurityFuncs.Base64Decode(result[12]); + bool parsedValue2; + if (bool.TryParse(commandlineargs, out parsedValue2)) + { + 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) + { + + 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 || CMD || 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 + { + 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, MeshDetail, ShadingQuality, MaterialQuality, + AA, AASamples, Bevels, Shadows_2008, Shadows_2007, Style_2007, GFXQualityLevel, WindowResolution, FullscreenResolution, ModernResolution); + } +#if URI || LAUNCHER || CMD || 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 || CMD || BASICLAUNCHER + catch (Exception ex) + { + Util.LogExceptions(ex); +#else + catch (Exception) + { +#endif + return; + } + + try + { + if (GraphicsMode != 0) + { + RobloxXML.EditRenderSettings(doc, "graphicsMode", GraphicsMode.ToString(), XMLTypes.Token); + } + + 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 || CMD || 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 || CMD || BASICLAUNCHER + 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"; + } + } + else + { + 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 = GetGenLuaFileName(ClientName, type); + } + + 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) + { + 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) + { + label.Text = status; + } + } +#endif + +#if URI + public static void LaunchRBXClient(ScriptType type, bool no3d, bool nomap, EventHandler e, Label label) +#elif LAUNCHER + public static void LaunchRBXClient(ScriptType type, bool no3d, bool nomap, EventHandler e, RichTextBox box) +#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); +#elif LAUNCHER + LaunchRBXClient(GlobalVars.UserConfiguration.SelectedClient, type, no3d, nomap, e, box); +#else + LaunchRBXClient(GlobalVars.UserConfiguration.SelectedClient, type, no3d, nomap, e); +#endif + } + +#if URI + public static void LaunchRBXClient(string ClientName, ScriptType type, bool no3d, bool nomap, EventHandler e, Label label) +#elif LAUNCHER + public static void LaunchRBXClient(string ClientName, ScriptType type, bool no3d, bool nomap, EventHandler e, RichTextBox box) +#else + public static void LaunchRBXClient(string ClientName, ScriptType type, bool no3d, bool nomap, EventHandler e) +#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) + { +#if LAUNCHER + if (box != null) + { + ConsolePrint("ERROR - Failed to launch Novetus. (A server is already running.)", 2, box); + } +#elif CMD + ConsolePrint("ERROR - Failed to launch Novetus. (A server is already running.)", 2); +#endif + +#if LAUNCHER + 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) + { +#pragma warning disable CS0219 // Variable is assigned but its value is never used + 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" + + "Roblox does NOT use TCP, only UDP. However, if your server doesn't work with just UDP, feel free to set up TCP too as that might help the issue in some cases."; +#pragma warning restore CS0219 // Variable is assigned but its value is never used +#if LAUNCHER + MessageBox.Show(hostingTips, "Novetus - Hosting Tips", MessageBoxButtons.OK, MessageBoxIcon.Information); +#elif CMD + ConsolePrint(hostingTips + "\nPress any key to continue...", 4); + Console.ReadKey(); +#endif + GlobalVars.UserConfiguration.FirstServerLaunch = false; + } + else + { + goto default; + } + break; + case ScriptType.Solo: + FileManagement.ReloadLoadoutValue(true); + goto default; + default: + if (GlobalVars.GameOpened != ScriptType.None) + { +#if LAUNCHER + if (box != null) + { + ConsolePrint("ERROR - Failed to launch Novetus. (A game is already running.)", 2, box); + } +#elif CMD + ConsolePrint("ERROR - Failed to launch Novetus. (A game is already running.)", 2); +#endif + +#if LAUNCHER + MessageBox.Show("Failed to launch Novetus. (Error: A game is already running.)", "Novetus - Error", MessageBoxButtons.OK, MessageBoxIcon.Error); +#endif + return; + } + break; + } + +#if LAUNCHER + ReadClientValues(ClientName, box); +#else + ReadClientValues(ClientName); +#endif + + 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; + + if (!GlobalVars.AdminMode && !info.AlreadyHasSecurity) + { + string validstart = ""; + string validend = ""; + + foreach (string line in info.CommandLineArgs.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)) + { + if (line.Contains(validstart) && line.Contains(validend)) + { + string extractedFile = ScriptFuncs.ClientScript.GetArgsFromTag(line, validstart, validend); + if (!string.IsNullOrWhiteSpace(extractedFile)) + { + try + { + 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."); +#elif LAUNCHER + if (box != null) + { + ConsolePrint("ERROR - Failed to launch Novetus. (The client has been detected as modified.)", 2, box); + } +#elif CMD + ConsolePrint("ERROR - Failed to launch Novetus. (The client has been detected as modified.)", 2); +#endif + +#if LAUNCHER + MessageBox.Show("Failed to launch Novetus. (Error: The client has been detected as modified.)", "Novetus - Error", MessageBoxButtons.OK, MessageBoxIcon.Error); +#endif + +#if URI + throw new IOException("The client has been detected as modified."); +#else + return; +#endif + } + else + { + GlobalVars.ValidatedExtraFiles += 1; + } + } +#if URI || LAUNCHER || CMD || BASICLAUNCHER + catch (Exception ex) + { + Util.LogExceptions(ex); +#else + catch (Exception) + { +#endif + continue; + } + } + } + } + } + + if (info.CommandLineArgs.Contains("%args%")) + { + 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 + { + args = ScriptFuncs.ClientScript.CompileScript(ClientName, info.CommandLineArgs, + ScriptFuncs.ClientScript.GetTagFromType(type, false, no3d), + ScriptFuncs.ClientScript.GetTagFromType(type, true, no3d), + mapfile, + luafile, + rbxexe); + } + + if (args == "") + return; + + try + { +#if LAUNCHER + ConsolePrint("Client Loaded.", 4, box); +#elif CMD + ConsolePrint("Client Loaded.", 4); +#elif URI +#endif + + if (type.Equals(ScriptType.Client)) + { + if (!GlobalVars.AdminMode) + { + 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."); +#elif LAUNCHER + if (box != null) + { + ConsolePrint("ERROR - Failed to launch Novetus. (The client has been detected as modified.)", 2, box); + } +#elif CMD + ConsolePrint("ERROR - Failed to launch Novetus. (The client has been detected as modified.)", 2); +#endif + +#if LAUNCHER + MessageBox.Show("Failed to launch Novetus. (Error: The client has been detected as modified.)", "Novetus - Error", MessageBoxButtons.OK, MessageBoxIcon.Error); +#endif + +#if URI + throw new IOException("The client has been detected as modified."); +#else + return; +#endif + } + } + else + { + OpenClient(type, rbxexe, args, ClientName, mapname, e); + } + } + else + { + 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) + { + goto default; + } + break; + case ScriptType.Studio: + break; + case ScriptType.Server: +#if LAUNCHER + PingMasterServer(true, "Server will now display on the defined master server.", box); +#elif CMD + PingMasterServer(true, "Server will now display on the defined master server."); +#endif + goto default; + default: + GlobalVars.GameOpened = type; + break; + } + + GlobalVars.ValidatedExtraFiles = 0; + } +#if URI || LAUNCHER || CMD || BASICLAUNCHER + catch (Exception ex) +#else + catch (Exception) +#endif + { +#if URI + UpdateStatus(label, "Error: " + ex.Message); +#elif LAUNCHER + if (box != null) + { + ConsolePrint("ERROR - Failed to launch Novetus. (Error: " + ex.Message + ")", 2, box); + } +#elif CMD + ConsolePrint("ERROR - Failed to launch Novetus. (Error: " + ex.Message + ")", 2); +#endif + +#if URI || LAUNCHER + MessageBox.Show("Failed to launch Novetus. (Error: " + ex.Message + ")", "Novetus - Error", MessageBoxButtons.OK, MessageBoxIcon.Error); +#endif +#if URI || LAUNCHER || CMD || BASICLAUNCHER + Util.LogExceptions(ex); +#endif + +#if URI + //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); + } + } + +#if CMD + GlobalVars.ProcessID = client.Id; + 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) + { + string privateKeyPath = Path.GetDirectoryName(scriptFileName) + "//privatekey.txt"; + + if (File.Exists(privateKeyPath)) + { + //init vars + string format = (newSigFormat ? "--rbxsig" : "") + "%{0}%{1}"; + byte[] blob = Encoding.Default.GetBytes(File.ReadAllText(privateKeyPath)); + + 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); + } + } + + public static string GetScriptFuncForType(ScriptType type) + { + return GetScriptFuncForType(GlobalVars.UserConfiguration.SelectedClient, type); + } + + public static string GetScriptFuncForType(string ClientName, ScriptType type) + { + 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") : ""; +#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 + "'"; + + switch (type) + { + case ScriptType.Client: + return "_G.CSConnect(" + + (info.UsesID ? GlobalVars.UserConfiguration.UserID : 0) + ",'" + + GlobalVars.IP + "'," + + GlobalVars.JoinPort + ",'" + + (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) + { + 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(string ClientName, ScriptType type) + { + bool shouldUseLoadFile = GlobalVars.SelectedClientInfo.CommandLineArgs.Contains("%useloadfile%"); + string execScriptMethod = shouldUseLoadFile ? "loadfile" : "dofile"; + + string[] code = { + "--Load Script", + //scriptcontents, + (GlobalVars.SelectedClientInfo.SeperateFolders ? "" + + execScriptMethod + "('rbxasset://../../content/scripts/" + GlobalPaths.ScriptName + ".lua')" + (shouldUseLoadFile ? "()" : "") : + execScriptMethod + "('rbxasset://scripts/" + GlobalPaths.ScriptName + ".lua')" + (shouldUseLoadFile ? "()" : "")), + GetScriptFuncForType(type), + }; + + if (GlobalVars.SelectedClientInfo.SeperateFolders) + { + 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); + } + } + + public static string GetGeneratedScriptName(string ClientName, ScriptType type) + { + 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 + { + int pFrom = code.IndexOf(tag) + tag.Length; + int pTo = code.LastIndexOf(endtag); + string result = code.Substring(pFrom, pTo - pFrom); + return result; + } +#if URI || LAUNCHER || CMD || BASICLAUNCHER + catch (Exception ex) + { + Util.LogExceptions(ex); +#else + catch (Exception) + { +#endif + return "%donothing%"; + } + } + + 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) + { + 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 ""; + } + } + + 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 || CMD || 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; + + FileFormat.ClientInfo info = ClientManagement.GetClientInfoValues(ClientName); + + ScriptType type = GetTypeFromTag(start); + + //we must have the ending tag before we continue. + if (string.IsNullOrWhiteSpace(end)) + { + return ""; + } + + if (usesharedtags) + { + string sharedstart = ""; + string sharedend = ""; + + if (code.Contains(sharedstart) && code.Contains(sharedend)) + { + start = sharedstart; + end = sharedend; + } + } + + if (info.Fix2007) + { + Generator.GenerateScriptForClient(type); + } + + string extractedCode = GetArgsFromTag(code, start, end); + + if (extractedCode.Contains("%donothing%")) + { + return ""; + } + +#if LAUNCHER + string md5dir = !info.AlreadyHasSecurity ? SecurityFuncs.GenerateMD5(Assembly.GetExecutingAssembly().Location) : ""; +#else + 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("%ip%", GlobalVars.IP) + .Replace("%port%", GlobalVars.UserConfiguration.RobloxPort.ToString()) + .Replace("%joinport%", GlobalVars.JoinPort.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("%doublequote%", "\"") + .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()); + + if (compiled.Contains("%disabled%")) + { + MessageBox.Show("This option has been disabled for this client.", "Novetus - Error", MessageBoxButtons.OK, MessageBoxIcon.Error); + return ""; + } + + return compiled; + } + } + #endregion +} +#endregion diff --git a/Novetus/NovetusCore/StorageAndFunctions/FileManagement.cs b/Novetus/NovetusCore/StorageAndFunctions/FileManagement.cs new file mode 100644 index 0000000..2400a97 --- /dev/null +++ b/Novetus/NovetusCore/StorageAndFunctions/FileManagement.cs @@ -0,0 +1,1509 @@ +#region Usings +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Threading; +using System.Drawing; +using System.Drawing.Imaging; +using System.Text.RegularExpressions; +using System.Windows.Forms; +using System.Xml.Serialization; +#endregion + +#region File Formats +public class FileFormat +{ + #region Client Information + public class ClientInfo + { + 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 + + #region Configuration + public class Config + { + 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; + } + + 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; } + } + #endregion + + #region Customization Configuration + public class CustomizationConfig + { + 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 + + #region Program Information + public class ProgramInfo + { + public ProgramInfo() + { + Version = ""; + Branch = ""; + DefaultClient = ""; + RegisterClient1 = ""; + RegisterClient2 = ""; + DefaultMap = ""; + IsLite = false; + 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 bool IsLite { get; set; } + public bool InitialBootup { get; set; } + } + #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() + { + if (File.Exists(GlobalPaths.ConfigDir + "\\" + GlobalPaths.PartColorXMLName)) + { + XmlSerializer serializer = new XmlSerializer(typeof(PartColors)); + PartColors colors; + + using (FileStream fs = new FileStream(GlobalPaths.ConfigDir + "\\" + GlobalPaths.PartColorXMLName, FileMode.Open)) + { + colors = (PartColors)serializer.Deserialize(fs); + } + + 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("]"))) + { + item.ColorRawName = item.ColorName; + item.ColorName = "[Uncategorized]" + item.ColorName; + } + else + { + item.ColorRawName = item.ColorName; + } + + 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) + { + 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 || CMD + 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"); + + GlobalVars.ProgramInformation.IsLite = Convert.ToBoolean(isLite); + + try + { + GlobalVars.ExtendedVersionNumber = Convert.ToBoolean(extendedversionnumber); + if (GlobalVars.ExtendedVersionNumber) + { + if (other) + { + if (!string.IsNullOrWhiteSpace(exepath)) + { + 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 : "")) + .Replace("%lite%", (GlobalVars.ProgramInformation.IsLite ? " (Lite)" : "")); + } + 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 : "")) + .Replace("%lite%", (GlobalVars.ProgramInformation.IsLite ? " (Lite)" : "")); + } + + 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; + } + + 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 || CMD || BASICLAUNCHER + catch (Exception ex) + { + Util.LogExceptions(ex); +#else + catch (Exception) + { +#endif + 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) + { + 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 (GlobalVars.ProgramInformation.InitialBootup) + { + if (ini.IniValueExists(oldKey)) + { + ini.IniWriteValue(section, oldKey, val); + } + else + { + ini.IniWriteValue(section, newKey, val); + } + } + else + { + ini.IniWriteValue(section, oldKey, val); + } + } + else + { + ini.IniWriteValue(section, newKey, val); + } + + return ""; + } + else + { + if (ini.IniValueExists(newKey)) + { + return ini.IniReadValue(section, newKey, val); + } + else + { + return ini.IniReadValue(section, oldKey, val); + } + } + } + + private static int ValueInt(string val, int defaultVal) + { + int res; + if (int.TryParse(val, out res)) + { + 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()) + { + GlobalVars.UserConfiguration.LauncherStyle = Settings.Style.Extended; + } + + //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()); + ConfigUseOldValIfExists(ini, section, "ItemMakerDisableHelpMessage", "AssetSDKDisableHelpMessage", GlobalVars.UserConfiguration.DisabledAssetSDKHelp.ToString(), write); + ConfigUseOldValIfExists(ini, section, "AssetLocalizerSaveBackups", "AssetSDKFixerSaveBackups", GlobalVars.UserConfiguration.AssetSDKFixerSaveBackups.ToString(), write); + + if (forcewrite) + { + // try again.... + Config(cfgpath, false, doubleCheck); + } + } + 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; + + 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()); + 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")) + { + 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); + + 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 || CMD || 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 || CMD || 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); + } + } + } + } + + 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)) + { + 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 || CMD || BASICLAUNCHER + catch (Exception ex) + { + Util.LogExceptions(ex); +#else + catch (Exception) + { +#endif + ReShadeValues(cfgpath, true, setglobals); + } + } + } + } + + public static bool InitColors() + { + try + { + if (File.Exists(GlobalPaths.ConfigDir + "\\" + GlobalPaths.PartColorXMLName)) + { + GlobalVars.PartColorList = PartColorLoader.GetPartColors(); + GlobalVars.PartColorListConv = new List(); + GlobalVars.PartColorListConv.AddRange(GlobalVars.PartColorList); + return true; + } + else + { + goto Failure; + } + } +#if URI || LAUNCHER || CMD || BASICLAUNCHER + catch (Exception ex) + { + Util.LogExceptions(ex); +#else + catch (Exception) + { +#endif + goto Failure; + } + + 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 || CMD || 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() +#endif + { + 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 + 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"); + } + } + + public static void CreateAssetCacheDirectories() + { + if (!Directory.Exists(GlobalPaths.AssetCacheDirFonts)) + { + Directory.CreateDirectory(GlobalPaths.AssetCacheDirFonts); + } + + if (!Directory.Exists(GlobalPaths.AssetCacheDirSky)) + { + Directory.CreateDirectory(GlobalPaths.AssetCacheDirSky); + } + + if (!Directory.Exists(GlobalPaths.AssetCacheDirSounds)) + { + Directory.CreateDirectory(GlobalPaths.AssetCacheDirSounds); + } + + if (!Directory.Exists(GlobalPaths.AssetCacheDirTextures)) + { + Directory.CreateDirectory(GlobalPaths.AssetCacheDirTextures); + } + + if (!Directory.Exists(GlobalPaths.AssetCacheDirTexturesGUI)) + { + Directory.CreateDirectory(GlobalPaths.AssetCacheDirTexturesGUI); + } + + if (!Directory.Exists(GlobalPaths.AssetCacheDirScripts)) + { + Directory.CreateDirectory(GlobalPaths.AssetCacheDirScripts); + } + + if (!Directory.Exists(GlobalPaths.AssetCacheDirAssets)) + { + Directory.CreateDirectory(GlobalPaths.AssetCacheDirAssets); + } + } + + public static void CreateInitialFileListIfNeededMulti() + { + if (GlobalVars.NoFileList) + return; + + string filePath = GlobalPaths.ConfigDir + "\\InitialFileList.txt"; + + if (!File.Exists(filePath)) + { + Thread t = new Thread(CreateInitialFileList); + t.Start(); + } + else + { + 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) + { + 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; + } + } + + //MessageBox.Show(lineCount + "\n" + fileCount); + + if (lineCount != fileCount) + { + Thread t = new Thread(CreateInitialFileList); + t.Start(); + } + } + } + + private static void CreateInitialFileList() + { + string filterPath = GlobalPaths.ConfigDir + @"\\" + GlobalPaths.InitialFileListIgnoreFilterName; + string[] fileListToIgnore = File.ReadAllLines(filterPath); + string FileName = GlobalPaths.ConfigDir + "\\InitialFileList.txt"; + + 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; + } + } + } + } +} +#endregion \ No newline at end of file diff --git a/Novetus/NovetusCore/StorageAndFunctions/GlobalFuncs.cs b/Novetus/NovetusCore/StorageAndFunctions/GlobalFuncs.cs deleted file mode 100644 index 7a3f490..0000000 --- a/Novetus/NovetusCore/StorageAndFunctions/GlobalFuncs.cs +++ /dev/null @@ -1,3068 +0,0 @@ -#region Usings -#if LAUNCHER || CMD || URI || BASICLAUNCHER -using NLog; -#endif -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Drawing; -using System.Drawing.Imaging; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Management; -using System.Net; -using System.Reflection; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading; -using System.Threading.Tasks; -using System.Windows.Forms; -using System.Xml; -using System.Xml.Linq; -#endregion - -#region Global Functions -public class GlobalFuncs -{ - 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"); - - GlobalVars.ProgramInformation.IsLite = Convert.ToBoolean(isLite); - - try - { - GlobalVars.ExtendedVersionNumber = Convert.ToBoolean(extendedversionnumber); - if (GlobalVars.ExtendedVersionNumber) - { - if (other) - { - if (!string.IsNullOrWhiteSpace(exepath)) - { - 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 : "")) - .Replace("%lite%", (GlobalVars.ProgramInformation.IsLite ? " (Lite)" : "")); - } - 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 : "")) - .Replace("%lite%", (GlobalVars.ProgramInformation.IsLite ? " (Lite)" : "")); - } - - 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; - } - - 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 || CMD || BASICLAUNCHER - catch (Exception ex) - { - LogExceptions(ex); -#else - catch (Exception) - { -#endif - 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) - { - 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 (GlobalVars.ProgramInformation.InitialBootup) - { - if (ini.IniValueExists(oldKey)) - { - ini.IniWriteValue(section, oldKey, val); - } - else - { - ini.IniWriteValue(section, newKey, val); - } - } - else - { - ini.IniWriteValue(section, oldKey, val); - } - } - else - { - ini.IniWriteValue(section, newKey, val); - } - - return ""; - } - else - { - if (ini.IniValueExists(newKey)) - { - return ini.IniReadValue(section, newKey, val); - } - else - { - return ini.IniReadValue(section, oldKey, val); - } - } - } - - private static int ValueInt(string val, int defaultVal) - { - int res; - if (int.TryParse(val, out res)) - { - 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 (IsWineRunning()) - { - GlobalVars.UserConfiguration.LauncherStyle = Settings.Style.Extended; - } - - //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()); - ConfigUseOldValIfExists(ini, section, "ItemMakerDisableHelpMessage", "AssetSDKDisableHelpMessage", GlobalVars.UserConfiguration.DisabledAssetSDKHelp.ToString(), write); - ConfigUseOldValIfExists(ini, section, "AssetLocalizerSaveBackups", "AssetSDKFixerSaveBackups", GlobalVars.UserConfiguration.AssetSDKFixerSaveBackups.ToString(), write); - - if (forcewrite) - { - // try again.... - Config(cfgpath, false, doubleCheck); - } - } - 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; - - 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()); - 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")) - { - 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); - - 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 || CMD || BASICLAUNCHER - catch (Exception ex) - { - LogExceptions(ex); -#else - catch (Exception) - { -#endif - Config(cfgpath, true); - } - } - - if (!forcewrite) - { - string curval = 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 || CMD || BASICLAUNCHER - catch (Exception ex) - { - 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)) - { - 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)) - { - FixedFileCopy(fullpath, fulldirpath, false); - ReShadeValues(fulldirpath, write, false); - } - else - { - ReShadeValues(fulldirpath, write, false); - } - - if (!File.Exists(fulldllpath)) - { - FixedFileCopy(GlobalPaths.DataDir + "\\" + dllfilename, fulldllpath, false); - } - } - else - { - FixedFileDelete(fulldirpath); - - if (!GlobalVars.UserConfiguration.DisableReshadeDelete) - { - 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)) - { - 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 || CMD || BASICLAUNCHER - catch (Exception ex) - { - LogExceptions(ex); -#else - catch (Exception) - { -#endif - ReShadeValues(cfgpath, true, setglobals); - } - } - } - } - - public static bool InitColors() - { - try - { - if (File.Exists(GlobalPaths.ConfigDir + "\\" + GlobalPaths.PartColorXMLName)) - { - GlobalVars.PartColorList = PartColorLoader.GetPartColors(); - GlobalVars.PartColorListConv = new List(); - GlobalVars.PartColorListConv.AddRange(GlobalVars.PartColorList); - return true; - } - else - { - goto Failure; - } - } -#if URI || LAUNCHER || CMD || BASICLAUNCHER - catch (Exception ex) - { - LogExceptions(ex); -#else - catch (Exception) - { -#endif - goto Failure; - } - - 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 || CMD || BASICLAUNCHER - catch (Exception ex) - { - LogExceptions(ex); -#else - catch (Exception) - { -#endif - goto Failure; - } - - Failure: - return false; - } - -#if LAUNCHER - public static void ReadClientValues(RichTextBox box, bool initial = false) -#else - public static void ReadClientValues(bool initial = false) -#endif - { -#if LAUNCHER - ReadClientValues(GlobalVars.UserConfiguration.SelectedClient, box, initial); -#else - ReadClientValues(GlobalVars.UserConfiguration.SelectedClient, initial); -#endif - } - -#if LAUNCHER - public static void ReadClientValues(string ClientName, RichTextBox box, bool initial = false) -#else - public static void ReadClientValues(string ClientName, bool initial = false) -#endif - { - string name = ClientName; - if (string.IsNullOrWhiteSpace(name)) - { - if (!string.IsNullOrWhiteSpace(GlobalVars.ProgramInformation.DefaultClient)) - { - name = GlobalVars.ProgramInformation.DefaultClient; - } - else - { - return; - } - } - - string clientpath = GlobalPaths.ClientDir + @"\\" + name + @"\\clientinfo.nov"; - - if (!File.Exists(clientpath)) - { - try - { -#if LAUNCHER - 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, box); -#elif CMD - 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); -#endif - GenerateDefaultClientInfo(Path.GetDirectoryName(clientpath)); - -#if LAUNCHER - ReadClientValues(name, box, initial); -#else - ReadClientValues(name, initial); -#endif - } -#if URI || LAUNCHER || CMD || BASICLAUNCHER - catch (Exception ex) - { - LogExceptions(ex); -#else - catch (Exception) - { -#endif - -#if LAUNCHER - ConsolePrint("ERROR - Failed to generate default clientinfo.nov. Info: " + ex.Message, 2, box); - ConsolePrint("Loading default client '" + GlobalVars.ProgramInformation.DefaultClient + "'", 4, box); -#elif CMD - ConsolePrint("ERROR - Failed to generate default clientinfo.nov. Info: " + ex.Message, 2); - ConsolePrint("Loading default client '" + GlobalVars.ProgramInformation.DefaultClient + "'", 4); -#endif - name = GlobalVars.ProgramInformation.DefaultClient; -#if LAUNCHER - ReadClientValues(name, box, initial); -#else - ReadClientValues(name, initial); -#endif - } - } - else - { - LoadClientValues(clientpath); - - if (initial) - { -#if LAUNCHER - ConsolePrint("Client '" + name + "' successfully loaded.", 3, box); -#elif CMD - ConsolePrint("Client '" + name + "' successfully loaded.", 3); -#endif - } - } - - 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)) - { - FixedFileCopy(dir, fullpath, false); - } - } - } - - 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) - { - - 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; - - StringBuilder result = new StringBuilder(); - - for (int p = 0; p < numParagraphs; p++) - { - result.Append("lorem ipsum "); - for (int s = 0; s < numSentences; s++) - { - for (int w = 0; w < numWords; w++) - { - if (w > 0) { result.Append(" "); } - result.Append(words[rand.Next(words.Length)]); - } - result.Append(". "); - } - } - - 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")) - { - 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 ClientMD5 = File.Exists(path + ClientName) ? SecurityFuncs.GenerateMD5(path + ClientName) : ""; - - 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 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()), - SecurityFuncs.Base64Encode(DefaultClientInfo.LegacyMode.ToString()), - SecurityFuncs.Base64Encode(DefaultClientInfo.ClientMD5.ToString()), - SecurityFuncs.Base64Encode(DefaultClientInfo.ScriptMD5.ToString()), - SecurityFuncs.Base64Encode(DefaultClientInfo.Description.ToString()), - SecurityFuncs.Base64Encode(placeholder.ToString()), - SecurityFuncs.Base64Encode(DefaultClientInfo.Fix2007.ToString()), - SecurityFuncs.Base64Encode(DefaultClientInfo.AlreadyHasSecurity.ToString()), - SecurityFuncs.Base64Encode(((int)DefaultClientInfo.ClientLoadOptions).ToString()), - SecurityFuncs.Base64Encode(DefaultClientInfo.SeperateFolders.ToString()), - SecurityFuncs.Base64Encode(DefaultClientInfo.UsesCustomClientEXEName.ToString()), - SecurityFuncs.Base64Encode(DefaultClientInfo.CustomClientEXEName.ToString().Replace("\\", "")), - SecurityFuncs.Base64Encode(DefaultClientInfo.CommandLineArgs.ToString()) - }; - - File.WriteAllText(path + "\\clientinfo.nov", SecurityFuncs.Base64Encode(string.Join("|", lines))); - } - - 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) - { - return; - } - } - - 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 - { - 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."); - } - } - } - - 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; - } - - //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 - { - using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(fileFullName))) - { - image = Image.FromStream(ms); - } - - // 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 || CMD || BASICLAUNCHER - catch (Exception ex) - { - LogExceptions(ex); -#else - catch (Exception) - { -#endif - if (!string.IsNullOrWhiteSpace(fallbackFileFullName)) - image = LoadImage(fallbackFileFullName); - } - - return image; - } - - public static string CopyMapToRBXAsset() - { - string clientcontentpath = GlobalPaths.ClientDir + @"\\" + GlobalVars.UserConfiguration.SelectedClient + @"\\content\\temp.rbxl"; - FixedFileCopy(GlobalVars.UserConfiguration.MapPath, clientcontentpath, true); - return GlobalPaths.AltBaseGameDir + "temp.rbxl"; - } - - //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; - } -#if URI || LAUNCHER || CMD || BASICLAUNCHER - catch (Exception ex) - { - LogExceptions(ex); -#else - catch (Exception) - { -#endif - return null; - } - } - - //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(); - } - - 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(); - } - - 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)) - { - folders = SecurityFuncs.Base64Decode(result[11]); - commandlineargs = SecurityFuncs.Base64Decode(result[12]); - bool parsedValue2; - if (bool.TryParse(commandlineargs, out parsedValue2)) - { - 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; - } - -#if LAUNCHER - public static void ResetConfigValues(Settings.Style style) -#else - public static void ResetConfigValues() -#endif - { - 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 - 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 = GetItemTextureID(GlobalVars.UserCustomization.TShirt, "TShirt", new AssetCacheDefBasic("ShirtGraphic", new string[] { "Graphic" })); - GlobalVars.ShirtTextureID = GetItemTextureID(GlobalVars.UserCustomization.Shirt, "Shirt", new AssetCacheDefBasic("Shirt", new string[] { "ShirtTemplate" })); - GlobalVars.PantsTextureID = GetItemTextureID(GlobalVars.UserCustomization.Pants, "Pants", new AssetCacheDefBasic("Pants", new string[] { "PantsTemplate" })); - GlobalVars.FaceTextureID = GetItemTextureID(GlobalVars.UserCustomization.Face, "Face", new AssetCacheDefBasic("Decal", new string[] { "Texture" })); - - GlobalVars.TShirtTextureLocal = GetItemTextureLocalPath(GlobalVars.TShirtTextureID, "TShirt"); - GlobalVars.ShirtTextureLocal = GetItemTextureLocalPath(GlobalVars.ShirtTextureID, "Shirt"); - GlobalVars.PantsTextureLocal = GetItemTextureLocalPath(GlobalVars.PantsTextureID, "Pants"); - GlobalVars.FaceTextureLocal = GetItemTextureLocalPath(GlobalVars.FaceTextureID, "Face"); - } - } - - 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 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.AssetCacheDirTextures); - - try - { - string path = download.GetFullDLPath(); - download.InitDownloadNoDialog(path); - return GlobalPaths.AssetCacheTexturesGameDir + download.fileName; - } -#if URI || LAUNCHER || CMD || BASICLAUNCHER - catch (Exception ex) - { - 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.AssetCacheDirFonts); - - 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 = 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 || CMD || BASICLAUNCHER - catch (Exception ex) - { - 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 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; - 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")) - { - FixedFileCopy(dir, Settings.GetPathForClientLoadOptions(info.ClientLoadOptions) + @"\" + Path.GetFileName(dir).Replace(terms, "") - .Replace(dir.Substring(dir.LastIndexOf('-') + 1), "") - .Replace("-", ".xml"), true); - } - } - } - } -#if URI || LAUNCHER || CMD || BASICLAUNCHER - catch (Exception ex) - { - 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 - { - 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, MeshDetail, ShadingQuality, MaterialQuality, - AA, AASamples, Bevels, Shadows_2008, Shadows_2007, Style_2007, GFXQualityLevel, WindowResolution, FullscreenResolution, ModernResolution); - } -#if URI || LAUNCHER || CMD || BASICLAUNCHER - catch (Exception ex) - { - 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 || CMD || BASICLAUNCHER - catch (Exception ex) - { - LogExceptions(ex); -#else - catch (Exception) - { -#endif - return; - } - - try - { - if (GraphicsMode != 0) - { - RobloxXML.EditRenderSettings(doc, "graphicsMode", GraphicsMode.ToString(), XMLTypes.Token); - } - - 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 || CMD || BASICLAUNCHER - catch (Exception ex) - { - LogExceptions(ex); -#else - catch (Exception) - { -#endif - return; - } - finally - { - doc.Save(dir); - FixedFileCopy(dir, Settings.GetPathForClientLoadOptions(info.ClientLoadOptions) + @"\" + Path.GetFileName(dir).Replace(terms, "") - .Replace(dir.Substring(dir.LastIndexOf('-') + 1), "") - .Replace("-", ".xml"), true); - } - } - } - } -#if URI || LAUNCHER || CMD || BASICLAUNCHER - catch (Exception ex) - { - 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"; - } - } - else - { - 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 = GetGenLuaFileName(ClientName, type); - } - - 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) - { - 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) - { - LogPrint(status); - if (label != null) - { - label.Text = status; - } - } -#endif - -#if URI - public static void LaunchRBXClient(ScriptType type, bool no3d, bool nomap, EventHandler e, Label label) -#elif LAUNCHER - public static void LaunchRBXClient(ScriptType type, bool no3d, bool nomap, EventHandler e, RichTextBox box) -#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); -#elif LAUNCHER - LaunchRBXClient(GlobalVars.UserConfiguration.SelectedClient, type, no3d, nomap, e, box); -#else - LaunchRBXClient(GlobalVars.UserConfiguration.SelectedClient, type, no3d, nomap, e); -#endif - } - -#if URI - public static void LaunchRBXClient(string ClientName, ScriptType type, bool no3d, bool nomap, EventHandler e, Label label) -#elif LAUNCHER - public static void LaunchRBXClient(string ClientName, ScriptType type, bool no3d, bool nomap, EventHandler e, RichTextBox box) -#else - public static void LaunchRBXClient(string ClientName, ScriptType type, bool no3d, bool nomap, EventHandler e) -#endif - { - switch (type) - { - case ScriptType.Client: - ReloadLoadoutValue(true); - if (!GlobalVars.LocalPlayMode && GlobalVars.GameOpened != ScriptType.Server) - { - goto default; - } - break; - case ScriptType.Server: - if (GlobalVars.GameOpened == ScriptType.Server) - { -#if LAUNCHER - if (box != null) - { - ConsolePrint("ERROR - Failed to launch Novetus. (A server is already running.)", 2, box); - } -#elif CMD - ConsolePrint("ERROR - Failed to launch Novetus. (A server is already running.)", 2); -#endif - -#if LAUNCHER - 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) - { -#pragma warning disable CS0219 // Variable is assigned but its value is never used - 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" + - "Roblox does NOT use TCP, only UDP. However, if your server doesn't work with just UDP, feel free to set up TCP too as that might help the issue in some cases."; -#pragma warning restore CS0219 // Variable is assigned but its value is never used -#if LAUNCHER - MessageBox.Show(hostingTips, "Novetus - Hosting Tips", MessageBoxButtons.OK, MessageBoxIcon.Information); -#elif CMD - ConsolePrint(hostingTips + "\nPress any key to continue...", 4); - Console.ReadKey(); -#endif - GlobalVars.UserConfiguration.FirstServerLaunch = false; - } - else - { - goto default; - } - break; - case ScriptType.Solo: - ReloadLoadoutValue(true); - goto default; - default: - if (GlobalVars.GameOpened != ScriptType.None) - { -#if LAUNCHER - if (box != null) - { - ConsolePrint("ERROR - Failed to launch Novetus. (A game is already running.)", 2, box); - } -#elif CMD - ConsolePrint("ERROR - Failed to launch Novetus. (A game is already running.)", 2); -#endif - -#if LAUNCHER - MessageBox.Show("Failed to launch Novetus. (Error: A game is already running.)", "Novetus - Error", MessageBoxButtons.OK, MessageBoxIcon.Error); -#endif - return; - } - break; - } - -#if LAUNCHER - ReadClientValues(ClientName, box); -#else - ReadClientValues(ClientName); -#endif - - 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; - - if (!GlobalVars.AdminMode && !info.AlreadyHasSecurity) - { - string validstart = ""; - string validend = ""; - - foreach (string line in info.CommandLineArgs.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)) - { - if (line.Contains(validstart) && line.Contains(validend)) - { - string extractedFile = ScriptFuncs.ClientScript.GetArgsFromTag(line, validstart, validend); - if (!string.IsNullOrWhiteSpace(extractedFile)) - { - try - { - 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."); -#elif LAUNCHER - if (box != null) - { - ConsolePrint("ERROR - Failed to launch Novetus. (The client has been detected as modified.)", 2, box); - } -#elif CMD - ConsolePrint("ERROR - Failed to launch Novetus. (The client has been detected as modified.)", 2); -#endif - -#if LAUNCHER - MessageBox.Show("Failed to launch Novetus. (Error: The client has been detected as modified.)", "Novetus - Error", MessageBoxButtons.OK, MessageBoxIcon.Error); -#endif - -#if URI - throw new IOException("The client has been detected as modified."); -#else - return; -#endif - } - else - { - GlobalVars.ValidatedExtraFiles += 1; - } - } -#if URI || LAUNCHER || CMD || BASICLAUNCHER - catch (Exception ex) - { - LogExceptions(ex); -#else - catch (Exception) - { -#endif - continue; - } - } - } - } - } - - if (info.CommandLineArgs.Contains("%args%")) - { - 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 - { - args = ScriptFuncs.ClientScript.CompileScript(ClientName, info.CommandLineArgs, - ScriptFuncs.ClientScript.GetTagFromType(type, false, no3d), - ScriptFuncs.ClientScript.GetTagFromType(type, true, no3d), - mapfile, - luafile, - rbxexe); - } - - if (args == "") - return; - - try - { -#if LAUNCHER - ConsolePrint("Client Loaded.", 4, box); -#elif CMD - ConsolePrint("Client Loaded.", 4); -#elif URI -#endif - - if (type.Equals(ScriptType.Client)) - { - if (!GlobalVars.AdminMode) - { - 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."); -#elif LAUNCHER - if (box != null) - { - ConsolePrint("ERROR - Failed to launch Novetus. (The client has been detected as modified.)", 2, box); - } -#elif CMD - ConsolePrint("ERROR - Failed to launch Novetus. (The client has been detected as modified.)", 2); -#endif - -#if LAUNCHER - MessageBox.Show("Failed to launch Novetus. (Error: The client has been detected as modified.)", "Novetus - Error", MessageBoxButtons.OK, MessageBoxIcon.Error); -#endif - -#if URI - throw new IOException("The client has been detected as modified."); -#else - return; -#endif - } - } - else - { - OpenClient(type, rbxexe, args, ClientName, mapname, e); - } - } - else - { - 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) - { - goto default; - } - break; - case ScriptType.Studio: - break; - case ScriptType.Server: -#if LAUNCHER - PingMasterServer(true, "Server will now display on the defined master server.", box); -#elif CMD - PingMasterServer(true, "Server will now display on the defined master server."); -#endif - goto default; - default: - GlobalVars.GameOpened = type; - break; - } - - GlobalVars.ValidatedExtraFiles = 0; - } -#if URI || LAUNCHER || CMD || BASICLAUNCHER - catch (Exception ex) -#else - catch (Exception) -#endif - { -#if URI - UpdateStatus(label, "Error: " + ex.Message); -#elif LAUNCHER - if (box != null) - { - ConsolePrint("ERROR - Failed to launch Novetus. (Error: " + ex.Message + ")", 2, box); - } -#elif CMD - ConsolePrint("ERROR - Failed to launch Novetus. (Error: " + ex.Message + ")", 2); -#endif - -#if URI || LAUNCHER - MessageBox.Show("Failed to launch Novetus. (Error: " + ex.Message + ")", "Novetus - Error", MessageBoxButtons.OK, MessageBoxIcon.Error); -#endif -#if URI || LAUNCHER || CMD || BASICLAUNCHER - LogExceptions(ex); -#endif - -#if URI - //toss the exception back to the URI - throw new Exception(ex.Message); -#endif - } - } - -#if LAUNCHER - public static void PingMasterServer(bool online, string reason, RichTextBox box) -#else - public static void PingMasterServer(bool online, string reason) -#endif - { - 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"; - } - -#if LAUNCHER - ConsolePrint("Pinging master server. " + reason, 4, box); -#elif CMD - ConsolePrint("Pinging master server. " + reason, 4); -#endif - -#if LAUNCHER - Task.Factory.StartNew(() => TryPing(box)); -#else - Task.Factory.StartNew(() => TryPing()); -#endif - } - -#if LAUNCHER - public static void TryPing(RichTextBox box) -#else - private static void TryPing() -#endif - { - string response = HttpGet(GlobalVars.PingURL); - - if (!string.IsNullOrWhiteSpace(response)) - { -#if LAUNCHER - ConsolePrint(response, response.Contains("ERROR:") ? 2 : 4, box); -#elif CMD - ConsolePrint(response, response.Contains("ERROR:") ? 2 : 4); -#endif - - if (response.Contains("ERROR:")) - { - GlobalVars.ServerID = "N/A"; - } - } - - if (!GlobalVars.ServerID.Equals("N/A")) - { -#if LAUNCHER - ConsolePrint("Your server's ID is " + GlobalVars.ServerID, 4, box); -#elif CMD - ConsolePrint("Your server's ID is " + GlobalVars.ServerID, 4); -#endif - } - - GlobalVars.PingURL = ""; - } - - 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); - } - } - -#if CMD - GlobalVars.ProcessID = client.Id; - CreateTXT(); -#endif - } - -#if LAUNCHER - public static void ConsolePrint(string text, int type, RichTextBox box, bool noLog = false, 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); - if (!noLog) - LogPrint(text); - break; - case 2: - box.AppendText(text, Color.Red); - if (!noLog) - LogPrint(text, 2); - break; - case 3: - box.AppendText(text, Color.Lime); - if (!noLog) - LogPrint(text); - break; - case 4: - box.AppendText(text, Color.Aqua); - if (!noLog) - LogPrint(text); - break; - case 5: - box.AppendText(text, Color.Yellow); - if (!noLog) - LogPrint(text, 3); - break; - case 6: - box.AppendText(text, Color.LightSalmon); - if (!noLog) - LogPrint(text); - break; - case 0: - default: - box.AppendText(text, Color.Black); - if (!noLog) - LogPrint(text); - break; - } - - box.AppendText(Environment.NewLine, Color.White); - } -#elif CMD - public static void ConsolePrint(string text, int type, bool notime = false, bool noLog = false) - { - if (!notime) - { - ConsoleText("[" + DateTime.Now.ToShortTimeString() + "] - ", ConsoleColor.White); - } - - switch (type) - { - case 2: - ConsoleText(text, ConsoleColor.Red); - if (!noLog) - LogPrint(text, 2); - break; - case 3: - ConsoleText(text, ConsoleColor.Green); - if (!noLog) - LogPrint(text); - break; - case 4: - ConsoleText(text, ConsoleColor.Cyan); - if (!noLog) - LogPrint(text); - break; - case 5: - ConsoleText(text, ConsoleColor.Yellow); - if (!noLog) - LogPrint(text, 3); - break; - case 1: - default: - ConsoleText(text, ConsoleColor.White); - if (!noLog) - LogPrint(text); - break; - } - - ConsoleText(Environment.NewLine, ConsoleColor.White); - } - - public static void ConsoleText(string text, ConsoleColor color) - { - Console.ForegroundColor = color; - Console.Write(text); - } - - public static void CreateTXT() - { - if (GlobalVars.RequestToOutputInfo) - { - 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 = { - SecurityFuncs.Base64Encode("localhost"), - SecurityFuncs.Base64Encode(GlobalVars.UserConfiguration.RobloxPort.ToString()), - SecurityFuncs.Base64Encode(GlobalVars.UserConfiguration.SelectedClient) - }; - string URI2 = "novetus://" + SecurityFuncs.Base64Encode(string.Join("|", lines2), true); - - string[] text = { - "Process ID: " + (GlobalVars.ProcessID == 0 ? "N/A" : GlobalVars.ProcessID.ToString()), - "Don't copy the Process ID when sharing the server.", - "--------------------", - "Server Info:", - "Client: " + GlobalVars.UserConfiguration.SelectedClient, - "IP: " + (!string.IsNullOrWhiteSpace(GlobalVars.UserConfiguration.AlternateServerIP) ? GlobalVars.UserConfiguration.AlternateServerIP : GlobalVars.ExternalIP), - "Port: " + GlobalVars.UserConfiguration.RobloxPort.ToString(), - "Map: " + GlobalVars.UserConfiguration.Map, - "Players: " + GlobalVars.UserConfiguration.PlayerLimit, - "Version: Novetus " + GlobalVars.ProgramInformation.Version, - "Online URI Link:", - URI, - "Local URI Link:", - URI2 - }; - - string txt = GlobalPaths.BasePath + "\\" + GlobalVars.ServerInfoFileName; - File.WriteAllLines(txt, text); - ConsolePrint("Server Information sent to file " + txt, 4); - } - } -#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; - } - } - - public static void CreateAssetCacheDirectories() - { - if (!Directory.Exists(GlobalPaths.AssetCacheDirFonts)) - { - Directory.CreateDirectory(GlobalPaths.AssetCacheDirFonts); - } - - if (!Directory.Exists(GlobalPaths.AssetCacheDirSky)) - { - Directory.CreateDirectory(GlobalPaths.AssetCacheDirSky); - } - - if (!Directory.Exists(GlobalPaths.AssetCacheDirSounds)) - { - Directory.CreateDirectory(GlobalPaths.AssetCacheDirSounds); - } - - if (!Directory.Exists(GlobalPaths.AssetCacheDirTextures)) - { - Directory.CreateDirectory(GlobalPaths.AssetCacheDirTextures); - } - - if (!Directory.Exists(GlobalPaths.AssetCacheDirTexturesGUI)) - { - Directory.CreateDirectory(GlobalPaths.AssetCacheDirTexturesGUI); - } - - if (!Directory.Exists(GlobalPaths.AssetCacheDirScripts)) - { - Directory.CreateDirectory(GlobalPaths.AssetCacheDirScripts); - } - - if (!Directory.Exists(GlobalPaths.AssetCacheDirAssets)) - { - Directory.CreateDirectory(GlobalPaths.AssetCacheDirAssets); - } - } - - // 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 || CMD || BASICLAUNCHER - catch (Exception ex) - { - LogExceptions(ex); -#else - catch (Exception) - { -#endif - } - } - - 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 - - public static bool FileHasInvalidChars(string path) - { - string fileName = Path.GetFileName(path); - - if (Regex.Match(fileName, @"[^\w-.'_!()& ]") != Match.Empty) - { - 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 URI || LAUNCHER || CMD || BASICLAUNCHER - catch (Exception ex) - { - LogExceptions(ex); -#else - catch (Exception) - { -#endif - } - } - -#if LAUNCHER || CMD || URI || BASICLAUNCHER - public static void LogExceptions(Exception ex) - { - LogPrint("EXCEPTION|MESSAGE: " + (ex.Message != null ? ex.Message.ToString() : "N/A"), 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 - - //http://stevenhollidge.blogspot.com/2012/06/async-taskdelay.html - public static Task Delay(int milliseconds) - { - var tcs = new TaskCompletionSource(); - new System.Threading.Timer(_ => tcs.SetResult(null)).Change(milliseconds, -1); - return tcs.Task; - } - -#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) - { - //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; - } - } -#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 || CMD || 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 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; - } - - 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 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 == "") - { - 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="); - string fixedID = Regex.Replace(id, "[^0-9]", ""); - - //really fucking hacky. - string finalUrl = fixedUrl.Before("id=") + "id=" + fixedID; - - return finalUrl; - } - - public static void CreateInitialFileListIfNeededMulti() - { - if (GlobalVars.NoFileList) - return; - - string filePath = GlobalPaths.ConfigDir + "\\InitialFileList.txt"; - - if (!File.Exists(filePath)) - { - Thread t = new Thread(CreateInitialFileList); - t.Start(); - } - else - { - 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) - { - 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; - } - } - - //MessageBox.Show(lineCount + "\n" + fileCount); - - if (lineCount != fileCount) - { - Thread t = new Thread(CreateInitialFileList); - t.Start(); - } - } - } - - private static void CreateInitialFileList() - { - string filterPath = GlobalPaths.ConfigDir + @"\\" + GlobalPaths.InitialFileListIgnoreFilterName; - string[] fileListToIgnore = File.ReadAllLines(filterPath); - string FileName = GlobalPaths.ConfigDir + "\\InitialFileList.txt"; - - 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; - } - } - } - } -} -#endregion diff --git a/Novetus/NovetusCore/StorageAndFunctions/NETExt.cs b/Novetus/NovetusCore/StorageAndFunctions/NETExt.cs deleted file mode 100644 index 7e4d6a8..0000000 --- a/Novetus/NovetusCore/StorageAndFunctions/NETExt.cs +++ /dev/null @@ -1,213 +0,0 @@ -#region Usings -using System; -using System.Drawing; -using System.Windows.Forms; -using System.Diagnostics; -using System.Security.Cryptography; -using System.Text; -using System.IO; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using System.Net; -#endregion - -#region .NET Extentions - -//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 - -public static class NETExt -{ - #region Rich Text Box Extensions - public static void AppendText(this RichTextBox box, string text, Color color) - { - box.SelectionStart = box.TextLength; - box.SelectionLength = 0; - - box.SelectionColor = color; - box.AppendText(text); - box.SelectionColor = box.ForeColor; - } - #endregion - - #region Process Extensions - public static bool IsRunning(this Process process) - { - try - { - Process.GetProcessById(process.Id); - } - catch (InvalidOperationException) - { - 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 -} -#endregion \ No newline at end of file diff --git a/Novetus/NovetusCore/StorageAndFunctions/NovetusFuncs.cs b/Novetus/NovetusCore/StorageAndFunctions/NovetusFuncs.cs new file mode 100644 index 0000000..fc40557 --- /dev/null +++ b/Novetus/NovetusCore/StorageAndFunctions/NovetusFuncs.cs @@ -0,0 +1,852 @@ +#region Usings +using System; +using System.IO; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Xml; +using System.Xml.Linq; +using System.Linq; +#endregion + +#region Novetus Functions +public class NovetusFuncs +{ + public static string CopyMapToRBXAsset() + { + 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://")) + { + 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.AssetCacheDirTextures); + + try + { + string path = download.GetFullDLPath(); + download.InitDownloadNoDialog(path); + return GlobalPaths.AssetCacheTexturesGameDir + download.fileName; + } +#if URI || LAUNCHER || CMD || 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.AssetCacheDirFonts); + + 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 || CMD || 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; + } + +#if LAUNCHER + public static void PingMasterServer(bool online, string reason, RichTextBox box) +#else + public static void PingMasterServer(bool online, string reason) +#endif + { + 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"; + } + +#if LAUNCHER + ConsolePrint("Pinging master server. " + reason, 4, box); +#elif CMD + ConsolePrint("Pinging master server. " + reason, 4); +#endif + +#if LAUNCHER + Task.Factory.StartNew(() => TryPing(box)); +#else + Task.Factory.StartNew(() => TryPing()); +#endif + } + +#if LAUNCHER + public static void TryPing(RichTextBox box) +#else + private static void TryPing() +#endif + { + string response = Util.HttpGet(GlobalVars.PingURL); + + if (!string.IsNullOrWhiteSpace(response)) + { +#if LAUNCHER + ConsolePrint(response, response.Contains("ERROR:") ? 2 : 4, box); +#elif CMD + ConsolePrint(response, response.Contains("ERROR:") ? 2 : 4); +#endif + + if (response.Contains("ERROR:")) + { + GlobalVars.ServerID = "N/A"; + } + } + + if (!GlobalVars.ServerID.Equals("N/A")) + { +#if LAUNCHER + ConsolePrint("Your server's ID is " + GlobalVars.ServerID, 4, box); +#elif CMD + ConsolePrint("Your server's ID is " + GlobalVars.ServerID, 4); +#endif + } + + GlobalVars.PingURL = ""; + } + +#if CMD + public static void CreateTXT() + { + if (GlobalVars.RequestToOutputInfo) + { + 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 = { + SecurityFuncs.Base64Encode("localhost"), + SecurityFuncs.Base64Encode(GlobalVars.UserConfiguration.RobloxPort.ToString()), + SecurityFuncs.Base64Encode(GlobalVars.UserConfiguration.SelectedClient) + }; + string URI2 = "novetus://" + SecurityFuncs.Base64Encode(string.Join("|", lines2), true); + + string[] text = { + "Process ID: " + (GlobalVars.ProcessID == 0 ? "N/A" : GlobalVars.ProcessID.ToString()), + "Don't copy the Process ID when sharing the server.", + "--------------------", + "Server Info:", + "Client: " + GlobalVars.UserConfiguration.SelectedClient, + "IP: " + (!string.IsNullOrWhiteSpace(GlobalVars.UserConfiguration.AlternateServerIP) ? GlobalVars.UserConfiguration.AlternateServerIP : GlobalVars.ExternalIP), + "Port: " + GlobalVars.UserConfiguration.RobloxPort.ToString(), + "Map: " + GlobalVars.UserConfiguration.Map, + "Players: " + GlobalVars.UserConfiguration.PlayerLimit, + "Version: Novetus " + GlobalVars.ProgramInformation.Version, + "Online URI Link:", + URI, + "Local URI Link:", + URI2 + }; + + string txt = GlobalPaths.BasePath + "\\" + GlobalVars.ServerInfoFileName; + File.WriteAllLines(txt, text); + ConsolePrint("Server Information sent to file " + txt, 4); + } + } +#endif + +#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) + { + //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; + } + } +#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 == "") + { + 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="); + string fixedID = Regex.Replace(id, "[^0-9]", ""); + + //really fucking hacky. + string finalUrl = fixedUrl.Before("id=") + "id=" + fixedID; + + return finalUrl; + } +} +#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 +{ + public static AssetCacheDef Fonts + { + get + { + return new AssetCacheDef("SpecialMesh", + new string[] { "MeshId", "TextureId" }, + new string[] { ".mesh", ".png" }, + new string[] { GlobalPaths.AssetCacheDirFonts, GlobalPaths.AssetCacheDirTextures }, + new string[] { GlobalPaths.AssetCacheFontsGameDir, GlobalPaths.AssetCacheTexturesGameDir }); + } + } + + public static AssetCacheDef Sky + { + get + { + return new AssetCacheDef("Sky", + new string[] { "SkyboxBk", "SkyboxDn", "SkyboxFt", "SkyboxLf", "SkyboxRt", "SkyboxUp" }, + new string[] { ".png" }, + new string[] { GlobalPaths.AssetCacheDirSky }, + new string[] { GlobalPaths.AssetCacheSkyGameDir }); + } + } + + public static AssetCacheDef Decal + { + get + { + return new AssetCacheDef("Decal", + new string[] { "Texture" }, + new string[] { ".png" }, + new string[] { GlobalPaths.AssetCacheDirTextures }, + new string[] { GlobalPaths.AssetCacheTexturesGameDir }); + } + } + + public static AssetCacheDef Texture + { + get + { + return new AssetCacheDef("Texture", + new string[] { "Texture" }, + new string[] { ".png" }, + new string[] { GlobalPaths.AssetCacheDirTextures }, + new string[] { GlobalPaths.AssetCacheTexturesGameDir }); + } + } + + public static AssetCacheDef HopperBin + { + get + { + return new AssetCacheDef("HopperBin", + new string[] { "TextureId" }, + new string[] { ".png" }, + new string[] { GlobalPaths.AssetCacheDirTextures }, + new string[] { GlobalPaths.AssetCacheTexturesGameDir }); + } + } + + public static AssetCacheDef Tool + { + get + { + return new AssetCacheDef("Tool", + new string[] { "TextureId" }, + new string[] { ".png" }, + new string[] { GlobalPaths.AssetCacheDirTextures }, + new string[] { GlobalPaths.AssetCacheTexturesGameDir }); + } + } + + public static AssetCacheDef Sound + { + get + { + return new AssetCacheDef("Sound", + new string[] { "SoundId" }, + new string[] { ".wav" }, + new string[] { GlobalPaths.AssetCacheDirSounds }, + new string[] { GlobalPaths.AssetCacheSoundsGameDir }); + } + } + + public static AssetCacheDef ImageLabel + { + get + { + return new AssetCacheDef("ImageLabel", + new string[] { "Image" }, + new string[] { ".png" }, + new string[] { GlobalPaths.AssetCacheDirTextures }, + new string[] { GlobalPaths.AssetCacheTexturesGameDir }); + } + } + + public static AssetCacheDef Shirt + { + get + { + return new AssetCacheDef("Shirt", + new string[] { "ShirtTemplate" }, + new string[] { ".png" }, + new string[] { GlobalPaths.AssetCacheDirTextures }, + new string[] { GlobalPaths.AssetCacheTexturesGameDir }); + } + } + + public static AssetCacheDef ShirtGraphic + { + get + { + return new AssetCacheDef("ShirtGraphic", + new string[] { "Graphic" }, + new string[] { ".png" }, + new string[] { GlobalPaths.AssetCacheDirTextures }, + new string[] { GlobalPaths.AssetCacheTexturesGameDir }); + } + } + + public static AssetCacheDef Pants + { + get + { + return new AssetCacheDef("Pants", + new string[] { "PantsTemplate" }, + new string[] { ".png" }, + new string[] { GlobalPaths.AssetCacheDirTextures }, + new string[] { GlobalPaths.AssetCacheTexturesGameDir }); + } + } + + public static AssetCacheDef Script + { + get + { + return new AssetCacheDef("Script", + new string[] { "LinkedSource" }, + new string[] { ".lua" }, + new string[] { GlobalPaths.AssetCacheDirScripts }, + new string[] { GlobalPaths.AssetCacheScriptsGameDir }); + } + } + + public static AssetCacheDef LocalScript + { + get + { + return new AssetCacheDef("LocalScript", + new string[] { "LinkedSource" }, + new string[] { ".lua" }, + new string[] { GlobalPaths.AssetCacheDirScripts }, + new string[] { GlobalPaths.AssetCacheScriptsGameDir }); + } + } + + //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) + { + 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 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 void DownloadFilesFromNode(string url, string path, string fileext, string id) + { + if (!string.IsNullOrWhiteSpace(id)) + { + Downloader download = new Downloader(url, id); + download.InitDownload(path, fileext, "", true, false); + if (download.getDownloadOutcome().Contains("Error")) + { + throw new IOException(download.getDownloadOutcome()); + } + } + } + + 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 rbxassetid = "rbxassetid://"; + string urlFixed = url + oldurl.After(rbxassetid); + string peram = "id="; + + if (urlFixed.Contains(peram)) + { + return urlFixed; + } + } + } + } + } + + return ""; + } + + 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); + } +} +#endregion +#endregion diff --git a/Novetus/NovetusCore/StorageAndFunctions/ScriptFuncs.cs b/Novetus/NovetusCore/StorageAndFunctions/ScriptFuncs.cs deleted file mode 100644 index 06981b6..0000000 --- a/Novetus/NovetusCore/StorageAndFunctions/ScriptFuncs.cs +++ /dev/null @@ -1,454 +0,0 @@ -#region Usings -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Runtime.InteropServices; -using System.Security.Cryptography; -using System.Text; -using System.Text.RegularExpressions; -using System.Windows.Forms; -using System.Xml.Linq; -#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) - { - string privateKeyPath = Path.GetDirectoryName(scriptFileName) + "//privatekey.txt"; - - if (File.Exists(privateKeyPath)) - { - //init vars - string format = (newSigFormat ? "--rbxsig" : "") + "%{0}%{1}"; - byte[] blob = Encoding.Default.GetBytes(File.ReadAllText(privateKeyPath)); - - 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. - GlobalFuncs.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); - } - } - - public static string GetScriptFuncForType(ScriptType type) - { - return GetScriptFuncForType(GlobalVars.UserConfiguration.SelectedClient, type); - } - - public static string GetScriptFuncForType(string ClientName, ScriptType type) - { - FileFormat.ClientInfo info = GlobalFuncs.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") : ""; -#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 + "'"; - - switch (type) - { - case ScriptType.Client: - return "_G.CSConnect(" - + (info.UsesID ? GlobalVars.UserConfiguration.UserID : 0) + ",'" - + GlobalVars.IP + "'," - + GlobalVars.JoinPort + ",'" - + (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) - { - 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(string ClientName, ScriptType type) - { - bool shouldUseLoadFile = GlobalVars.SelectedClientInfo.CommandLineArgs.Contains("%useloadfile%"); - string execScriptMethod = shouldUseLoadFile ? "loadfile" : "dofile"; - - string[] code = { - "--Load Script", - //scriptcontents, - (GlobalVars.SelectedClientInfo.SeperateFolders ? "" + - execScriptMethod + "('rbxasset://../../content/scripts/" + GlobalPaths.ScriptName + ".lua')" + (shouldUseLoadFile ? "()" : "") : - execScriptMethod + "('rbxasset://scripts/" + GlobalPaths.ScriptName + ".lua')" + (shouldUseLoadFile ? "()" : "")), - GetScriptFuncForType(type), - }; - - if (GlobalVars.SelectedClientInfo.SeperateFolders) - { - string scriptsFolder = GlobalPaths.ClientDir + @"\\" + ClientName + @"\\" + GlobalFuncs.GetClientSeperateFolderName(type) + @"\\content\\scripts"; - if (!Directory.Exists(scriptsFolder)) - { - Directory.CreateDirectory(scriptsFolder); - } - } - - string outputPath = (GlobalVars.SelectedClientInfo.SeperateFolders ? - GlobalPaths.ClientDir + @"\\" + ClientName + @"\\" + GlobalFuncs.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); - } - } - - public static string GetGeneratedScriptName(string ClientName, ScriptType type) - { - GenerateScriptForClient(ClientName, type); - return GlobalFuncs.GetGenLuaFileName(ClientName, type); - } - } -#endregion - - #region ClientScript Parser - public class ClientScript - { - public static string GetArgsFromTag(string code, string tag, string endtag) - { - try - { - int pFrom = code.IndexOf(tag) + tag.Length; - int pTo = code.LastIndexOf(endtag); - string result = code.Substring(pFrom, pTo - pFrom); - return result; - } -#if URI || LAUNCHER || CMD || BASICLAUNCHER - catch (Exception ex) - { - GlobalFuncs.LogExceptions(ex); -#else - catch (Exception) - { -#endif - return "%donothing%"; - } - } - - 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) - { - 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 ""; - } - } - - 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 || CMD || BASICLAUNCHER - catch (Exception ex) - { - GlobalFuncs.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 = GlobalFuncs.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; - - FileFormat.ClientInfo info = GlobalFuncs.GetClientInfoValues(ClientName); - - ScriptType type = GetTypeFromTag(start); - - //we must have the ending tag before we continue. - if (string.IsNullOrWhiteSpace(end)) - { - return ""; - } - - if (usesharedtags) - { - string sharedstart = ""; - string sharedend = ""; - - if (code.Contains(sharedstart) && code.Contains(sharedend)) - { - start = sharedstart; - end = sharedend; - } - } - - if (info.Fix2007) - { - Generator.GenerateScriptForClient(type); - } - - string extractedCode = GetArgsFromTag(code, start, end); - - if (extractedCode.Contains("%donothing%")) - { - return ""; - } - -#if LAUNCHER - string md5dir = !info.AlreadyHasSecurity ? SecurityFuncs.GenerateMD5(Assembly.GetExecutingAssembly().Location) : ""; -#else - 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("%ip%", GlobalVars.IP) - .Replace("%port%", GlobalVars.UserConfiguration.RobloxPort.ToString()) - .Replace("%joinport%", GlobalVars.JoinPort.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%") ? GlobalFuncs.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("%doublequote%", "\"") - .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()); - - if (compiled.Contains("%disabled%")) - { - MessageBox.Show("This option has been disabled for this client.", "Novetus - Error", MessageBoxButtons.OK, MessageBoxIcon.Error); - return ""; - } - - return compiled; - } - } -#endregion -} -#endregion \ No newline at end of file diff --git a/Novetus/NovetusCore/StorageAndFunctions/Util.cs b/Novetus/NovetusCore/StorageAndFunctions/Util.cs new file mode 100644 index 0000000..71960e7 --- /dev/null +++ b/Novetus/NovetusCore/StorageAndFunctions/Util.cs @@ -0,0 +1,725 @@ +#region Usings +using System; +using System.Drawing; +using System.Windows.Forms; +using System.Diagnostics; +using System.Security.Cryptography; +using System.Text; +using System.IO; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Net; +using NLog; +using System.Text.RegularExpressions; +using System.Drawing.Imaging; +using System.Runtime.InteropServices; +#endregion + +#region Utils + +//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 + +public static class Util +{ + #region Rich Text Box Extensions + public static void AppendText(this RichTextBox box, string text, Color color) + { + box.SelectionStart = box.TextLength; + box.SelectionLength = 0; + + box.SelectionColor = color; + box.AppendText(text); + box.SelectionColor = box.ForeColor; + } + #endregion + + #region Process Extensions + public static bool IsRunning(this Process process) + { + try + { + Process.GetProcessById(process.Id); + } + catch (InvalidOperationException) + { + 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 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) + { + return; + } + } + + 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 + { + 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 + { + using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(fileFullName))) + { + image = Image.FromStream(ms); + } + + // 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 || CMD || 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 || CMD || BASICLAUNCHER + catch (Exception ex) + { + LogExceptions(ex); +#else + catch (Exception) + { +#endif + } + } + + 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 + + public static bool FileHasInvalidChars(string path) + { + string fileName = Path.GetFileName(path); + + if (Regex.Match(fileName, @"[^\w-.'_!()& ]") != Match.Empty) + { + 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 URI || LAUNCHER || CMD || 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) + { + var tcs = new TaskCompletionSource(); + new System.Threading.Timer(_ => tcs.SetResult(null)).Change(milliseconds, -1); + return tcs.Task; + } + + 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 || CMD || URI || BASICLAUNCHER + public static void LogExceptions(Exception ex) + { + LogPrint("EXCEPTION|MESSAGE: " + (ex.Message != null ? ex.Message.ToString() : "N/A"), 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 || CMD || 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)) + { + 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); + } + +#if LAUNCHER + public static void ConsolePrint(string text, int type, RichTextBox box, bool noLog = false, 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); + if (!noLog) + LogPrint(text); + break; + case 2: + box.AppendText(text, Color.Red); + if (!noLog) + LogPrint(text, 2); + break; + case 3: + box.AppendText(text, Color.Lime); + if (!noLog) + LogPrint(text); + break; + case 4: + box.AppendText(text, Color.Aqua); + if (!noLog) + LogPrint(text); + break; + case 5: + box.AppendText(text, Color.Yellow); + if (!noLog) + LogPrint(text, 3); + break; + case 6: + box.AppendText(text, Color.LightSalmon); + if (!noLog) + LogPrint(text); + break; + case 0: + default: + box.AppendText(text, Color.Black); + if (!noLog) + LogPrint(text); + break; + } + + box.AppendText(Environment.NewLine, Color.White); + } +#elif CMD + public static void ConsolePrint(string text, int type, bool notime = false, bool noLog = false) + { + if (!notime) + { + ConsoleText("[" + DateTime.Now.ToShortTimeString() + "] - ", ConsoleColor.White); + } + + switch (type) + { + case 2: + ConsoleText(text, ConsoleColor.Red); + if (!noLog) + LogPrint(text, 2); + break; + case 3: + ConsoleText(text, ConsoleColor.Green); + if (!noLog) + LogPrint(text); + break; + case 4: + ConsoleText(text, ConsoleColor.Cyan); + if (!noLog) + LogPrint(text); + break; + case 5: + ConsoleText(text, ConsoleColor.Yellow); + if (!noLog) + LogPrint(text, 3); + break; + case 1: + default: + ConsoleText(text, ConsoleColor.White); + if (!noLog) + LogPrint(text); + break; + } + + ConsoleText(Environment.NewLine, ConsoleColor.White); + } + + public static void ConsoleText(string text, ConsoleColor color) + { + Console.ForegroundColor = color; + Console.Write(text); + } +#endif + #endregion +} +#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; + } + + 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 diff --git a/Novetus/NovetusCore/WinForms/CustomFormControls.cs b/Novetus/NovetusCore/WinForms/CustomFormControls.cs deleted file mode 100644 index f8bef38..0000000 --- a/Novetus/NovetusCore/WinForms/CustomFormControls.cs +++ /dev/null @@ -1,27 +0,0 @@ -#region Usings -using System; -using System.Runtime.InteropServices; -using System.Windows.Forms; -#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; - } - - protected override void WndProc(ref Message m) - { - if (m.Msg == 0x1328 && !DesignMode) - m.Result = new IntPtr(1); - else - base.WndProc(ref m); - } -} -#endregion - - diff --git a/Novetus/NovetusCore/WinForms/FormExt.cs b/Novetus/NovetusCore/WinForms/FormExt.cs deleted file mode 100644 index f3d7eaa..0000000 --- a/Novetus/NovetusCore/WinForms/FormExt.cs +++ /dev/null @@ -1,28 +0,0 @@ -#region Usings -using System; -using System.Runtime.InteropServices; -using System.Windows.Forms; -#endregion - -#region Form Extensions -public static class FormExt -{ - [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