コード例 #1
0
        public void ExtractFile(string sourceArchiveName, string fileToExtract, string destinationDirectoryName)
        {
            //TODO: Wrap in using?
            var zip          = zipFileProxy.Open(sourceArchiveName, ZipArchiveMode.Read);
            var zipFileEntry = zip.Entries.FirstOrDefault(entry => entry.FullName.Equals(fileToExtract));

            if (zipFileEntry == null)
            {
                throw new FileNotFoundInArchiveException();
            }

            var absoluteFileExtractionPath = Path.Combine(destinationDirectoryName, fileToExtract);

            if (fileProxy.Exists(absoluteFileExtractionPath))
            {
                var result = AskForUserPermission(new[] { absoluteFileExtractionPath });

                if (result != MessageBoxResult.Yes)
                {
                    return;
                }
            }

            zipFileProxy.ExtractToFile(zipFileEntry, absoluteFileExtractionPath, true);
        }
コード例 #2
0
        public bool CanRun()
        {
            // Check various requirements
            var saveGame = options.CurrentConverter.RequiredItems.First(i => i.TagName.Equals("SaveGame"));

            if (saveGame == null || !fileProxy.Exists(saveGame.SelectedValue))
            {
                return(false);
            }

            if (fileProxy.Exists(options.CurrentConverter.AbsoluteConverter.SelectedValue))
            {
                return(true);
            }

            return(false);
        }
コード例 #3
0
        private IEnumerable <Comic> ReadSerializedComics()
        {
            var json = file.Exists(appSettings.ComicsFile) ?
                       file.ReadAllText(appSettings.ComicsFile) :
                       "";

            var comics = JsonConvert.DeserializeObject <Comic[]>(json) ?? new Comic[0];

            return(comics);
        }
コード例 #4
0
        public string ReadTextFile(string path)
        {
            if (!fileProxy.Exists(path))
            {
                return(string.Empty);
            }

            var text = fileProxy.ReadAllText(path);

            return(text);
        }
コード例 #5
0
        private string[] Download(IEnumerable <Uri> links, Context context)
        {
            var downloadedFiles = new List <string>();

            foreach (var link in links)
            {
                var downloadPath = comicPath.DownloadPathFor(context.ComicId, link);

                ReportStripDownloading(link, downloadPath, context);
                if (
                    file.Exists(comicPath.DownloadPathForPreviousIndex(context.ComicId, link)) ||
                    file.Exists(downloadPath)
                    )
                {
                    ReportStripAlreadyDownloaded(link, context);
                    continue;
                }

                try
                {
                    downloader.Download(link, downloadPath);
                }
                catch (WebException ex)
                {
                    Warn(context, ex.Message);
                    continue;
                }

                downloadedFiles.Add(downloadPath);
                ReportStripDownloaded(link, context);

                EmbedMetadataIfEnabled(downloadPath, context);

                Sleep(context);
            }

            return(downloadedFiles.ToArray());
        }
