Esempio n. 1
0
        public void SignImages(string setCodesStr, bool small, bool zoom, bool nonToken, bool token)
        {
            foreach (FsPath qualityDir in getQualities(small, zoom))
            {
                foreach ((_, _, FsPath tokenSuffix) in getIsToken(nonToken, token))
                {
                    FsPath outputFile  = getSignatureFile(qualityDir, tokenSuffix);
                    FsPath packagePath = TargetDir.Join(qualityDir).Concat(tokenSuffix);
                    new ImageDirectorySigner().SignFiles(packagePath, outputFile, setCodesStr);

                    FsPath signatureFile           = getSignatureFile(qualityDir, tokenSuffix);
                    FsPath compressedSignatureFile = signatureFile
                                                     .Parent()
                                                     .Join(signatureFile.Basename(extension: false))
                                                     .Concat(SevenZipExtension);

                    if (compressedSignatureFile.IsFile())
                    {
                        compressedSignatureFile.DeleteFile();
                    }

                    new SevenZip(false).Compress(signatureFile, compressedSignatureFile)
                    .Should().BeTrue();
                }
            }
        }
Esempio n. 2
0
        public void SignFiles(FsPath packagePath, FsPath output, string setCodes)
        {
            FsPath parentDir = output.Parent();

            parentDir.CreateDirectory();

            if (packagePath.IsDirectory())
            {
                var sets = setCodes?.Split(';', ',', '|')
                           // to remove duplicates with different set name casing
                           .ToHashSet(StringComparer.OrdinalIgnoreCase);

                var prevSignatureByPath = sets != null && output.IsFile()
                                        ? Signer.ReadFromFile(output, internPath: false)
                                          .Where(_ => !sets.Contains(_.Path.Parent().Value))
                                          .ToDictionary(_ => _.Path)
                                        : new Dictionary <FsPath, FileSignature>();

                var signatures = Signer.CreateSignatures(packagePath, precalculated: prevSignatureByPath);
                Signer.WriteToFile(output, signatures);
            }
            else if (packagePath.IsFile())
            {
                var metadata = Signer.CreateSignature(packagePath);
                Signer.WriteToFile(output, Sequence.Array(metadata));
            }
            else
            {
                Console.WriteLine("Specified path {0} does not exist", packagePath);
            }
        }
Esempio n. 3
0
        private void openInExplorerClick(object sender, EventArgs e)
        {
            FsPath fullPath = _models[_imageIndex].ImageFile.FullPath;

            if (!fullPath.IsFile())
            {
                return;
            }

            if (Runtime.IsLinux)
            {
                var explorerApp = detectFileExplorerApp();
                if (!string.IsNullOrEmpty(explorerApp))
                {
                    Process.Start(explorerApp, $"--select \"{fullPath}\"");
                }
                else
                {
                    Process.Start("xdg-open", $"\"{fullPath.Parent()}\"");
                }
            }
            else
            {
                Process.Start("explorer.exe", $"/select, \"{fullPath}\"");
            }
        }
Esempio n. 4
0
        public static void Scale(FsPath sourceFile, FsPath targetFile)
        {
            FsPath exe = Runtime.IsLinux
                                ? getLinuxExecutable()
                                : getWindowsExecutable();
            string args             = $"--jobs {Environment.ProcessorCount} --mode scale -i \"{sourceFile}\" -o \"{targetFile}\"";
            FsPath workingDirectory = exe.Parent();

            var process = Process.Start(new ProcessStartInfo(exe.Value, args)
            {
                WorkingDirectory = workingDirectory.Value,
                UseShellExecute  = false,
                CreateNoWindow   = true
            });

            if (process == null)
            {
                throw new Exception("Failed to start waifu2x-converter.exe");
            }

            if (!process.WaitForExit(180_000))
            {
                throw new TimeoutException("waifu2x-converter.exe timeout");
            }
        }
