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());
        }
        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 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());
    }
Beispiel #5
0
        /// <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}"));
            }
        }
        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());
    }
        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(() =>
            {
                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);
        }
Beispiel #11
0
        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);
        }