Ejemplo n.º 1
0
    internal static LatestInProfileUpdate?Parse(HtmlNode node, ListEntryType listEntryType)
    {
        var selector = listEntryType switch
        {
            ListEntryType.Anime => AnimeSelector,
            ListEntryType.Manga => MangaSelector,
            _ => throw new ArgumentOutOfRangeException(nameof(listEntryType), listEntryType, null)
        };
        var dataNode = node.SelectSingleNode(selector);

        if (dataNode == null)
        {
            return(null);
        }
        var hd = new HtmlDocument();

        hd.LoadHtml(dataNode.InnerHtml);
        dataNode = hd.DocumentNode;
        var link              = dataNode.SelectSingleNode("//a").Attributes["href"].Value;
        var id                = CommonParser.ExtractIdFromMalUrl(link);
        var dataText          = dataNode.SelectSingleNode("//div[1]/div[2]").InnerText.Trim();
        var splitted          = dataText.Split(Constants.DOT);
        var progressTypeValue = splitted[0].Trim();
        var scoreText         = splitted[1].Trim();
        var index             = progressTypeValue.IndexOfAny(Numbers);
        var progressValue     = 0;
        var progress          = GenericProgress.Unknown;

        if (index == -1)
        {
            progress = ProgressParser.Parse(progressTypeValue);
        }
        else
        {
            progress = ProgressParser.Parse(progressTypeValue.Substring(0, index - 1).Trim());
            var length = progressTypeValue.IndexOf('/') - index;
            if (length > 0)
            {
                progressValue = int.Parse(progressTypeValue.Substring(index, length));
            }
        }

        var score = 0;

        if (!scoreText.Contains('-'))
        {
            var scoreIndex = scoreText.LastIndexOf(' ');
            score = int.Parse(scoreText.Substring(scoreIndex));
        }

        return(new()
        {
            Id = id,
            Progress = progress,
            ProgressValue = progressValue,
            Score = score
        });
    }
}
Ejemplo n.º 2
0
    internal static RecentUpdate ToRecentUpdate(this FeedItem feedItem, ListEntryType type)
    {
        var index                = feedItem.Description.IndexOf('-');
        var progressText         = feedItem.Description.Substring(0, index - 1).Trim();
        var progress             = ProgressParser.Parse(progressText);
        var di                   = feedItem.Description.LastIndexOf("-", StringComparison.OrdinalIgnoreCase);
        var oi                   = feedItem.Description.LastIndexOf(" of", StringComparison.OrdinalIgnoreCase);
        var progressedSubEntries = int.Parse(feedItem.Description.Substring(di + 2, oi - di - 2));

        return(new(type, CommonParser.ExtractIdFromMalUrl(feedItem.Link), feedItem.PublishingDateTimeOffset, progress, progressedSubEntries));
    }