Esempio n. 5
0
        public static void Scale(FsPath sourceFile, FsPath targetFile)
        {
            int parallelism = Environment.ProcessorCount;

            // download from https://yadi.sk/d/f1HuKUg7xW2FUQ/tools?w=1
            FsPath exe              = DevPaths.MtgToolsDir.Join("waifu2x-converter-cpp", "waifu2x-converter-cpp.exe");
            string args             = $"--jobs {parallelism} --mode scale -i \"{sourceFile}\" -o \"{targetFile}\"";
            FsPath workingDirectory = exe.Parent();

            var process = Process.Start(new ProcessStartInfo(exe.Value, args)
            {
                WorkingDirectory = workingDirectory.Value,
                UseShellExecute  = false,
                CreateNoWindow   = true
            });

            if (process == null)
            {
                throw new Exception("Failed to start waifu2x-converter.exe");
            }

            if (!process.WaitForExit(180_000))
            {
                throw new TimeoutException("waifu2x-converter.exe timeout");
            }
        }
Esempio n. 6
0
        public void RenameWizardsWebpageImages(string htmlFile, string targetSubdir)
        {
            FsPath htmlPath  = HtmlDir.Join(htmlFile);
            FsPath targetDir = DevPaths.GathererOriginalDir.Join(targetSubdir);

            string htmlFileName  = htmlPath.Basename(extension: false);
            FsPath directoryName = htmlPath.Parent();

            if (!directoryName.HasValue())
            {
                throw new ArgumentException(htmlPath.Value, nameof(htmlPath));
            }

            FsPath filesDirectory = directoryName.Join(htmlFileName + "_files");

            string content = htmlPath.ReadAllText();
            var    matches = _imgTagPattern.Matches(content);

            targetDir.CreateDirectory();
            foreach (Match match in matches)
            {
                string originalFileName = match.Groups["file"].Value;
                string ext = Path.GetExtension(originalFileName);

                FsPath filePath = filesDirectory.Join(originalFileName);

                string name = HttpUtility.HtmlDecode(match.Groups["name"].Value)
                              .Replace(" // ", "");

                FsPath defaultTargetPath = targetDir.Join(name + ext);

                bool defaultTargetExists = defaultTargetPath.IsFile();

                if (defaultTargetExists || getTargetPath(1).IsFile())
                {
                    if (defaultTargetExists)
                    {
                        defaultTargetPath.MoveFileTo(getTargetPath(1));
                    }

                    for (int i = 2; i < 12; i++)
                    {
                        FsPath targetPath = getTargetPath(i);
                        if (!targetPath.IsFile())
                        {
                            filePath.CopyFileTo(targetPath, overwrite: false);
                            break;
                        }
                    }
                }
                else
                {
                    filePath.CopyFileTo(defaultTargetPath, overwrite: false);
                }

                FsPath getTargetPath(int num) =>
                targetDir.Join(name + num + ext);
            }
        }
Esempio n. 7
0
 private static void moveDirectoryToBackup(FsPath dir, FsPath dirBak)
 {
     if (dirBak.IsDirectory())
     {
         dirBak.DeleteDirectory(recursive: true);
     }
     dirBak.Parent().CreateDirectory();
     dir.MoveDirectoryTo(dirBak);
 }
Esempio n. 8
0
        public void Save(FsPath file)
        {
            FsPath directory = file.Parent();

            directory.CreateDirectory();
            var state = getState();

            WriteHistory(file, state);
        }