コード例 #6
0
        public OperationResult MoveModFileAndFolder()
        {
            var operationResult = new OperationResult();

            // NOTE: This method may be V2 specific. I'll have to talk to Idhrendur about the rules for how this is/will be handled in other converters.
            // I'll figure out some generic way of handling any problems related to that when and if it occurs.

            var targetGameModPathItem =
                options.CurrentConverter.RequiredItems.First(i => i.InternalTagName.Equals("targetGameModPath"));
            var desiredFileName =
                folderProxy.GetFileNameWithoutExtension(options.CurrentConverter.AbsoluteSourceSaveGame.SelectedValue) +
                options.CurrentConverter.TargetGame.SaveGameExtension;

            if (options.CurrentConverter.Categories != null)
            {
                var activeConfiguration = options.CurrentConverter.Categories.First(c => c.FriendlyName == "Configuration");
                if (activeConfiguration != null)
                {
                    var outputName = activeConfiguration.Preferences.FirstOrDefault(d => d.Name == "output_name");
                    if (outputName != null)
                    {
                        var grabbedName = outputName.ToString();
                        int index1      = grabbedName.IndexOf("\"");
                        int index2      = grabbedName.LastIndexOf("\"");
                        if (index2 - index1 > 1)
                        {
                            grabbedName     = grabbedName.Substring(index1 + 1, index2 - index1 - 1);
                            desiredFileName = grabbedName;
                        }

                        operationResult.LogEntries.Add(new LogEntry("Output name: " + desiredFileName,
                                                                    LogEntrySeverity.Info, LogEntrySource.UI));
                    }
                }
            }


            // This is savegame normalization. It strips accents in a fashion compatible with the converter.

            var normalizedString = desiredFileName.Normalize(NormalizationForm.FormD);
            var stringBuilder    = new StringBuilder();

            foreach (var c in normalizedString)
            {
                var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c);
                if (unicodeCategory != UnicodeCategory.NonSpacingMark)
                {
                    stringBuilder.Append(c);
                }
            }
            desiredFileName = stringBuilder.ToString().Normalize(NormalizationForm.FormC);

            // Here we transliterate the name in case Normalize failed to do it's job (cyrillic letters won't normalize at all in frontend, unlike converter)
            // This produces questionmarks for non-normalizable characters, which we replace with zeroes, same as the converter does.

            byte[] unicodeBytes = Encoding.Unicode.GetBytes(desiredFileName);
            byte[] asciiBytes   = Encoding.Convert(Encoding.Unicode, Encoding.ASCII, unicodeBytes);
            desiredFileName = Encoding.ASCII.GetString(asciiBytes);
            desiredFileName = desiredFileName.Replace('?', '0');
            operationResult.LogEntries.Add(new LogEntry("Mod to be copied: ", LogEntrySeverity.Info, LogEntrySource.UI, desiredFileName));

            var translatedSaveGameName = nameTranslator.TranslateName(desiredFileName);

            // Copy the newly created output mod to the target game mod directory.
            // The mod consists of two things: One file and one folder named after the save. Ex: The folder "France144_11_11" and the file "France144_11_11.mod".
            var converterWorkingDirectory = directoryHelper.GetConverterWorkingDirectory(options.CurrentConverter);
            var outputModFolderSourcePath = folderProxy.Combine(converterWorkingDirectory, "output",
                                                                translatedSaveGameName);
            var outputModFileSourcePath = folderProxy.Combine(converterWorkingDirectory, "output",
                                                              (translatedSaveGameName + ".mod"));

            var expectedAbsoluteOutputModFolderTargetPath = folderProxy.Combine(targetGameModPathItem.SelectedValue,
                                                                                translatedSaveGameName);
            var expectedAbsoluteOutputModFileTargetPath = expectedAbsoluteOutputModFolderTargetPath + ".mod";

            var modFileExists   = fileProxy.Exists(expectedAbsoluteOutputModFileTargetPath);
            var modFolderExists = folderProxy.Exists(expectedAbsoluteOutputModFolderTargetPath);

            if (modFileExists || modFolderExists)
            {
                var confirmationMessage =
                    string.Format("One or more parts of the output mod exists in {0} already. Overwrite?",
                                  targetGameModPathItem.SelectedValue);
                var result = messageBoxProxy.Show(confirmationMessage, "Confirmation Required", MessageBoxButton.YesNo);

                if (result == MessageBoxResult.No)
                {
                    operationResult.State = OperationResultState.Warning;
                    return(operationResult);
                }
            }

            try
            {
                fileProxy.Copy(outputModFileSourcePath, expectedAbsoluteOutputModFileTargetPath, true);
                directoryCopyHelper.DirectoryCopy(outputModFolderSourcePath, expectedAbsoluteOutputModFolderTargetPath,
                                                  true, true);

                operationResult.LogEntries.Add(new LogEntry("Mod copied to: ", LogEntrySeverity.Info, LogEntrySource.UI,
                                                            expectedAbsoluteOutputModFolderTargetPath));
            }
            catch (Exception e)
            {
                operationResult.LogEntries.Add(new LogEntry(e.Message, LogEntrySeverity.Error, LogEntrySource.UI));
                operationResult.State = OperationResultState.Error;
            }

            return(operationResult);
        }
コード例 #7
0
 public bool CanRun()
 {
     return(fileProxy.Exists(options.CurrentConverter.AbsoluteSourceSaveGame.SelectedValue));
 }