Ejemplo n.º 3
0
        /// <summary>
        /// Runs command with output parsed by specified progress parsers
        /// </summary>
        /// <param name="bin">The executable to run.</param>
        /// <param name="args">Command line arguments.</param>
        /// <param name="stdOutHandler">Callback to handle parsing console output.</param>
        /// <param name="stdErrHandler">Callback to handle parsing console output.</param>
        public void ExecuteCommand_Parser(string bin, string args, ProgressParser stdOutHandler, ProgressParser stdErrHandler)
        {
            this.LogProxy($"Executing command: {bin} {args}", LogLevel.Info);

            //remove existing environment variables so that we can add them cleanly
            Environment.SetEnvironmentVariable("FONTCONFIG_FILE", null);
            Environment.SetEnvironmentVariable("FC_CONFIG_DIR", null);
            Environment.SetEnvironmentVariable("FONTCONFIG_PATH", null);

            var procStartInfo = new ProcessStartInfo(bin, args)
            {
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                UseShellExecute        = false,
                CreateNoWindow         = false,
                EnvironmentVariables   =
                {
                    {
                        "FONTCONFIG_FILE", this.mediaTools.FfFontsConf
                    },
                    {
                        "FC_CONFIG_DIR", this.mediaTools.FfFontsDir
                    },
                    {
                        "FONTCONFIG_PATH", this.mediaTools.FfFontsDir
                    }
                }
            };

            // Create process and execute
            var proc = new Process
            {
                StartInfo = procStartInfo
            };

            proc.OutputDataReceived += new DataReceivedEventHandler(stdOutHandler);
            proc.ErrorDataReceived  += new DataReceivedEventHandler(stdErrHandler);

            proc.Start();

            proc.BeginErrorReadLine();
            proc.BeginOutputReadLine();

            proc.WaitForExit();

            if (proc.ExitCode != 0)
            {
                this.LogProxy($"CMD {bin + " " + args} failed with error code: {proc.ExitCode}", LogLevel.AppError);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="Archive"></param>
        /// <param name="OutputFolder"></param>
        /// <returns></returns>
        public static bool UnpackArchive(string ArchivePath, string OutputFolder, ScriptBuildProgressDelegate ProgressCallback = null)
        {
            string installLocation = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            string sevenZipPath    = Path.Combine(Path.Combine(Path.Combine(installLocation, "Libraries"), "7zip"), "7za.exe");

            ProgressParser Parser = new ProgressParser();

            Parser.ParsePartialLines = false;
            Parser.LineSeperator     = "\r";
            Parser.AddPattern(@"^\s+(\d+)\% \- (.+)$",
                              new ProgressMatch(ProgressMatchType.Progress, ProgressMatchFormat.Float, 100),
                              new ProgressMatch(ProgressMatchType.CurrentFileName, ProgressMatchFormat.String));

            ScriptBuildOutputCallbackDelegate OutputCallback = (string Line) =>
            {
                Parser.Parse(Line);
                ProgressCallback?.Invoke("Decompressing " + Parser.CurrentFileName + "...", Parser.Progress);
            };

            int exitCode = RunAndWait(sevenZipPath, installLocation, "x \"" + ArchivePath + "\" -o\"" + OutputFolder + "\" -r -y -bsp1", OutputCallback);

            return(exitCode == 0);

            /*
             *
             * // SharpCompress is waaaaaaaaaaaaaaaaaaaaaaaaaaaaaay to slow :|
             * try
             * {
             *  using (IArchive Archive = ArchiveFactory.Open(ArchivePath))
             *  {
             *      int BufferLength = 1 * 1024 * 1024;
             *      byte[] Buffer = new byte[BufferLength];
             *
             *      long TotalUncompressed = Archive.TotalUncompressSize;
             *      long Uncompressed = 0;
             *
             *      foreach (IArchiveEntry Entry in Archive.Entries.Where(entry => !entry.IsDirectory))
             *      {
             *          using (Stream ArchiveStream = Entry.OpenEntryStream())
             *          {
             *              using (FileStream FileStream = new FileStream(OutputFolder + @"\" + Entry.Key, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
             *              {
             *                  int BytesRead = 0;
             *                  while ((BytesRead = ArchiveStream.Read(Buffer, 0, Buffer.Length)) > 0)
             *                  {
             *                      FileStream.Write(Buffer, 0, BytesRead);
             *                      Uncompressed += BytesRead;
             *
             *                      float Progress = (float)Uncompressed / (float)TotalUncompressed;
             *                      ProgressCallback?.Invoke("Unpacking " + Entry.Key + "...", Progress);
             *                  }
             *              }
             *          }
             *      }
             *  }
             * }
             * catch (Exception Ex) // Should be more specific, but sharpcompress has so little documentation and looking through the code there are so many potential exceptions...
             * {
             *  Logger.Log(LogLevel.Error, LogCategory.Script, "Failed to extract archive with error: {0}", Ex.Message.ToString());
             *  return false;
             * }
             *
             * return true;
             */
        }