Esempio n. 9
0
        public static void CreateApplicationShortcut(FsPath exePath, FsPath iconPath, FsPath shortcutPath)
        {
            if (shortcutPath.IsFile())
            {
                shortcutPath.DeleteFile();
            }

            var          wsh = new WshShell();
            IWshShortcut shortcut;

            try
            {
                shortcut = wsh.CreateShortcut(shortcutPath.Value) as IWshShortcut;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(
                    "Failed to create shortcut object {0} at {1}: {2}",
                    exePath, shortcutPath, ex);
                return;
            }

            FsPath bin = exePath.Parent();

            if (shortcut == null)
            {
                Console.Error.WriteLine("Failed to create shortcut {0} at {1}: {2}.{3} returned null",
                                        exePath, shortcutPath, nameof(WshShell), nameof(wsh.CreateShortcut));
                return;
            }

            shortcut.Arguments   = "";
            shortcut.TargetPath  = exePath.Value;
            shortcut.WindowStyle = 1;

            shortcut.Description      = "Application to search MTG cards and build decks";
            shortcut.WorkingDirectory = bin.Value;

            if (iconPath.HasValue())
            {
                shortcut.IconLocation = iconPath.Value;
            }

            try
            {
                shortcut.Save();
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("Failed to create shortcut {0} at {1}: {2}", exePath, shortcutPath, ex);
            }
        }
Esempio n. 10
0
        private static FsPath getDir(FsPath lastFile)
        {
            if (lastFile == FsPath.None)
            {
                return(FsPath.None);
            }

            var result = lastFile.Parent();

            if (!result.IsDirectory())
            {
                return(FsPath.None);
            }

            return(result);
        }
Esempio n. 11
0
        public void LoadHistory(FsPath file)
        {
            FsPath directory = file.Parent();

            directory.CreateDirectory();

            if (TryReadHistory(file, out var state))
            {
                _settingsHistory = state.SettingsHistory;
                _settingsIndex   = state.SettingsIndex;
            }
            else
            {
                _settingsHistory = new List <GuiSettings>();
                var defaultSettings = new GuiSettings();
                Add(defaultSettings);
            }

            IsLoaded = true;
            Loaded?.Invoke();
        }
Esempio n. 12
0
        public ImageFile(
            FsPath fileName, FsPath rootPath, string setCode = null, string artist = null,
            bool isArt = false, int?customPriority = null)
        {
            var    fileNameWithoutExtension = fileName.Basename(extension: false);
            FsPath directoryName            = fileName.Parent();

            FullPath = fileName;

            string[] parts        = fileNameWithoutExtension.Split(Sequence.Array('.'), StringSplitOptions.None);
            var      lastNamePart = Enumerable.Range(0, parts.Length)
                                    .Last(i =>
                                          i == 0 ||
                                          // Richard Garfield, Ph.D..xlhq.jpg
                                          // S.N.O.T..xlhq.jpg
                                          // Our Market Research....xlhq.jpg
                                          parts[i].Length <= 1 ||
                                          // Sarpadian Empires, Vol. VII.xlhq.jpg
                                          // Но Thoughtseize.[Size 16x20].jpg
                                          parts[i].Contains(' ') && !(parts[i].StartsWith("[") && parts[i].EndsWith("]")));

            Type = string.Join(".", parts.Skip(1 + lastNamePart));

            string imageNameRaw = string.Join(".", parts.Take(1 + lastNamePart));
            var    imageName    = _patternToRemove.Replace(imageNameRaw, string.Empty);
            var    replacedName = _nameReplacements.TryGet(imageName) ?? imageName;

            ImageName = string.Intern(replacedName);

            var nameParts = ImageName.SplitTailingNumber();

            Name          = string.Intern(nameParts.Item1);
            VariantNumber = nameParts.Item2;

            rootPath = rootPath.ToAppRootedPath();

            if (setCode != null)
            {
                SetCode = string.Intern(setCode);
                SetCodeIsFromAttribute = true;
            }
            else
            {
                var setCodeMatch = _setCodeRegex.Match(directoryName.RelativeTo(rootPath).Value);
                if (setCodeMatch.Success)
                {
                    SetCode = string.Intern(setCodeMatch.Value.ToUpperInvariant());
                }
                else
                {
                    SetCode = string.Empty;
                }
            }

            Priority = customPriority ?? getPriority();

            if (artist != null)
            {
                Artist = string.Intern(artist);
            }

            IsArt   = isArt;
            IsToken = directoryName.Value.IndexOf("Token", Str.Comparison) >= 0;
        }