public static void WalkDirectory(DirectoryInfo dir, Mod mod) { Console.WriteLine("Found directory " + dir.Name + " belonging to " + mod.Name); foreach (var file in dir.EnumerateFiles()) { var relativePathExtract = file.DirectoryName.Split( new[] { mod.FolderName + Path.DirectorySeparatorChar }, StringSplitOptions.None); var relpath = ""; if (relativePathExtract.Length > 1) { relpath = relativePathExtract.Last(); } var modfile = new ModFile { Filename = file.Name, RelativePath = relpath, Hash = GetMd5(file) }; mod.Files.Add(modfile); } foreach (var subdir in dir.EnumerateDirectories()) { // wew recursion WalkDirectory(subdir, mod); } }
public void TestModletListWithMalformedSteps() { MockRepo repo = new MockRepo(); TestClass obj = new TestClass { intValue = 10, boolValue = false }; repo.AddDef("a", obj); ModDefinition mod = new ModDefinition { guid = "a", modletlist = new List <ModletStep> { new ModletStep { field = "intValue", value = 20 }, new ModletStep { field = null, value = 20 }, new ModletStep { field = "NoValue", value = null }, new ModletStep { field = null, value = null }, new ModletStep { field = "boolValue", value = true } } }; ModFile f = new ModFile("ModlietListWithMalformedSteps", repo, new MockLogger()); f.ApplyMod(mod); Assert.AreEqual(obj.intValue, 20); Assert.IsTrue(obj.boolValue); }
public void AddMod(ModFile mod, bool isInstalled) { this.Mods.Add(mod.GetID(), isInstalled); this._modFiles.Add(mod.GetID(), mod); Write(); }
private static List <ModFile> LoadInApplication() { _cachedEditorFiles = new List <ModFile>(); Queue <string> directoriesToCheckForMods = new Queue <string>(); directoriesToCheckForMods.Enqueue($"{Directories.DataPath}/{Settings.ModsDirectory}"); while (directoriesToCheckForMods.Count > 0) { string directory = directoriesToCheckForMods.Dequeue(); foreach (string file in Directory.GetFiles(directory)) { if (Path.GetExtension(file) == UMS.Utility.MOD_EXTENSION) { ModFile mod = ModFile.LoadFromFile(file); OutputModFile(mod); _cachedEditorFiles.Add(mod); } } foreach (string subFolder in Directory.GetDirectories(directory)) { directoriesToCheckForMods.Enqueue(subFolder); } } return(_cachedEditorFiles); }
private static void parseDelArgs(ModFile mf) { if (mf.DelInfo == null) { mf = ModParsing.GetSpecificMod(mf.ModId); if (string.IsNullOrEmpty(mf.DelInfo)) { Console.WriteLine( "There's no info on how to delete this mod! Please ask the creators to add that in!"); return; } } var args = mf.DelInfo.Split('?'); foreach (var target in args) { // If something is broken, skip this target since continuing would delete the h3 directory. if (string.IsNullOrEmpty(target)) { continue; } var path = Path.Combine(Utilities.GameDirectoryOrThrow, target); if (File.Exists(path)) { File.Delete(path); } else if (Directory.Exists(path)) { Directory.Delete(path, true); } } }
/// <summary> /// This function installs a mod based off the parameters provided. The first parameter is the an 5-length array which /// represents the file info. The second parameter is a bool which determines if the archive will be deleted after /// installation. /// </summary> /// <param name="fileinfo">ModFile class, gets the <c>rawname</c> from it</param> /// <param name="delArchive">Defines if the archive should be deleted after installation</param> /// <returns>Boolean</returns> public static bool InstallMod(ModFile fileinfo, bool delArchive = true) { fileinfo.Arguments.Replace("BACKSLASH", @"\"); if (fileinfo.Arguments == "") { fileinfo.Arguments = "unzipToDir?"; } var args = fileinfo.Arguments.Split('?'); ModInstallerCommon.DebugLog(""); for (var i = 0; i < args.Length; i++) { ModInstallerCommon.DebugLog(args[i] + ", "); } for (var i = 0; i < args.Length; i++) { if (args[i] == "moveToFolder") { MoveToFolder(args[i + 1], args[i + 2], args[i + 3]); } if (args[i] == "unzipToDir") { ModInstallerCommon.DebugLog("Unzipping to " + args[i + 1]); var ArchiveType = Archives.ArchiveType.Zip; if (fileinfo.RawName.ToLower().EndsWith(".rar")) { ArchiveType = Archives.ArchiveType.RAR; Console.WriteLine("Archive is rar!"); } if (fileinfo.RawName.ToLower().EndsWith(".7z")) { ArchiveType = Archives.ArchiveType.SevenZip; Console.WriteLine("Archive is 7z!"); } Archives.UnArchive(fileinfo.RawName, Path.Combine(Utilities.GameDirectoryOrThrow, args[i + 1]), delArchive, ArchiveType); } if (args[i] == "addFolder") { ModInstallerCommon.DebugLog("Creating Directory " + args[i + 1]); Directory.CreateDirectory(Path.Combine(Utilities.GameDirectoryOrThrow, args[i + 1])); } if (args[i] == "break") { break; } } Console.WriteLine("Installed " + fileinfo.Name); return(true); }
public bool SetActive(ModFile mod, bool state) { if (state) { // Enable Mod string modPath = FileSystem.GetDisabledDir(mod.TFDir) + @"\" + Path.GetFileName(mod.Path); if (File.Exists(modPath)) { string newPath = FileSystem.GetCustomDir(mod.TFDir) + @"\" + Path.GetFileName(mod.Path); File.Move(modPath, newPath); mod.Path = newPath; } mod.Active = true; } else { // Disable Mod string modPath = FileSystem.GetCustomDir(mod.TFDir) + @"\" + Path.GetFileName(mod.Path); if (File.Exists(modPath)) { string newPath = FileSystem.GetDisabledDir(mod.TFDir) + @"\" + Path.GetFileName(mod.Path); File.Move(modPath, newPath); mod.Path = newPath; } mod.Active = false; } return(true); }
public static void Run(ModFile m) { _fieldsInRecords = new Dictionary <string, HashSet <string> >(); Stopwatch.Start(); foreach (var child in m.Children) { //Console.WriteLine(child.Type); switch (child) { case Group group1: FoundGroup(group1); break; case Record record1: FoundRecord(record1); break; } } var parsing = Stopwatch.ElapsedMilliseconds; Stopwatch.Stop(); Console.WriteLine($"Found Groups: {_groups}, Records: {_records}, Subrecords: {_fields}"); Console.WriteLine($"Tranversing took: {parsing}ms"); foreach (var kv in _fieldsInRecords) { Console.WriteLine($"{kv.Key} => {string.Join(',', kv.Value)}"); } }
/// <summary> /// Given modid, returns all dependents /// </summary> /// <returns><c>ModFile</c> Array</returns> public static ModFile[] GetDependents(ModFile mf, bool GetNonInstalledToo) { ModFile[] mods = null; if (!GetNonInstalledToo) { mods = GetAllMods(); } //if get dependants of non-installed too else { mods = InstalledMods.GetInstalledMods(); } //otherwise, by default, get all installed mods to compare to ModFile[] dependents = new ModFile[0]; //list of dependants for (int i = 0; i < mods.Length; i++) //for every mod { for (int x = 0; x < mods[i].Dependencies.Length; x++) //for every mod's dependencies { if (mods[i].Dependencies[x] == mf.ModId) //if the dependencies include the modid of the mf { Array.Resize <ModFile>(ref dependents, dependents.Length + 1); dependents[dependents.Length - 1] = mods[i]; //add to list of dependents (apparently ^1 is the same as length - 1. huh.) } } } return(dependents); }
/// <summary> /// Downloads a mod for updating. /// </summary> /// <param name="release">The mods release to be downloaded.</param> /// <param name="username">The username.</param> /// <param name="token">The login token.</param> /// <param name="progress">A progress object used to report the progress of the operation.</param> /// <param name="cancellationToken">A cancelation token that can be used to cancel the operation.</param> public static async Task <ModFile> DownloadUpdateAsync(ModRelease release, string username, string token, IProgress <double> progress, CancellationToken cancellationToken) { DirectoryInfo modDirectory = App.Instance.Settings.GetModDirectory(release.InfoFile.FactorioVersion); if (!modDirectory.Exists) { modDirectory.Create(); } var downloadUrl = BuildUrl(release, username, token); var file = new FileInfo(Path.Combine(modDirectory.FullName, release.FileName)); await WebHelper.DownloadFileAsync(downloadUrl, null, file, progress, cancellationToken); if (cancellationToken.IsCancellationRequested) { return(null); } ModFile modFile; if (!ModFile.TryLoadFromFile(file, out modFile)) { throw new InvalidOperationException("The server sent an invalid mod file."); } return(modFile); }
private ModFile ReadModFolder() { ModFile modFolder = new ModFile();; var configFileName = "Configuration.xml"; var config = XmlHelper.ReadXmlFile(configFileName); if (config == null) { // Throw new invalid xml exception? return(null); } try { var foundModFolder = config.Descendants("folderName").First(); modFolder.FileName = XElementHelper.ReadStringValue(foundModFolder, "fileName"); modFolder.SourcePath = XElementHelper.ReadStringValue(foundModFolder, "sourcePath"); modFolder.TargetPath = XElementHelper.ReadStringValue(foundModFolder, "targetPath"); } catch { } return(modFolder); }
private static void parseDelArgs(ModFile mf) { if (mf.DelInfo == null) { mf = ModParsing.GetSpecificMod(mf.ModId); if (mf.DelInfo == null || mf.DelInfo == "") { Console.WriteLine( "There's no info on how to delete this mod! Please ask the creators to add that in!"); return; } } var args = mf.DelInfo.Split('?'); for (var i = 0; i < args.Length; i++) { if (File.Exists(ModInstallerCommon.Files.MainFiledir + @"\" + args[i])) { File.Delete(ModInstallerCommon.Files.MainFiledir + @"\" + args[i]); } else if (Directory.Exists(ModInstallerCommon.Files.MainFiledir + @"\" + args[i])) { Directory.Delete(ModInstallerCommon.Files.MainFiledir + @"\" + args[i]); } } }
private Stream ExtractWholeFile(ZipEntry ze, ref string path) { Utils.Debug($"Extracting {ze.Name} from OMOD"); var file = ModFile.GetInputStream(ze); Stream tempStream; if (path != null || ze.Size > Framework.Settings.MaxMemoryStreamSize) { tempStream = Utils.CreateTempFile(out path); } else { tempStream = new MemoryStream((int)ze.Size); } byte[] buffer = new byte[4096]; int i; while ((i = file.Read(buffer, 0, 4096)) > 0) { tempStream.Write(buffer, 0, i); } tempStream.Position = 0; return(tempStream); }
public static IEnumerator Play_Mode_Loading() { List <ModFile> files = Hooks.GetModsInProject(); Assert.IsTrue(files.Count > 0, "No mods were loaded"); string tempPath = Path.GetTempPath() + System.Guid.NewGuid(); Directories.EnsurePathExists(tempPath); foreach (ModFile mod in files) { mod.Save(tempPath); } int deserialized = 0; foreach (string savedFile in Directory.GetFiles(tempPath)) { ModFile file = ModFile.LoadFromFile(savedFile); if (file != null) { deserialized++; } } Assert.IsTrue(deserialized == files.Count, $"We only deserialized {deserialized}/{files.Count} mod files"); return(null); }
public static ModFile[] GetDependants(string modid, bool GetNonInstalledToo = false) { ModFile[] mods = null; if (!GetNonInstalledToo) { mods = GetAllMods(); } else { mods = InstalledMods.GetInstalledMods(); } ModFile[] dependants = new ModFile[0]; for (int i = 0; i < mods.Length; i++) { for (int x = 0; x < mods[i].Dependencies.Length; x++) { if (mods[i].Dependencies[x] == modid) { Array.Resize <ModFile>(ref dependants, dependants.Length + 1); dependants[dependants.Length - 1] = mods[i]; } } } return(dependants); }
private static void Main(string[] args) { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); var filename = @"e:\SteamLibrary\steamapps\common\Skyrim Special Edition\Data\Skyrim.esm"; if (args.Length != 0 && File.Exists(args[0])) { filename = args[0]; } var stopWatch = new Stopwatch(); Console.WriteLine($"Memory used before: {GC.GetTotalMemory(false)} bytes"); stopWatch.Start(); var m = new ModFile(filename); var loading = stopWatch.ElapsedMilliseconds; Console.WriteLine($"Loading took: {loading}ms"); Console.WriteLine($"Memory used after: {GC.GetTotalMemory(false)} bytes"); //TraverseModFile.Run(m); TestGenerated.Run(m); Console.WriteLine($"Memory usage before dispose: {GC.GetTotalMemory(false)} bytes"); m.Dispose(); Console.WriteLine($"Memory usage after dispose: {GC.GetTotalMemory(false)} bytes"); m = null; GC.Collect(); Console.WriteLine($"Memory usage after gc collect: {GC.GetTotalMemory(false)} bytes"); }
/// <summary> /// Creates a <see cref="ModFileInfo"/> from a <see cref="ModFile"/>. /// </summary> /// <param name="modFile">ModFile to get information from.</param> public ModFileInfo(ModFile modFile) { Id = modFile?.FileID.ToString(); Filename = modFile?.FileName; Name = modFile?.Name; HumanReadableVersion = modFile?.ModVersion; }
void btnMergeFiles_Click(object sender, EventArgs e) { if (!Paths.ValidateModsDirectory() || (treConflicts.FileNodes.Any(node => ModFile.IsScript(node.Text)) && !Paths.ValidateScriptsDirectory()) || (treConflicts.FileNodes.Any(node => ModFile.IsBundle(node.Text)) && !Paths.ValidateBundlesDirectory())) { return; } var mergedModName = Paths.RetrieveMergedModName(); if (mergedModName == null) { return; } InitializeProgressScreen("Merging"); Program.Inventory = MergeInventory.Load(Paths.Inventory); var merger = new FileMerger(Program.Inventory, OnMergeProgressChanged, OnMergeComplete); var fileNodes = treConflicts.FileNodes.Where(node => node.GetTreeNodes().Count(modNode => modNode.Checked) > 1); merger.MergeByTreeNodesAsync(fileNodes, mergedModName); }
public static ModFile[] ReturnIncompatableMods(ModFile mf, ModFile[] mfs, bool includeDisabledMods) { List <ModFile> list = new List <ModFile>(); //Get Direct Incompatable mods if (mf.IncompatableMods != null) { for (int x = 0; x < mf.IncompatableMods.Length; x++) //for every mod this is incompatable with { for (int y = 0; y < mfs.Length; y++) //for every mod that is given { if (CheckIfILmodDisabled(mfs[y]) && !includeDisabledMods) { continue; } if (mfs[y].ModId == mf.ModId) { continue; } if (mf.IncompatableMods[x] == mfs[y].ModId) //if mfs[y] is in inc.mods { list.Add(mfs[y]); //add as incompatable with } } } } //Get Singular Incompatable Mods if (mf.SingularModData != null) { for (int x = 0; x < mf.SingularModData.OccupiesID.Length; x++) //for every mod space this takes up { for (int y = 0; y < mfs.Length; y++) //for every mod given { if (CheckIfILmodDisabled(mfs[y]) && !includeDisabledMods) { continue; } if (mfs[y].ModId == mf.ModId) { continue; } if (mfs[y].SingularModData == null) { continue; } //if mfs[y] doesn't occupy anything, ignore for (int z = 0; z < mfs[y].SingularModData.OccupiesID.Length; z++) //if one of mfs[y]'s occupies place is also in mf { if (mf.SingularModData.OccupiesID[x] == mfs[y].SingularModData.OccupiesID[z]) { list.Add(mfs[y]); //add as incompatable with } } } } } return(list.ToArray()); }
public static Mod LoadOldFile(string fileName) { string modPath = Path.GetDirectoryName(fileName); DateTime creationDate = File.GetCreationTime(fileName); Mod loadedMod; try { string _modName = Path.GetFileNameWithoutExtension(fileName); List <ModFile> modFiles = new List <ModFile>(); using (StreamReader reader = File.OpenText(fileName)) { string line; while ((line = reader.ReadLine()) != null) { char[] lineArray = line.ToCharArray(); Array.Reverse(lineArray); string reversedLine = new string(lineArray); string[] lineElements = reversedLine.Split(new char[] { ' ' }, 3); for (int i = 0; i < lineElements.Length; i++) { char[] reversedElement = lineElements[i].ToCharArray(); Array.Reverse(reversedElement); lineElements[i] = new string(reversedElement); } Array.Reverse(lineElements); string path = Path.GetDirectoryName(lineElements[0]); string filename = Path.GetFileName(lineElements[0]); ModFile file = new ModFile() { Protected = false, FilePath = path, FileName = filename, FileHash = UInt32.Parse(lineElements[1], System.Globalization.NumberStyles.HexNumber), FileSize = UInt32.Parse(lineElements[2]), }; modFiles.Add(file); } } loadedMod = new Mod() { Name = _modName, ModStorePath = modPath, Version = new SemVersion(1), CreationDate = creationDate, Files = modFiles }; return(loadedMod); } catch (Exception ex) { MessageBox.Show("Error while parsing the mod file. Content is invalid."); throw; } }
protected void ModPack_FileRemoved(object sender, ModFile file) { if (file.ModType != this.ModType) { return; } base.BeginInvoke(new MethodInvoker(() => this.Remove(file.FileName, (ModPack)sender))); }
static MergeSource Create(FileInfo file, FileHash hash, bool isBundle) => new MergeSource { TextFile = isBundle ? null : file, Bundle = isBundle ? file : null, Hash = hash, Name = ModFile.GetModNameFromPath(file.FullName) };
private static void ReceiveModFile(Peer peer, byte[] data) { ModFile file = data.Deserialize <ModFile>(); ClientOutput.Line("Received " + file); Client.AddModFile(file); }
/// <summary> /// This function installs a mod based off the parameters provided. The first parameter is the an 5-length array which /// represents the file info. The second parameter is a bool which determines if the archive will be deleted after /// installation. /// </summary> /// <param name="fileinfo">ModFile class, gets the <c>rawname</c> from it</param> /// <param name="delArchive">Defines if the archive should be deleted after installation</param> /// <returns>Boolean</returns> public static bool InstallMod(ModFile fileinfo, bool delArchive = false) { fileinfo.Arguments.Replace("BACKSLASH", @"\"); if (fileinfo.Arguments == "") { fileinfo.Arguments = "unzipToDir?"; } var args = fileinfo.Arguments.Split('?'); ModInstallerCommon.DebugLog(""); for (var i = 0; i < args.Length; i++) { ModInstallerCommon.DebugLog(args[i] + ", "); } for (var i = 0; i < args.Length; i++) { if (args[i] == "moveToFolder") { MoveToFolder(args[i + 1], args[i + 2], args[i + 3]); } if (args[i] == "unzipToDir") { ModInstallerCommon.DebugLog("Unzipping to " + args[i + 1]); var ArchiveType = Archives.ArchiveType.Zip; if (fileinfo.RawName.EndsWith(".rar") || fileinfo.RawName.EndsWith(".RAR")) { ArchiveType = Archives.ArchiveType.RAR; } if (fileinfo.RawName.EndsWith(".7z") || fileinfo.RawName.EndsWith(".7Z")) { ArchiveType = Archives.ArchiveType.SevenZip; } Archives.UnArchive(fileinfo.RawName, ModInstallerCommon.Files.MainFiledir + "/" + args[i + 1], delArchive, ArchiveType); File.Delete(fileinfo.RawName); } if (args[i] == "addFolder") { ModInstallerCommon.DebugLog("Creating Directory " + args[i + 1]); Directory.CreateDirectory(ModInstallerCommon.Files.MainFiledir + args[i + 1]); } if (args[i] == "break") { break; } } Console.WriteLine("Installed " + fileinfo.Name); return(true); }
public static void Play(ModFile f) { if (!f.Enabled) { ModPlayer.Play(f.Base); return; } ModPlayer.Play(f.FilePath); }
public AssetCollisionDialog(ModFile mod, List <string> collisions) { this.DataContext = this; this.Message = "Fantome has detected that the following mods have asset collisions with: " + mod.GetID() + '\n'; this.Message += "Do you want to uninstall these mods to install: " + mod.GetID() + '?'; this.Collisions = collisions; InitializeComponent(); }
/// <summary> /// Gets the mod info and dependencies of a deserialized <c>ModFile</c> class /// </summary> /// <param name="modid">Modid of mod and dependencies you want</param> /// <returns></returns> public static ModFile[] GetModInfoAndDependencies(ModFile mf) { var result = new ModFile[1]; result[result.Length - 1] = mf; result = result.Concat(GetDependencies(mf)).ToArray(); //get dependencies and add them to result return(result); }
public static async Task <object> ShowUninstallModDialog(ModFile mod, ModManager modManager) { UninstallingModDialog dialog = new UninstallingModDialog() { DataContext = new UninstallingModViewModel(mod, modManager) }; return(await DialogHost.Show(dialog, "OperationDialog", dialog.StartUninstallation, null)); }
public static void Run(ModFile m) { var tes4 = m.Children[0] as TES4; Console.WriteLine(tes4.HEDR.version); Console.WriteLine(tes4.HEDR.numRecords); Console.WriteLine(tes4.CNAM?.Value); Console.WriteLine(tes4.SNAM?.Value); }
public GeneratingWadFilesDialog(ModFile mod) { this.DataContext = this; this._mod = mod; this.GeneratingString = string.Format("Generating WAD files for {0}...", mod.GetID()); InitializeComponent(); }
private ModFile ReadModFolder() { ModFile modFolder = new ModFile(); ; var configFileName = "Configuration.xml"; var config = XmlHelper.ReadXmlFile(configFileName); if (config == null) { // Throw new invalid xml exception? return null; } try { var foundModFolder = config.Descendants("folderName").First(); modFolder.FileName = XElementHelper.ReadStringValue(foundModFolder, "fileName"); modFolder.SourcePath = XElementHelper.ReadStringValue(foundModFolder, "sourcePath"); modFolder.TargetPath = XElementHelper.ReadStringValue(foundModFolder, "targetPath"); } catch { } return modFolder; }
public bool HasResolvedConflict(ModFile conflict) { var merge = Merges.FirstOrDefault(mrg => mrg.RelativePath.EqualsIgnoreCase(conflict.RelativePath)); if (merge == null) return false; if (conflict.Mods.Any(mod => !mod.Name.EqualsIgnoreCase(merge.MergedModName) && !merge.ContainsMod(mod.Name))) return false; if (merge.Mods.Any(mod => new LoadOrderComparer().Compare(merge.MergedModName, mod.Name) > 0)) return false; return merge.Mods.All(mod => mod.Hash == Tools.Hasher.ComputeHash(merge.GetModFile(mod.Name))); }