コード例 #8
0
        public static void StartPaketBootstrapping(IDownloadStrategy downloadStrategy, DownloadArguments dlArgs, IFileProxy fileProxy, Action onSuccess)
        {
            Action <Exception> handleException = exception =>
            {
                if (!fileProxy.Exists(dlArgs.Target))
                {
                    Environment.ExitCode = 1;
                }
                ConsoleImpl.WriteError(String.Format("{0} ({1})", exception.Message, downloadStrategy.Name));
            };

            try
            {
                string versionRequested;
                if (!dlArgs.IgnorePrerelease)
                {
                    versionRequested = "prerelease requested";
                }
                else if (String.IsNullOrWhiteSpace(dlArgs.LatestVersion))
                {
                    versionRequested = "downloading latest stable";
                }
                else
                {
                    versionRequested = string.Format("version {0} requested", dlArgs.LatestVersion);
                }

                ConsoleImpl.WriteDebug("Checking Paket version ({0})...", versionRequested);

                var localVersion = fileProxy.GetLocalFileVersion(dlArgs.Target);

                var specificVersionRequested = true;
                var latestVersion            = dlArgs.LatestVersion;

                if (latestVersion == String.Empty)
                {
                    latestVersion            = downloadStrategy.GetLatestVersion(dlArgs.IgnorePrerelease);
                    specificVersionRequested = false;
                }

                if (dlArgs.DoSelfUpdate)
                {
                    ConsoleImpl.WriteDebug("Trying self update");
                    downloadStrategy.SelfUpdate(latestVersion);
                }
                else
                {
                    var currentSemVer = String.IsNullOrEmpty(localVersion) ? new SemVer() : SemVer.Create(localVersion);
                    if (currentSemVer.PreRelease != null && dlArgs.IgnorePrerelease)
                    {
                        currentSemVer = new SemVer();
                    }
                    var latestSemVer = SemVer.Create(latestVersion);
                    var comparison   = currentSemVer.CompareTo(latestSemVer);

                    if ((comparison > 0 && specificVersionRequested) || comparison < 0)
                    {
                        downloadStrategy.DownloadVersion(latestVersion, dlArgs.Target);
                        ConsoleImpl.WriteDebug("Done.");
                    }
                    else
                    {
                        ConsoleImpl.WriteDebug("Paket.exe {0} is up to date.", localVersion);
                    }
                }

                onSuccess();
            }
            catch (WebException exn)
            {
                var shouldHandleException = true;
                if (!fileProxy.Exists(dlArgs.Target))
                {
                    if (downloadStrategy.FallbackStrategy != null)
                    {
                        var fallbackStrategy = downloadStrategy.FallbackStrategy;
                        ConsoleImpl.WriteDebug("'{0}' download failed. If using Mono, you may need to import trusted certificates using the 'mozroots' tool as none are contained by default. Trying fallback download from '{1}'.", downloadStrategy.Name, fallbackStrategy.Name);
                        StartPaketBootstrapping(fallbackStrategy, dlArgs, fileProxy, onSuccess);
                        shouldHandleException = !fileProxy.Exists(dlArgs.Target);
                    }
                }
                if (shouldHandleException)
                {
                    handleException(exn);
                }
            }
            catch (Exception exn)
            {
                handleException(exn);
            }
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: haraldsteinlechner/Paket
        public static void StartPaketBootstrapping(IDownloadStrategy downloadStrategy, DownloadArguments dlArgs, IFileProxy fileProxy, Action onSuccess)
        {
            Action<Exception> handleException = exception =>
            {
                if (!fileProxy.Exists(dlArgs.Target))
                    Environment.ExitCode = 1;
                ConsoleImpl.WriteError(String.Format("{0} ({1})", exception.Message, downloadStrategy.Name));
            };
            try
            {
                string versionRequested;
                if (!dlArgs.IgnorePrerelease)
                    versionRequested = "prerelease requested";
                else if (String.IsNullOrWhiteSpace(dlArgs.LatestVersion))
                    versionRequested = "downloading latest stable";
                else
                    versionRequested = string.Format("version {0} requested", dlArgs.LatestVersion);

                ConsoleImpl.WriteDebug("Checking Paket version ({0})...", versionRequested);

                var localVersion = fileProxy.GetLocalFileVersion(dlArgs.Target);

                var specificVersionRequested = true;
                var latestVersion = dlArgs.LatestVersion;

                if (latestVersion == String.Empty)
                {
                    latestVersion = downloadStrategy.GetLatestVersion(dlArgs.IgnorePrerelease);
                    specificVersionRequested = false;
                }

                if (dlArgs.DoSelfUpdate)
                {
                    ConsoleImpl.WriteDebug("Trying self update");
                    downloadStrategy.SelfUpdate(latestVersion);
                }
                else
                {
                    var currentSemVer = String.IsNullOrEmpty(localVersion) ? new SemVer() : SemVer.Create(localVersion);
                    if (currentSemVer.PreRelease != null && dlArgs.IgnorePrerelease)
                        currentSemVer = new SemVer();
                    var latestSemVer = SemVer.Create(latestVersion);
                    var comparison = currentSemVer.CompareTo(latestSemVer);

                    if ((comparison > 0 && specificVersionRequested) || comparison < 0)
                    {
                        downloadStrategy.DownloadVersion(latestVersion, dlArgs.Target);
                        ConsoleImpl.WriteDebug("Done.");
                    }
                    else
                    {
                        ConsoleImpl.WriteDebug("Paket.exe {0} is up to date.", localVersion);
                    }
                }

                onSuccess();
            }
            catch (WebException exn)
            {
                var shouldHandleException = true;
                if (!fileProxy.Exists(dlArgs.Target))
                {
                    if (downloadStrategy.FallbackStrategy != null)
                    {
                        var fallbackStrategy = downloadStrategy.FallbackStrategy;
                        ConsoleImpl.WriteDebug("'{0}' download failed. If using Mono, you may need to import trusted certificates using the 'mozroots' tool as none are contained by default. Trying fallback download from '{1}'.", downloadStrategy.Name, fallbackStrategy.Name);
                        StartPaketBootstrapping(fallbackStrategy, dlArgs, fileProxy, onSuccess);
                        shouldHandleException = !fileProxy.Exists(dlArgs.Target);
                    }
                }
                if (shouldHandleException)
                    handleException(exn);
            }
            catch (Exception exn)
            {
                handleException(exn);
            }
        }
コード例 #10
0
        public OperationResult MoveModFileAndFolder()
        {
            var operationResult = new OperationResult();

            // NOTE: This method may be V2 specific. I'll have to talk to Idhrendur about the rules for how this is/will be handled in other converters.
            // I'll figure out some generic way of handling any problems related to that when and if it occurs.

            var targetGameModPathItem =
                options.CurrentConverter.RequiredItems.First(i => i.InternalTagName.Equals("targetGameModPath"));
            var desiredFileName =
                folderProxy.GetFileNameWithoutExtension(options.CurrentConverter.AbsoluteSourceSaveGame.SelectedValue) +
                options.CurrentConverter.TargetGame.SaveGameExtension;

            var translatedSaveGameName = nameTranslator.TranslateName(desiredFileName);

            // Copy the newly created output mod to the target game mod directory.
            // The mod consists of two things: One file and one folder named after the save. Ex: The folder "France144_11_11" and the file "France144_11_11.mod".
            var converterWorkingDirectory = directoryHelper.GetConverterWorkingDirectory(options.CurrentConverter);
            var outputModFolderSourcePath = folderProxy.Combine(converterWorkingDirectory, "output",
                                                                translatedSaveGameName);
            var outputModFileSourcePath = folderProxy.Combine(converterWorkingDirectory, "output",
                                                              (translatedSaveGameName + ".mod"));

            var expectedAbsoluteOutputModFolderTargetPath = folderProxy.Combine(targetGameModPathItem.SelectedValue,
                                                                                translatedSaveGameName);
            var expectedAbsoluteOutputModFileTargetPath = expectedAbsoluteOutputModFolderTargetPath + ".mod";

            var modFileExists   = fileProxy.Exists(expectedAbsoluteOutputModFileTargetPath);
            var modFolderExists = folderProxy.Exists(expectedAbsoluteOutputModFolderTargetPath);

            if (modFileExists || modFolderExists)
            {
                var confirmationMessage =
                    string.Format("One or more parts of the output mod exists in {0} already. Overwrite?",
                                  targetGameModPathItem.SelectedValue);
                var result = messageBoxProxy.Show(confirmationMessage, "Confirmation Required", MessageBoxButton.YesNo);

                if (result == MessageBoxResult.No)
                {
                    operationResult.State = OperationResultState.Warning;
                    return(operationResult);
                }
            }

            try
            {
                fileProxy.Copy(outputModFileSourcePath, expectedAbsoluteOutputModFileTargetPath, true);
                directoryCopyHelper.DirectoryCopy(outputModFolderSourcePath, expectedAbsoluteOutputModFolderTargetPath,
                                                  true, true);

                operationResult.LogEntries.Add(new LogEntry("Mod copied to: ", LogEntrySeverity.Info, LogEntrySource.UI,
                                                            expectedAbsoluteOutputModFolderTargetPath));
            }
            catch (Exception e)
            {
                operationResult.LogEntries.Add(new LogEntry(e.Message, LogEntrySeverity.Error, LogEntrySource.UI));
                operationResult.State = OperationResultState.Error;
            }

            return(operationResult);
        }