public void Test_ExtractZipFile_ExtractsCorrectly() { string pathToZip = Path.Combine(TestPaths.ToTestFilesFolder, "testZipFile.zip"); string extractPath = Path.Combine(TestPaths.ToTestFilesFolder, "TestDir"); if (Directory.Exists(extractPath)) { Directory.Delete(extractPath, true); } Directory.CreateDirectory(extractPath); BoolWithMessage result = FileUtils.ExtractZipFile(pathToZip, extractPath); Assert.IsTrue(result.Result); bool extractedFileExists = File.Exists(Path.Combine(extractPath, "testFile.txt")); Assert.IsTrue(extractedFileExists); bool mapDirExists = Directory.Exists(Path.Combine(extractPath, "testFolder")); Assert.IsTrue(mapDirExists); extractedFileExists = File.Exists(Path.Combine(extractPath, "testFolder", "testFile.txt")); Assert.IsTrue(extractedFileExists); }
public BoolWithMessage AddAsset() { string errorMessage = ValidateAssetInfo(null); if (!string.IsNullOrWhiteSpace(errorMessage)) { return(BoolWithMessage.False($"The following errors were found:\n\n{errorMessage}")); } Asset newAsset = new Asset() { ID = $"{SelectedAssetID}{SelectedIDExtension}", Author = SelectedAssetAuthor, Category = SelectedAssetCategory, Description = SelectedAssetDescription, Name = SelectedAssetName, PreviewImage = SelectedAssetImageUrl, UpdatedDate = DateTime.UtcNow, Version = 1, }; if (!string.IsNullOrWhiteSpace(SelectedAssetUpdatedDate)) { DateTime.TryParse(SelectedAssetUpdatedDate, out DateTime updateDate); if (updateDate != null && updateDate != DateTime.MinValue) { newAsset.UpdatedDate = updateDate; } } double.TryParse(SelectedAssetVersion, out double version); if (version <= 0) { newAsset.Version = version; } if (SelectedAssetDownloadType == "Url") { newAsset.DownloadLink = AssetCatalog.FormatUrl(SelectedAssetDownloadUrl); } else if (SelectedAssetDownloadType == "Google Drive") { newAsset.DownloadLink = $"rsmm://GDrive/{SelectedAssetDownloadUrl}"; } AssetViewModel viewModel = new AssetViewModel(newAsset); AssetList.Add(viewModel); AssetToEdit = null; SelectedAsset = null; SelectedAsset = AssetList[AssetList.Count - 1]; return(BoolWithMessage.True()); }
internal Task <BoolWithMessage> ImportMapAsync(bool isReimport = false) { Task <BoolWithMessage> task = Task.Factory.StartNew(() => { string sourceFolderToCopy; if (IsZipFileImport) { if (File.Exists(PathToFileOrFolder) == false) { System.Windows.MessageBox.Show("File does not exist", "Error!", MessageBoxButton.OK, MessageBoxImage.Error); return(new BoolWithMessage(false, $"{PathToFileOrFolder} does not exist.")); } // extract files first before copying Directory.CreateDirectory(PathToTempUnzipFolder); BoolWithMessage didExtract = FileUtils.ExtractCompressedFile(PathToFileOrFolder, PathToTempUnzipFolder); if (didExtract.Result == false) { UserMessage = $"Failed to extract file: {didExtract.Message}"; return(new BoolWithMessage(false, $"Failed to extract: {didExtract.Message}.")); } sourceFolderToCopy = EnsurePathToMapFilesIsCorrect(PathToTempUnzipFolder); } else { if (Directory.Exists(PathToFileOrFolder) == false) { System.Windows.MessageBox.Show("Folder does not exist", "Error!", MessageBoxButton.OK, MessageBoxImage.Error); return(new BoolWithMessage(false, $"{PathToFileOrFolder} does not exist.")); } sourceFolderToCopy = PathToFileOrFolder; } FileUtils.CopyDirectoryRecursively(sourceFolderToCopy, SessionPath.ToContent, filesToExclude: FilesToExclude, foldersToExclude: AllStockFoldersToExclude, doContainsSearch: false); if (IsZipFileImport && Directory.Exists(PathToTempUnzipFolder)) { // remove unzipped temp files Directory.Delete(PathToTempUnzipFolder, true); } else if (isReimport == false) { // make .meta file to tag where the imported map came from to support the 'Re-import' feature string mapName = MetaDataManager.GetMapFileNameFromFolder(sourceFolderToCopy); BoolWithMessage result = MetaDataManager.TrackMapLocation(mapName, sourceFolderToCopy); } return(new BoolWithMessage(true)); }); return(task); }
public static BoolWithMessage DeleteFiles(List <string> filesToDelete) { try { HashSet <string> possibleFoldersToDelete = new HashSet <string>(); // this will be a list of directories where files were deleted; if these directories are empty then they will also be deleted foreach (string file in filesToDelete) { if (File.Exists(file)) { FileInfo fileInfo = new FileInfo(file); if (possibleFoldersToDelete.Contains(fileInfo.DirectoryName) == false) { possibleFoldersToDelete.Add(fileInfo.DirectoryName); } File.Delete(file); } } // delete the possible empty directories foreach (string folder in possibleFoldersToDelete) { // iteratively go up parent folder structure to delete empty folders after files have been deleted string currentDir = folder; if (Directory.Exists(currentDir) && currentDir != SessionPath.ToContent) { List <string> remainingFiles = GetAllFilesInDirectory(currentDir); while (remainingFiles.Count == 0 && currentDir != SessionPath.ToContent) { string dirToDelete = currentDir; DirectoryInfo dirInfo = new DirectoryInfo(currentDir); currentDir = dirInfo.Parent.FullName; // get path to parent directory to check next Directory.Delete(dirToDelete, true); if (currentDir != SessionPath.ToContent) { remainingFiles = GetAllFilesInDirectory(currentDir); // get list of files from parent dir to check next } } } } return(BoolWithMessage.True()); } catch (Exception e) { return(BoolWithMessage.False($"Failed to delete files: {e.Message}")); } }
public bool UpdateGameSettings() { string returnMessage = ""; BoolWithMessage didSetSettings = GameSettingsManager.UpdateGameSettings(SkipMovieIsChecked, DBufferIsChecked); BoolWithMessage didSetObjCount = BoolWithMessage.True(); // set to true by default in case the user does not have the file to modify BoolWithMessage didSetVideoSettings = ValidateAndUpdateVideoSettings(); if (GameSettingsManager.DoesInventorySaveFileExist()) { didSetObjCount = GameSettingsManager.ValidateAndUpdateObjectCount(ObjectCountText); if (didSetObjCount.Result == false) { returnMessage += didSetObjCount.Message; } } if (didSetSettings.Result == false) { returnMessage += didSetSettings.Message; } if (didSetVideoSettings.Result == false) { returnMessage += didSetVideoSettings.Message; } if (!didSetVideoSettings.Result || !didSetSettings.Result) { MessageService.Instance.ShowMessage(returnMessage); return(false); } returnMessage = "Game settings updated!"; if (GameSettingsManager.DoesInventorySaveFileExist() == false) { returnMessage += " Object count cannot be changed until a .sav file exists."; } if (SessionPath.IsSessionRunning()) { returnMessage += " Restart the game for changes to take effect."; } MessageService.Instance.ShowMessage(returnMessage); return(didSetSettings.Result && didSetObjCount.Result && didSetVideoSettings.Result); }
public void Test_ExtractZipFile_InvalidFile_ReturnsFalse() { string pathToZip = Path.Combine(TestPaths.ToTestFilesFolder, "NotAZip.zip"); string extractPath = Path.Combine(TestPaths.ToTestFilesFolder, "TestDir"); BoolWithMessage result = FileUtils.ExtractZipFile(pathToZip, extractPath); Assert.IsFalse(result.Result); }
private void btnAdd_Click(object sender, RoutedEventArgs e) { BoolWithMessage didAdd = ViewModel.AddAsset(); if (didAdd.Result) { lstAssets.ScrollIntoView(ViewModel.SelectedAsset); } else { MessageBox.Show(didAdd.Message, "Failed To Add", MessageBoxButton.OK, MessageBoxImage.Error); } }
private void BtnRename_Click(object sender, RoutedEventArgs e) { BoolWithMessage renameResult = ViewModel.ValidateAndSetCustomName(); if (renameResult.Result) { this.DialogResult = true; this.Close(); } else { MessageBox.Show(renameResult.Message, "Error Renaming!", MessageBoxButton.OK, MessageBoxImage.Error); } }
public BoolWithMessage OpenPreviewUrlInBrowser() { if (String.IsNullOrEmpty(PreviewUrl)) { return(BoolWithMessage.False("No preview url for this map.")); } ProcessStartInfo info = new ProcessStartInfo() { FileName = this.PreviewUrl }; Process.Start(info); return(BoolWithMessage.True()); }
/// <summary> /// Runs avantgarde updater which will exit the application to run a seperate console app that downloads /// and copies the latest files. /// </summary> public static BoolWithMessage UpdateApplication() { if (IsUpdateAvailable()) { try { UpdaterInstance.Update(); } catch (Exception e) { Logger.Error(e, "failed to launch update process"); return(BoolWithMessage.False($"An error occurred while trying to update: {e.Message}")); } } return(BoolWithMessage.True()); }
public BoolWithMessage ImportCatalog(string pathToCatalog) { try { AssetCatalog catalog = JsonConvert.DeserializeObject <AssetCatalog>(File.ReadAllText(pathToCatalog)); AssetList = new ObservableCollection <AssetViewModel>(catalog.Assets.Select(a => new AssetViewModel(a)).ToList()); ClearSelectedAsset(); CatalogName = catalog.Name; return(BoolWithMessage.True()); } catch (Exception e) { return(BoolWithMessage.False($"Failed to import catalog: {e.Message}")); } }
private void BtnUpdate_Click(object sender, RoutedEventArgs e) { ViewModel.HeaderMessage = "Updating app ..."; BoolWithMessage updateResult = null; Task updateTask = Task.Factory.StartNew(() => { updateResult = VersionChecker.UpdateApplication(); }); updateTask.ContinueWith((updateAntecedent) => { if (updateResult?.Result == false) { System.Windows.MessageBox.Show(updateResult.Message, "Error Updating!", MessageBoxButton.OK, MessageBoxImage.Error); } }); }
/// <summary> /// Deletes the selected asset files from Session folders /// </summary> public void RemoveSelectedAsset() { AssetViewModel assetToRemove = SelectedAsset; BoolWithMessage deleteResult = BoolWithMessage.False(""); if (assetToRemove.AssetCategory == AssetCategory.Maps.Value) { MapMetaData mapToDelete = MetaDataManager.GetAllMetaDataForMaps()?.Where(m => m.AssetName == assetToRemove.Asset.ID).FirstOrDefault(); if (mapToDelete == null) { UserMessage = "Failed to find meta data to delete map files ..."; return; } deleteResult = MetaDataManager.DeleteMapFiles(mapToDelete); } else { TextureMetaData textureToDelete = MetaDataManager.GetTextureMetaDataByName(assetToRemove.Asset.ID); if (textureToDelete == null) { UserMessage = $"Failed to find meta data to delete texture files for {assetToRemove.Asset.ID}..."; return; } deleteResult = MetaDataManager.DeleteTextureFiles(textureToDelete); } UserMessage = deleteResult.Message; if (deleteResult.Result) { RefreshPreviewForSelected(); // refresh list if filtering by installed or uninstalled if (SelectedInstallStatus != defaultInstallStatusValue) { RefreshFilteredAssetList(); } } }
private void btnExport_Click(object sender, RoutedEventArgs e) { using (System.Windows.Forms.SaveFileDialog fileBrowserDialog = new System.Windows.Forms.SaveFileDialog()) { fileBrowserDialog.Filter = "Catalog Json (*.json)|*.json"; fileBrowserDialog.Title = "Save Asset Catalog Json File"; System.Windows.Forms.DialogResult result = fileBrowserDialog.ShowDialog(); if (result == System.Windows.Forms.DialogResult.OK) { BoolWithMessage didSave = ViewModel.ExportCatalog(fileBrowserDialog.FileName); if (!didSave.Result) { MessageBox.Show(didSave.Message, "Failed to Export", MessageBoxButton.OK, MessageBoxImage.Error); } } } }
public void RefreshGameSettings() { BoolWithMessage result = GameSettingsManager.RefreshGameSettingsFromIniFiles(); if (result.Result == false) { MessageService.Instance.ShowMessage(result.Message); } ObjectCountText = GameSettingsManager.ObjectCount.ToString(); SkipMovieIsChecked = GameSettingsManager.SkipIntroMovie; DBufferIsChecked = GameSettingsManager.EnableDBuffer; ShadowQualityText = ((VideoSettingsOptions)GameSettingsManager.ShadowQuality).ToString(); AntiAliasingText = ((VideoSettingsOptions)GameSettingsManager.AntiAliasingQuality).ToString(); TexturesQualityText = ((VideoSettingsOptions)GameSettingsManager.TextureQuality).ToString(); ViewDistanceQualityText = ((VideoSettingsOptions)GameSettingsManager.ViewDistanceQuality).ToString(); ShadingQualityText = ((VideoSettingsOptions)GameSettingsManager.ShadowQuality).ToString(); FoliageQualityText = ((VideoSettingsOptions)GameSettingsManager.FoliageQuality).ToString(); EffectsQualityText = ((VideoSettingsOptions)GameSettingsManager.EffectsQuality).ToString(); PostProcessingText = ((VideoSettingsOptions)GameSettingsManager.PostProcessQuality).ToString(); FullScreenMode = FullscreenDropdownOptions[GameSettingsManager.FullscreenMode]; if (string.IsNullOrEmpty(GameSettingsManager.ResolutionSizeX) && string.IsNullOrEmpty(GameSettingsManager.ResolutionSizeY)) { ResolutionText = "Match Desktop Resolution"; } else if (ResolutionDropdownOptions.Any(r => r == $"{GameSettingsManager.ResolutionSizeX}x{GameSettingsManager.ResolutionSizeY}")) { ResolutionText = $"{GameSettingsManager.ResolutionSizeX}x{GameSettingsManager.ResolutionSizeY}"; CustomResolutionText = $"{GameSettingsManager.ResolutionSizeX}x{GameSettingsManager.ResolutionSizeY}"; } else { ResolutionText = "Custom"; CustomResolutionText = $"{GameSettingsManager.ResolutionSizeX}x{GameSettingsManager.ResolutionSizeY}"; } FrameRateLimitText = GameSettingsManager.FrameRateLimit.ToString(); IsVsyncEnabled = GameSettingsManager.EnableVsync; }
public static void DeleteFilesInEnvFolder() { if (!IsLoaded()) { return; // not loaded so no files to delete } try { BoolWithMessage result = FileUtils.DeleteFiles(LoadedToolsuiteFiles); if (!result.Result) { Logger.Warn($"Failed to delete RMS files: {result.Message}"); } } catch (Exception e) { Logger.Error(e); } }
public void RemoveSelectedTexture() { InstalledTextureItemViewModel textureToRemove = SelectedTexture; if (textureToRemove == null) { Logger.Warn("textureToRemove is null"); return; } BoolWithMessage deleteResult = MetaDataManager.DeleteTextureFiles(textureToRemove.MetaData); if (deleteResult.Result) { StatusMessage = $"Successfully removed {textureToRemove.TextureName}!"; InitInstalledTextures(); } else { StatusMessage = $"Failed to remove texture: {deleteResult.Message}"; } }
public BoolWithMessage ExportCatalog(string savePath) { try { UpdateAsset(SelectedAsset); // ensure the currently selected asset is updated before writing to file AssetCatalog catalog = new AssetCatalog() { Name = CatalogName, Assets = AssetList.Select(a => a.Asset).ToList() }; string fileContents = JsonConvert.SerializeObject(catalog, Formatting.Indented); File.WriteAllText(savePath, fileContents); return(BoolWithMessage.True()); } catch (Exception e) { return(BoolWithMessage.False($"Failed to export catalog: {e.Message}")); } }
public BoolWithMessage BeginDownloadInBrowser() { if (String.IsNullOrEmpty(DownloadUrl)) { return(BoolWithMessage.False("No direct download url for this map.")); } try { string directDownloadLink = DownloadUtils.GetDirectDownloadLinkFromAnonPage(this.DownloadUrl); ProcessStartInfo info = new ProcessStartInfo() { FileName = directDownloadLink }; Process.Start(info); } catch (Exception e) { return(BoolWithMessage.False($"Could not initiate download from browser: {e.Message}")); } return(BoolWithMessage.True()); }
public void Test_ExtractRarFiles_ExtractsCorrectly() { string pathToZip = "C:\\Users\\Adam\\Downloads\\Skate3.rar"; string extractPath = "C:\\Users\\Adam\\Documents\\TestDir"; if (Directory.Exists(extractPath)) { Directory.Delete(extractPath, true); } Directory.CreateDirectory(extractPath); BoolWithMessage result = FileUtils.ExtractRarFile(pathToZip, extractPath); Assert.IsTrue(result.Result); bool extractedFileExists = File.Exists($"{extractPath}\\Skate3\\BlackBoxPark\\Tex\\1.uasset"); Assert.IsTrue(extractedFileExists); bool mapDirExists = Directory.Exists($"{extractPath}\\Skate3\\Maps"); Assert.IsTrue(mapDirExists); }
internal Task <BoolWithMessage> ImportMapAsync() { Task <BoolWithMessage> task = Task.Factory.StartNew(() => { List <string> filesCopied; IProgress <double> progress = new Progress <double>(percent => this.ImportProgress = percent * 100); if (IsZipFileImport) { // extract compressed file to correct location if (File.Exists(PathToFileOrFolder) == false) { return(BoolWithMessage.False($"{PathToFileOrFolder} does not exist.")); } if (!FileUtils.CompressedFileHasFile(PathToFileOrFolder, ".umap", FileUtils.SearchType.EndsWith)) { return(BoolWithMessage.False($"{PathToFileOrFolder} does not contain a valid .umap file to import.")); } this.ImportProgress = 0; try { if (FileUtils.CompressedFileHasFile(PathToFileOrFolder, "Content/", FileUtils.SearchType.StartsWith) || FileUtils.CompressedFileHasFile(PathToFileOrFolder, "Content\\", FileUtils.SearchType.StartsWith)) { // extract files to SessionGame/ instead if the zipped up root folder is 'Content/' filesCopied = FileUtils.ExtractCompressedFile(PathToFileOrFolder, SessionPath.ToSessionGame, progress); } else { filesCopied = FileUtils.ExtractCompressedFile(PathToFileOrFolder, SessionPath.ToContent, progress); } string relativePathData = Path.Combine("Content", "Data"); if (filesCopied.Any(f => f.Contains(relativePathData))) { Logger.Info("Checking for files extracted to Data folder ..."); for (int i = filesCopied.Count - 1; i >= 0; i--) { if (filesCopied[i].Contains(relativePathData) && File.Exists(filesCopied[i])) { File.Delete(filesCopied[i]); filesCopied.RemoveAt(i); } } } } catch (Exception e) { Logger.Error(e, "failed to extract file"); UserMessage = $"Failed to extract file: {e.Message}"; return(BoolWithMessage.False($"Failed to extract: {e.Message}.")); } } else { // validate folder exists and contains a valid map file if (Directory.Exists(PathToFileOrFolder) == false) { return(BoolWithMessage.False($"{PathToFileOrFolder} does not exist.")); } if (!MetaDataManager.DoesValidMapExistInFolder(PathToFileOrFolder)) { return(BoolWithMessage.False($"{PathToFileOrFolder} does not contain a valid .umap file to import.")); } filesCopied = FileUtils.CopyDirectoryRecursively(PathToFileOrFolder, SessionPath.ToContent, filesToExclude: FilesToExclude, foldersToExclude: StockFoldersToExclude, doContainsSearch: false, progress); } // create meta data for new map and save to disk MapMetaData metaData = GenerateMetaData(filesCopied); MetaDataManager.SaveMapMetaData(metaData); return(BoolWithMessage.True()); }); return(task); }
private BoolWithMessage ValidateAndUpdateVideoSettings() { if (!int.TryParse(FrameRateLimitText, out int frameRate)) { return(BoolWithMessage.False("Frame Rate must be a valid number between 10 and 999")); } if (frameRate < 10 || frameRate > 999) { return(BoolWithMessage.False("Frame Rate must be a valid number between 10 and 999")); } if (ResolutionText == "Match Desktop Resolution") { GameSettingsManager.ResolutionSizeX = null; GameSettingsManager.ResolutionSizeY = null; } else if (ResolutionText == "Custom") { string[] res = CustomResolutionText.Split(new char[] { 'x' }, StringSplitOptions.RemoveEmptyEntries); if (res.Length != 2) { return(BoolWithMessage.False("Custom resolution invalid. Must be in format '1920x1080'")); } if (!int.TryParse(res[0], out int customResX) || !int.TryParse(res[1], out int customResY)) { return(BoolWithMessage.False("Custom resolution invalid. Must be in format '1920x1080'")); } if (customResX <= 0 || customResY <= 0) { return(BoolWithMessage.False("Custom resolution invalid. Must be in format '1920x1080'")); } GameSettingsManager.ResolutionSizeX = res[0]; GameSettingsManager.ResolutionSizeY = res[1]; } else { string[] res = ResolutionText.Split(new char[] { 'x' }, StringSplitOptions.RemoveEmptyEntries); GameSettingsManager.ResolutionSizeX = res[0]; GameSettingsManager.ResolutionSizeY = res[1]; } GameSettingsManager.EnableVsync = IsVsyncEnabled; GameSettingsManager.FrameRateLimit = frameRate; Enum.TryParse(AntiAliasingText, out VideoSettingsOptions setting); GameSettingsManager.AntiAliasingQuality = (int)setting; Enum.TryParse(ShadowQualityText, out setting); GameSettingsManager.ShadowQuality = (int)setting; Enum.TryParse(ShadingQualityText, out setting); GameSettingsManager.ShadingQuality = (int)setting; Enum.TryParse(TexturesQualityText, out setting); GameSettingsManager.TextureQuality = (int)setting; Enum.TryParse(ViewDistanceQualityText, out setting); GameSettingsManager.ViewDistanceQuality = (int)setting; Enum.TryParse(FoliageQualityText, out setting); GameSettingsManager.FoliageQuality = (int)setting; Enum.TryParse(EffectsQualityText, out setting); GameSettingsManager.EffectsQuality = (int)setting; Enum.TryParse(PostProcessingText, out setting); GameSettingsManager.PostProcessQuality = (int)setting; GameSettingsManager.FullscreenMode = FullscreenDropdownOptions.IndexOf(FullScreenMode); return(GameSettingsManager.SaveVideoSettingsToDisk()); }
internal void ReplaceTextures() { if (IsPathValid() == false) { return; } FileInfo textureFileInfo = null; if (IsPathToZip) { Directory.CreateDirectory(PathToTempFolder); // extract to temp location BoolWithMessage didExtract = FileUtils.ExtractZipFile(PathToFile, PathToTempFolder); if (didExtract.Result == false) { MessageChanged?.Invoke($"Failed to extract .zip file: {didExtract.Message}"); return; } string foundTextureName = FindTextureFileInUnzippedTempFolder(); if (foundTextureName == "") { MessageChanged?.Invoke($"Failed to find a .uasset file inside the .zip"); return; } textureFileInfo = new FileInfo(foundTextureName); } else { textureFileInfo = new FileInfo(PathToFile); } // find which folder to copy to based on file name string targetFolder = GetFolderPathToTexture(textureFileInfo.NameWithoutExtension()); if (targetFolder == "") { MessageChanged?.Invoke($"Failed to find path to original texture: {textureFileInfo.Name}"); return; } try { // find and copy files that match the .uasset name string textureDirectory = Path.GetDirectoryName(textureFileInfo.FullName); foreach (string file in Directory.GetFiles(textureDirectory)) { if (file.Contains(textureFileInfo.NameWithoutExtension())) { FileInfo foundFile = new FileInfo(file); string targetPath = Path.Combine(targetFolder, foundFile.Name); File.Copy(file, targetPath, overwrite: true); } } // delete temp folder with unzipped files if (IsPathToZip) { if (Directory.Exists(PathToTempFolder)) { Directory.Delete(PathToTempFolder, true); } } } catch (Exception e) { MessageChanged?.Invoke($"Failed to copy texture files: {e.Message}"); return; } MessageChanged?.Invoke($"Successfully replaced textures for {textureFileInfo.Name}!"); }
/// <summary> /// Handles the entire unpacking process /// ... download zip file /// ... extract zip file /// ... run UnrealPak.exe /// ... copy unpacked files to Session folder /// </summary> internal void StartUnpackingAsync(string pathToSession) { this.PathToSession = pathToSession; bool didDownload = false; // download the zip file in the background Task t = Task.Factory.StartNew(() => { didDownload = DownloadZipFile(); }); t.ContinueWith((task) => { if (didDownload == false) { UnpackCompleted(false); return; } ProgressChanged("Extracting .zip file ..."); BoolWithMessage isExtracted = FileUtils.ExtractZipFile($"{PathToPakFolder}\\{DownloadedZipFileName}", PathToPakFolder); if (isExtracted.Result == false) { ProgressChanged($"Failed to unzip file: {isExtracted.Message}. Cannot continue."); UnpackCompleted(false); return; } bool runSuccess = true;; Task waitTask = Task.Factory.StartNew(() => { try { RunUnrealPakBatFile(); // this will wait for UnrealPak to finish } catch (Exception e) { ProgressChanged($"Failed to run UnrealPak.exe : {e.Message}. Cannot continue"); runSuccess = false; } }); waitTask.ContinueWith((unrealTask) => { if (runSuccess == false) { UnpackCompleted(false); return; } // validate files were unpacked by checking subset of expected folders List <string> expectedDirs = new List <string>() { "\\out\\SessionGame\\Config", "\\out\\SessionGame\\Content", "\\out\\SessionGame\\Content\\Customization" }; foreach (string dir in expectedDirs) { if (Directory.Exists($"{PathToPakFolder}{dir}") == false) { ProgressChanged($"Failed to unpack files correctly. The expected folders were not found ({PathToPakFolder}{dir}). Cannot continue."); UnpackCompleted(false); return; } } bool didCopy = CopyUnpackedFilesToSession(); UnpackCompleted(didCopy); }); }); }
/// <summary> /// Handles the entire unpacking process /// ... download zip file /// ... extract zip file /// ... run UnrealPak.exe /// ... copy unpacked files to Session folder /// </summary> internal void StartUnpackingAsync(string pathToSession) { this.PathToSession = pathToSession; bool didDownload = false; // download the zip file in the background Task t = Task.Factory.StartNew(() => { didDownload = DownloadZipFile(); }); t.ContinueWith((task) => { if (didDownload == false) { UnpackCompleted(false); return; } ProgressChanged("Extracting .zip file ..."); BoolWithMessage isExtracted = FileUtils.ExtractZipFile(Path.Combine(PathToPakFolder, DownloadedZipFileName), PathToPakFolder); if (isExtracted.Result == false) { ProgressChanged($"Failed to unzip file: {isExtracted.Message}. Cannot continue."); UnpackCompleted(false); return; } bool runSuccess = true;; Task waitTask = Task.Factory.StartNew(() => { try { RunUnrealPakExe(); // this will wait for UnrealPak to finish } catch (Exception e) { ProgressChanged($"Failed to run UnrealPak.exe : {e.Message}. Cannot continue"); runSuccess = false; } }); waitTask.ContinueWith((unrealTask) => { if (runSuccess == false) { UnpackCompleted(false); return; } bool didRename = RenamePakFile(); if (didRename == false) { ProgressChanged("Unpacking complete, but failed to rename the .pak file."); UnpackCompleted(false); } // validate files were unpacked by checking subset of expected folders List <string> expectedDirs = new List <string>() { Path.Combine("SessionGame", "Config"), Path.Combine("SessionGame", "Content"), Path.Combine("SessionGame", "Content", "Customization") }; foreach (string dir in expectedDirs) { if (Directory.Exists(Path.Combine(PathToSession, dir)) == false) { ProgressChanged($"Failed to unpack files correctly. The expected folders were not found ({Path.Combine(PathToSession, dir)}). Cannot continue."); UnpackCompleted(false); return; } } // delete the original backed up map files so new unpacked files are backedup DeleteOriginalMapFileBackup(); UnpackCompleted(true); }); }); }
private BoolWithMessage UpdateAsset(AssetViewModel assetToUpdate) { if (assetToUpdate == null) { return(BoolWithMessage.False("assetToUpdate is null")); } string validationMsg = ValidateAssetInfo(assetToUpdate); if (!string.IsNullOrEmpty(validationMsg)) { UpdatedAssetInvalid?.Invoke(validationMsg); return(BoolWithMessage.False(validationMsg)); } if (SelectedAssetDownloadType == "Url") { assetToUpdate.Asset.DownloadLink = AssetCatalog.FormatUrl(SelectedAssetDownloadUrl); } else if (SelectedAssetDownloadType == "Google Drive") { assetToUpdate.Asset.DownloadLink = $"rsmm://GDrive/{SelectedAssetDownloadUrl}"; } else if (SelectedAssetDownloadType == "Mega") { assetToUpdate.Asset.DownloadLink = $"rsmm://MegaFile/{SelectedAssetDownloadUrl}"; } assetToUpdate.Asset.ID = $"{SelectedAssetID}{SelectedIDExtension}"; assetToUpdate.Asset.Name = SelectedAssetName; assetToUpdate.Asset.Author = SelectedAssetAuthor; assetToUpdate.Asset.Category = SelectedAssetCategory; assetToUpdate.Asset.Description = SelectedAssetDescription; assetToUpdate.Asset.PreviewImage = SelectedAssetImageUrl; double.TryParse(SelectedAssetVersion, out double version); if (version <= 0) { assetToUpdate.Asset.Version = 1; } else { assetToUpdate.Asset.Version = version; } DateTime.TryParse(SelectedAssetUpdatedDate, out DateTime updateDate); if (updateDate != DateTime.MinValue) { assetToUpdate.Asset.UpdatedDate = updateDate.ToUniversalTime(); } else if (string.IsNullOrWhiteSpace(SelectedAssetUpdatedDate)) { assetToUpdate.Asset.UpdatedDate = DateTime.UtcNow; } assetToUpdate.Name = assetToUpdate.Asset.Name; assetToUpdate.Author = assetToUpdate.Asset.Author; assetToUpdate.AssetCategory = assetToUpdate.Asset.Category; assetToUpdate.Version = assetToUpdate.Asset.Version.ToString(); assetToUpdate.UpdatedDate = assetToUpdate.Asset.UpdatedDate.ToLocalTime().ToString(AssetViewModel.dateTimeFormat); assetToUpdate.Description = assetToUpdate.Asset.Description; return(BoolWithMessage.True()); }
internal Task <BoolWithMessage> ImportMapAsync() { Task <BoolWithMessage> task = Task.Factory.StartNew(() => { string sourceFolderToCopy; if (IsZipFileImport) { // extract compressed file before copying if (File.Exists(PathToFileOrFolder) == false) { return(BoolWithMessage.False($"{PathToFileOrFolder} does not exist.")); } // extract files first before copying BoolWithMessage didExtract = BoolWithMessage.False(""); try { Directory.CreateDirectory(PathToTempUnzipFolder); didExtract = FileUtils.ExtractCompressedFile(PathToFileOrFolder, PathToTempUnzipFolder); } catch (Exception e) { Logger.Error(e, "failed to extract zip"); didExtract.Message = e.Message; } if (didExtract.Result == false) { UserMessage = $"Failed to extract file: {didExtract.Message}"; return(BoolWithMessage.False($"Failed to extract: {didExtract.Message}.")); } sourceFolderToCopy = EnsurePathToMapFilesIsCorrect(PathToTempUnzipFolder); } else { // validate folder exists and contains a valid map file if (Directory.Exists(PathToFileOrFolder) == false) { return(BoolWithMessage.False($"{PathToFileOrFolder} does not exist.")); } sourceFolderToCopy = PathToFileOrFolder; bool hasValidMap = MetaDataManager.DoesValidMapExistInFolder(sourceFolderToCopy); if (hasValidMap == false) { return(BoolWithMessage.False($"{PathToFileOrFolder} does not contain a valid .umap file to import.")); } } // create meta data for new map and save to disk MapMetaData metaData = MetaDataManager.CreateMapMetaData(sourceFolderToCopy, true); if (AssetToImport != null) { metaData.AssetName = AssetToImport.ID; } if (IsZipFileImport == false && metaData != null) { metaData.OriginalImportPath = sourceFolderToCopy; } MetaDataManager.SaveMapMetaData(metaData); // copy/move files if (IsZipFileImport) { FileUtils.MoveDirectoryRecursively(sourceFolderToCopy, SessionPath.ToContent, filesToExclude: FilesToExclude, foldersToExclude: AllStockFoldersToExclude, doContainsSearch: false); } else { FileUtils.CopyDirectoryRecursively(sourceFolderToCopy, SessionPath.ToContent, filesToExclude: FilesToExclude, foldersToExclude: AllStockFoldersToExclude, doContainsSearch: false); } if (IsZipFileImport && Directory.Exists(PathToTempUnzipFolder)) { // remove unzipped temp files Directory.Delete(PathToTempUnzipFolder, true); } return(BoolWithMessage.True()); }); return(task); }