Beispiel #1
0
        // 解析测试视频
        private List <TestVideo> ParseTestVideo(string videoPath)
        {
            if (Directory.Exists(videoPath))
            {
                List <TestVideo> testVideos = new List <TestVideo>();
                var videos = Utility.Director(videoPath).Where(f =>
                {
                    string ex = Path.GetExtension(f);
                    return(ex == ".ts" || ex == ".mp4" || ex == ".flv" || ex == ".avi");
                }).ToList();

                foreach (var item in videos)
                {
                    var _testVideoItem = new TestVideo {
                        VideoName = Path.GetFileName(item), VideoPath = Path.GetDirectoryName(item)
                    };
                    testVideos.Add(_testVideoItem);
                }

                return(testVideos);
            }
            else
            {
                MessageWindow.ShowDialog($"无法访问文件夹 [{videoPath}]", this);
            }

            return(null);
        }
Beispiel #2
0
        public async Task DownloadMissingArchives(List <Archive> missing, bool download = true)
        {
            if (download)
            {
                foreach (var a in missing.Where(a => a.State.GetType() == typeof(ManualDownloader.State)))
                {
                    var outputPath = DownloadFolder.Combine(a.Name);
                    await a.State.Download(a, outputPath);
                }
            }

            await missing.Where(a => a.State.GetType() != typeof(ManualDownloader.State))
            .PMap(Queue, async archive =>
            {
                Info($"Downloading {archive.Name}");
                var outputPath = DownloadFolder.Combine(archive.Name);

                if (download)
                {
                    if (outputPath.Exists)
                    {
                        var origName  = Path.GetFileNameWithoutExtension(archive.Name);
                        var ext       = Path.GetExtension(archive.Name);
                        var uniqueKey = archive.State.PrimaryKeyString.StringSha256Hex();
                        outputPath    = DownloadFolder.Combine(origName + "_" + uniqueKey + "_" + ext);
                        outputPath.Delete();
                    }
                }

                return(await DownloadArchive(archive, download, outputPath));
            });
        }
        public static string MakePartFilename(string path, int part)
        {
            string dirName   = Path.GetDirectoryName(path);
            string baseName  = Path.GetFileNameWithoutExtension(path);
            string extension = Path.GetExtension(path);

            return($"{dirName}/{baseName}_{part}{extension}");
        }
Beispiel #4
0
        public void VerifyAllFiles()
        {
            var skip_files = new HashSet <string> {
                "portable.txt"
            };

            foreach (var dest_file in Directory.EnumerateFiles(InstallFolder, "*", DirectoryEnumerationOptions.Recursive))
            {
                var rel_file = dest_file.RelativeTo(InstallFolder);
                if (rel_file.StartsWith(Consts.LOOTFolderFilesDir) || rel_file.StartsWith(Consts.GameFolderFilesDir))
                {
                    continue;
                }

                if (!skip_files.Contains(rel_file))
                {
                    Assert.IsTrue(File.Exists(Path.Combine(MO2Folder, rel_file)), $"Only in Destination: {rel_file}");
                }
            }

            var skip_extensions = new HashSet <string> {
                ".txt", ".ini"
            };

            foreach (var src_file in Directory.EnumerateFiles(MO2Folder, "*", DirectoryEnumerationOptions.Recursive))
            {
                var rel_file = src_file.RelativeTo(MO2Folder);

                if (rel_file.StartsWith("downloads\\"))
                {
                    continue;
                }

                var dest_file = Path.Combine(InstallFolder, rel_file);
                Assert.IsTrue(File.Exists(dest_file), $"Only in Source: {rel_file}");

                var fi_src  = new FileInfo(src_file);
                var fi_dest = new FileInfo(dest_file);

                if (!skip_extensions.Contains(Path.GetExtension(src_file)))
                {
                    Assert.AreEqual(fi_src.Length, fi_dest.Length, $"Differing sizes {rel_file}");
                    Assert.AreEqual(src_file.FileHash(), dest_file.FileHash(), $"Differing content hash {rel_file}");
                }
            }
        }
        public static ExportFormat ExtensionToModelFormat(string path)
        {
            string extension = Path.GetExtension(path)?.ToLower();

            switch (extension)
            {
            case ".gr2":
            case ".lsm":
                return(ExportFormat.GR2);

            case ".dae":
                return(ExportFormat.DAE);

            default:
                throw new ArgumentException($"Unrecognized model file extension: {extension}");
            }
        }
Beispiel #6
0
        public static ResourceFormat ExtensionToResourceFormat(string path)
        {
            var extension = Path.GetExtension(path).ToLower();

            switch (extension)
            {
            case ".lsx":
                return(ResourceFormat.LSX);

            case ".lsb":
                return(ResourceFormat.LSB);

            case ".lsf":
                return(ResourceFormat.LSF);

            case ".lsj":
                return(ResourceFormat.LSJ);

            default:
                throw new ArgumentException("Unrecognized file extension: " + extension);
            }
        }
Beispiel #7
0
        private void EnumerateFiles(List <string> paths, string rootPath, string currentPath, string extension)
        {
            foreach (string filePath in Directory.GetFiles(currentPath))
            {
                var fileExtension = Path.GetExtension(filePath);
                if (fileExtension.ToLower() == extension)
                {
                    var relativePath = filePath.Substring(rootPath.Length);
                    if (relativePath[0] == '/' || relativePath[0] == '\\')
                    {
                        relativePath = relativePath.Substring(1);
                    }

                    paths.Add(relativePath);
                }
            }

            foreach (string directoryPath in Directory.GetDirectories(currentPath))
            {
                EnumerateFiles(paths, rootPath, directoryPath, extension);
            }
        }
        /// <summary>
        /// Tests if a file name matches a Windows file pattern
        /// </summary>
        /// <remarks>
        /// Not an exact duplicate of the internal Windows implementation, but most common patterns are supported
        /// https://blogs.msdn.microsoft.com/jeremykuhne/2017/06/04/wildcards-in-windows/
        /// https://blogs.msdn.microsoft.com/oldnewthing/20071217-00/?p=24143/
        /// </remarks>
        /// <param name="fileName">the file name to test</param>
        /// <param name="pattern">the Windows file patten</param>
        /// <returns>True if match, otherwise false</returns>
        public static bool WildcardMatch(string fileName, string pattern)
        {
            if (fileName == null)
            {
                throw new ArgumentNullException(nameof(fileName));
            }
            if (pattern == null)
            {
                throw new ArgumentNullException(nameof(pattern));
            }

            if (string.IsNullOrEmpty(pattern))
            {
                return(fileName.Length == 0);
            }

            if (pattern == "*" || pattern == "*.*")
            {
                return(!string.IsNullOrWhiteSpace(fileName));
            }

            if (pattern == "*.")
            {
                return(string.IsNullOrWhiteSpace(Path.GetExtension(fileName)));
            }

            if (pattern == ".*")
            {
                return(fileName.StartsWith(dot, StringComparison.OrdinalIgnoreCase));
            }

            if (pattern.StartsWith(star, StringComparison.OrdinalIgnoreCase) && pattern.IndexOf('*', 1) == -1 && pattern.IndexOf('?') == -1)
            {
                return(fileName.EndsWith(pattern.Substring(1), StringComparison.CurrentCulture));
            }

            int fileNameIndex  = 0;
            int patternIndex   = 0;
            int fileNameLength = fileName.Length;
            int patternLength  = pattern.Length;

            while (fileNameIndex < fileNameLength && patternIndex < patternLength && pattern[patternIndex] != '*')
            {
                char wild = pattern[patternIndex];
                if (wild != '?' && wild != fileName[fileNameIndex])
                {
                    return(false);
                }
                patternIndex++;
                fileNameIndex++;
            }

            int fileNameIndex2 = 0;
            int patternIndex2  = 0;

            while (fileNameIndex < fileNameLength && patternIndex < patternLength)
            {
                char wild = pattern[patternIndex];
                if (wild == '*')
                {
                    patternIndex++;
                    if (patternIndex == patternLength)
                    {
                        return(true);
                    }
                    patternIndex2  = patternIndex;
                    fileNameIndex2 = fileNameIndex + 1;
                }
                else if (wild == '?' || wild == fileName[fileNameIndex])
                {
                    patternIndex++;
                    fileNameIndex++;
                }
                else
                {
                    patternIndex  = patternIndex2;
                    fileNameIndex = fileNameIndex2;
                    fileNameIndex2++;
                }
            }
            while (patternIndex < patternLength && pattern[patternIndex] == '*')
            {
                patternIndex++;
            }
            return(patternIndex == patternLength && fileNameIndex == fileNameLength);
        }
Beispiel #9
0
 internal string GenerateStagedName()
 {
     if (_stagedPath != null)
     {
         return(_stagedPath);
     }
     _stagedPath = Path.Combine(VirtualFileSystem._stagedRoot, Guid.NewGuid().ToString() + Path.GetExtension(Paths.Last()));
     return(_stagedPath);
 }
Beispiel #10
0
        /// <summary>
        /// Tests if a file name matches a Windows file pattern
        /// </summary>
        /// <remarks>
        /// Not an exact duplicate of the internal Windows implementation, but most common patterns are supported
        /// https://blogs.msdn.microsoft.com/jeremykuhne/2017/06/04/wildcards-in-windows/
        /// https://blogs.msdn.microsoft.com/oldnewthing/20071217-00/?p=24143/
        /// </remarks>
        /// <param name="fileName">the file name to test</param>
        /// <param name="pattern">the Windows file patten</param>
        /// <returns>True if match, otherwise false</returns>
        public static bool WildcardMatch(string fileName, string pattern)
        {
            if (string.IsNullOrEmpty(pattern))
            {
                return(fileName.Length == 0);
            }

            if (pattern == "*" || pattern == "*.*")
            {
                return(!string.IsNullOrWhiteSpace(fileName));
            }

            if (pattern == "*.")
            {
                return(string.IsNullOrWhiteSpace(Path.GetExtension(fileName)));
            }

            if (pattern == ".*")
            {
                return(fileName.StartsWith("."));
            }

            if (pattern.StartsWith("*") && pattern.IndexOf('*', 1) == -1 && pattern.IndexOf('?') == -1)
            {
                return(fileName.EndsWith(pattern.Substring(1)));
            }

            int fileNameIndex  = 0;
            int patternIndex   = 0;
            int fileNameLength = fileName.Length;
            int patternLength  = pattern.Length;

            while (fileNameIndex < fileNameLength && patternIndex < patternLength && pattern[patternIndex] != '*')
            {
                char wild = pattern[patternIndex];
                if (wild != '?' && wild != fileName[fileNameIndex])
                {
                    return(false);
                }
                patternIndex++;
                fileNameIndex++;
            }

            int fileNameIndex2 = 0;
            int patternIndex2  = 0;

            while (fileNameIndex < fileNameLength && patternIndex < patternLength)
            {
                char wild = pattern[patternIndex];
                if (wild == '*')
                {
                    patternIndex++;
                    if (patternIndex == patternLength)
                    {
                        return(true);
                    }
                    patternIndex2  = patternIndex;
                    fileNameIndex2 = fileNameIndex + 1;
                }
                else if (wild == '?' || wild == fileName[fileNameIndex])
                {
                    patternIndex++;
                    fileNameIndex++;
                }
                else
                {
                    patternIndex  = patternIndex2;
                    fileNameIndex = fileNameIndex2;
                    fileNameIndex2++;
                }
            }
            while (patternIndex < patternLength && pattern[patternIndex] == '*')
            {
                patternIndex++;
            }
            return(patternIndex == patternLength && fileNameIndex == fileNameLength);
        }
Beispiel #11
0
        public static Extension FromPath(string path)
        {
            var ext = Path.GetExtension(path);

            return(!string.IsNullOrWhiteSpace(ext) ? new Extension(ext) : None);
        }
Beispiel #12
0
        private static void Main(string[] args)
        {
            ExceptionlessClient.Default.Startup("x3MPpeQSBUUsXl3DjekRQ9kYjyN3cr5JuwdoOBpZ");

            SetupNLog();

            _keywords = new HashSet <string> {
                "temp", "tmp"
            };

            _logger = LogManager.GetCurrentClassLogger();



            _fluentCommandLineParser = new FluentCommandLineParser <ApplicationArguments>
            {
                IsCaseSensitive = false
            };

            _fluentCommandLineParser.Setup(arg => arg.File)
            .As('f')
            .WithDescription("File to process. Either this or -d is required");

            _fluentCommandLineParser.Setup(arg => arg.Directory)
            .As('d')
            .WithDescription("Directory to recursively process. Either this or -f is required");

            _fluentCommandLineParser.Setup(arg => arg.Keywords)
            .As('k')
            .WithDescription(
                "Comma separated list of keywords to highlight in output. By default, 'temp' and 'tmp' are highlighted. Any additional keywords will be added to these.");

            _fluentCommandLineParser.Setup(arg => arg.OutFile)
            .As('o')
            .WithDescription(
                "When specified, save prefetch file bytes to the given path. Useful to look at decompressed Win10 files");

            _fluentCommandLineParser.Setup(arg => arg.Quiet)
            .As('q')
            .WithDescription(
                "Do not dump full details about each file processed. Speeds up processing when using --json or --csv. Default is FALSE\r\n")
            .SetDefault(false);

            _fluentCommandLineParser.Setup(arg => arg.JsonDirectory)
            .As("json")
            .WithDescription(
                "Directory to save json representation to. Use --pretty for a more human readable layout");

            _fluentCommandLineParser.Setup(arg => arg.CsvDirectory)
            .As("csv")
            .WithDescription(
                "Directory to save CSV results to. Be sure to include the full path in double quotes");
            _fluentCommandLineParser.Setup(arg => arg.CsvName)
            .As("csvf")
            .WithDescription("File name to save CSV formatted results to. When present, overrides default name");


            _fluentCommandLineParser.Setup(arg => arg.xHtmlDirectory)
            .As("html")
            .WithDescription(
                "Directory to save xhtml formatted results to. Be sure to include the full path in double quotes");

            _fluentCommandLineParser.Setup(arg => arg.JsonPretty)
            .As("pretty")
            .WithDescription(
                "When exporting to json, use a more human readable layout. Default is FALSE\r\n").SetDefault(false);



            _fluentCommandLineParser.Setup(arg => arg.DateTimeFormat)
            .As("dt")
            .WithDescription(
                "The custom date/time format to use when displaying timestamps. See https://goo.gl/CNVq0k for options. Default is: yyyy-MM-dd HH:mm:ss")
            .SetDefault("yyyy-MM-dd HH:mm:ss");

            _fluentCommandLineParser.Setup(arg => arg.PreciseTimestamps)
            .As("mp")
            .WithDescription(
                "When true, display higher precision for timestamps. Default is FALSE").SetDefault(false);


            var header =
                $"PECmd version {Assembly.GetExecutingAssembly().GetName().Version}" +
                "\r\n\r\nAuthor: Eric Zimmerman ([email protected])" +
                "\r\nhttps://github.com/EricZimmerman/PECmd";

            var footer = @"Examples: PECmd.exe -f ""C:\Temp\CALC.EXE-3FBEF7FD.pf""" + "\r\n\t " +
                         @" PECmd.exe -f ""C:\Temp\CALC.EXE-3FBEF7FD.pf"" --json ""D:\jsonOutput"" --jsonpretty" +
                         "\r\n\t " +
                         @" PECmd.exe -d ""C:\Temp"" -k ""system32, fonts""" + "\r\n\t " +
                         @" PECmd.exe -d ""C:\Temp"" --csv ""c:\temp"" --csvf foo.csv --json c:\temp\json" +
                         "\r\n\t " +
                         @" PECmd.exe -d ""C:\Windows\Prefetch""" + "\r\n\t " +
                         "\r\n\t" +
                         "  Short options (single letter) are prefixed with a single dash. Long commands are prefixed with two dashes\r\n";

            _fluentCommandLineParser.SetupHelp("?", "help")
            .WithHeader(header)
            .Callback(text => _logger.Info(text + "\r\n" + footer));

            var result = _fluentCommandLineParser.Parse(args);

            if (result.HelpCalled)
            {
                return;
            }

            if (result.HasErrors)
            {
                _logger.Error("");
                _logger.Error(result.ErrorText);

                _fluentCommandLineParser.HelpOption.ShowHelp(_fluentCommandLineParser.Options);

                return;
            }

            if (UsefulExtension.IsNullOrEmpty(_fluentCommandLineParser.Object.File) &&
                UsefulExtension.IsNullOrEmpty(_fluentCommandLineParser.Object.Directory))
            {
                _fluentCommandLineParser.HelpOption.ShowHelp(_fluentCommandLineParser.Options);

                _logger.Warn("Either -f or -d is required. Exiting");
                return;
            }

            if (UsefulExtension.IsNullOrEmpty(_fluentCommandLineParser.Object.File) == false &&
                !File.Exists(_fluentCommandLineParser.Object.File))
            {
                _logger.Warn($"File '{_fluentCommandLineParser.Object.File}' not found. Exiting");
                return;
            }

            if (UsefulExtension.IsNullOrEmpty(_fluentCommandLineParser.Object.Directory) == false &&
                !Directory.Exists(_fluentCommandLineParser.Object.Directory))
            {
                _logger.Warn($"Directory '{_fluentCommandLineParser.Object.Directory}' not found. Exiting");
                return;
            }

            if (_fluentCommandLineParser.Object.Keywords?.Length > 0)
            {
                var kws = _fluentCommandLineParser.Object.Keywords.ToLowerInvariant().Split(new[] { ',' },
                                                                                            StringSplitOptions.RemoveEmptyEntries);

                foreach (var kw in kws)
                {
                    _keywords.Add(kw.Trim());
                }
            }


            _logger.Info(header);
            _logger.Info("");
            _logger.Info($"Command line: {string.Join(" ", Environment.GetCommandLineArgs().Skip(1))}");

            if (IsAdministrator() == false)
            {
                _logger.Fatal("\r\nWarning: Administrator privileges not found!");
            }

            _logger.Info("");
            _logger.Info($"Keywords: {string.Join(", ", _keywords)}");
            _logger.Info("");

            if (_fluentCommandLineParser.Object.PreciseTimestamps)
            {
                _fluentCommandLineParser.Object.DateTimeFormat = _preciseTimeFormat;
            }

            _processedFiles = new List <IPrefetch>();

            _failedFiles = new List <string>();

            if (_fluentCommandLineParser.Object.File?.Length > 0)
            {
                IPrefetch pf = null;

                try
                {
                    pf = LoadFile(_fluentCommandLineParser.Object.File);

                    if (pf != null)
                    {
                        if (_fluentCommandLineParser.Object.OutFile.IsNullOrEmpty() == false)
                        {
                            try
                            {
                                if (Directory.Exists(Path.GetDirectoryName(_fluentCommandLineParser.Object.OutFile)) ==
                                    false)
                                {
                                    Directory.CreateDirectory(
                                        Path.GetDirectoryName(_fluentCommandLineParser.Object.OutFile));
                                }

                                PrefetchFile.SavePrefetch(_fluentCommandLineParser.Object.OutFile, pf);
                                _logger.Info($"Saved prefetch bytes to '{_fluentCommandLineParser.Object.OutFile}'");
                            }
                            catch (Exception e)
                            {
                                _logger.Error($"Unable to save prefetch file. Error: {e.Message}");
                            }
                        }


                        _processedFiles.Add(pf);
                    }
                }
                catch (UnauthorizedAccessException ex)
                {
                    _logger.Error(
                        $"Unable to access '{_fluentCommandLineParser.Object.File}'. Are you running as an administrator? Error: {ex.Message}");
                }
                catch (Exception ex)
                {
                    _logger.Error(
                        $"Error getting prefetch files in '{_fluentCommandLineParser.Object.Directory}'. Error: {ex.Message}");
                }
            }
            else
            {
                _logger.Info($"Looking for prefetch files in '{_fluentCommandLineParser.Object.Directory}'");
                _logger.Info("");

                string[] pfFiles = null;


                var f = new DirectoryEnumerationFilters();
                f.InclusionFilter = fsei =>
                {
                    if (fsei.Extension.ToUpperInvariant() == ".PF")
                    {
                        return(true);
                    }

                    return(false);
                };

                f.RecursionFilter = entryInfo => !entryInfo.IsMountPoint && !entryInfo.IsSymbolicLink;

                f.ErrorFilter = (errorCode, errorMessage, pathProcessed) => true;

                var dirEnumOptions =
                    DirectoryEnumerationOptions.Files | DirectoryEnumerationOptions.Recursive |
                    DirectoryEnumerationOptions.SkipReparsePoints | DirectoryEnumerationOptions.ContinueOnException |
                    DirectoryEnumerationOptions.BasicSearch;

                var files2 =
                    Alphaleonis.Win32.Filesystem.Directory.EnumerateFileSystemEntries(_fluentCommandLineParser.Object.Directory, dirEnumOptions, f);



                try
                {
                    pfFiles = files2.ToArray(); //Directory.GetFiles(_fluentCommandLineParser.Object.Directory, "*.pf",                        SearchOption.AllDirectories);
                }
                catch (UnauthorizedAccessException ua)
                {
                    _logger.Error(
                        $"Unable to access '{_fluentCommandLineParser.Object.Directory}'. Are you running as an administrator? Error: {ua.Message}");
                    return;
                }
                catch (Exception ex)
                {
                    _logger.Error(
                        $"Error getting prefetch files in '{_fluentCommandLineParser.Object.Directory}'. Error: {ex.Message}");
                    return;
                }

                _logger.Info($"Found {pfFiles.Length:N0} Prefetch files");
                _logger.Info("");

                var sw = new Stopwatch();
                sw.Start();

                foreach (var file in pfFiles)
                {
                    var pf = LoadFile(file);

                    if (pf != null)
                    {
                        _processedFiles.Add(pf);
                    }
                }

                sw.Stop();

                if (_fluentCommandLineParser.Object.Quiet)
                {
                    _logger.Info("");
                }

                _logger.Info(
                    $"Processed {pfFiles.Length - _failedFiles.Count:N0} out of {pfFiles.Length:N0} files in {sw.Elapsed.TotalSeconds:N4} seconds");

                if (_failedFiles.Count > 0)
                {
                    _logger.Info("");
                    _logger.Warn("Failed files");
                    foreach (var failedFile in _failedFiles)
                    {
                        _logger.Info($"  {failedFile}");
                    }
                }
            }

            if (_processedFiles.Count > 0)
            {
                _logger.Info("");

                try
                {
                    CsvWriter    csv          = null;
                    StreamWriter streamWriter = null;

                    CsvWriter    csvTl          = null;
                    StreamWriter streamWriterTl = null;


                    if (_fluentCommandLineParser.Object.CsvDirectory?.Length > 0)
                    {
                        var outName = $"{DateTimeOffset.Now:yyyyMMddHHmmss}_PECmd_Output.csv";

                        if (_fluentCommandLineParser.Object.CsvName.IsNullOrEmpty() == false)
                        {
                            outName = Path.GetFileName(_fluentCommandLineParser.Object.CsvName);
                        }

                        var outNameTl = $"{DateTimeOffset.Now:yyyyMMddHHmmss}_PECmd_Output_Timeline.csv";
                        if (_fluentCommandLineParser.Object.CsvName.IsNullOrEmpty() == false)
                        {
                            outNameTl =
                                $"{Path.GetFileNameWithoutExtension(_fluentCommandLineParser.Object.CsvName)}_Timeline{Path.GetExtension(_fluentCommandLineParser.Object.CsvName)}";
                        }


                        var outFile   = Path.Combine(_fluentCommandLineParser.Object.CsvDirectory, outName);
                        var outFileTl = Path.Combine(_fluentCommandLineParser.Object.CsvDirectory, outNameTl);


                        if (Directory.Exists(_fluentCommandLineParser.Object.CsvDirectory) == false)
                        {
                            _logger.Warn(
                                $"Path to '{_fluentCommandLineParser.Object.CsvDirectory}' does not exist. Creating...");
                            Directory.CreateDirectory(_fluentCommandLineParser.Object.CsvDirectory);
                        }

                        _logger.Warn($"CSV output will be saved to '{outFile}'");
                        _logger.Warn($"CSV time line output will be saved to '{outFileTl}'");

                        try
                        {
                            streamWriter = new StreamWriter(outFile);
                            csv          = new CsvWriter(streamWriter);


                            csv.WriteHeader(typeof(CsvOut));
                            csv.NextRecord();

                            streamWriterTl = new StreamWriter(outFileTl);
                            csvTl          = new CsvWriter(streamWriterTl);

                            csvTl.WriteHeader(typeof(CsvOutTl));
                            csvTl.NextRecord();
                        }
                        catch (Exception ex)
                        {
                            _logger.Error(
                                $"Unable to open '{outFile}' for writing. CSV export canceled. Error: {ex.Message}");
                        }
                    }

                    if (_fluentCommandLineParser.Object.JsonDirectory?.Length > 0)
                    {
                        if (Directory.Exists(_fluentCommandLineParser.Object.JsonDirectory) == false)
                        {
                            _logger.Warn(
                                $"'{_fluentCommandLineParser.Object.JsonDirectory} does not exist. Creating...'");
                            Directory.CreateDirectory(_fluentCommandLineParser.Object.JsonDirectory);
                        }

                        _logger.Warn($"Saving json output to '{_fluentCommandLineParser.Object.JsonDirectory}'");
                    }

                    XmlTextWriter xml = null;

                    if (_fluentCommandLineParser.Object.xHtmlDirectory?.Length > 0)
                    {
                        if (Directory.Exists(_fluentCommandLineParser.Object.xHtmlDirectory) == false)
                        {
                            _logger.Warn(
                                $"'{_fluentCommandLineParser.Object.xHtmlDirectory} does not exist. Creating...'");
                            Directory.CreateDirectory(_fluentCommandLineParser.Object.xHtmlDirectory);
                        }

                        var outDir = Path.Combine(_fluentCommandLineParser.Object.xHtmlDirectory,
                                                  $"{DateTimeOffset.UtcNow:yyyyMMddHHmmss}_PECmd_Output_for_{_fluentCommandLineParser.Object.xHtmlDirectory.Replace(@":\", "_").Replace(@"\", "_")}");

                        if (Directory.Exists(outDir) == false)
                        {
                            Directory.CreateDirectory(outDir);
                        }

                        var styleDir = Path.Combine(outDir, "styles");
                        if (Directory.Exists(styleDir) == false)
                        {
                            Directory.CreateDirectory(styleDir);
                        }

                        File.WriteAllText(Path.Combine(styleDir, "normalize.css"), Resources.normalize);
                        File.WriteAllText(Path.Combine(styleDir, "style.css"), Resources.style);

                        Resources.directories.Save(Path.Combine(styleDir, "directories.png"));
                        Resources.filesloaded.Save(Path.Combine(styleDir, "filesloaded.png"));

                        var outFile = Path.Combine(_fluentCommandLineParser.Object.xHtmlDirectory, outDir,
                                                   "index.xhtml");

                        _logger.Warn($"Saving HTML output to '{outFile}'");

                        xml = new XmlTextWriter(outFile, Encoding.UTF8)
                        {
                            Formatting  = Formatting.Indented,
                            Indentation = 4
                        };

                        xml.WriteStartDocument();

                        xml.WriteProcessingInstruction("xml-stylesheet", "href=\"styles/normalize.css\"");
                        xml.WriteProcessingInstruction("xml-stylesheet", "href=\"styles/style.css\"");

                        xml.WriteStartElement("document");
                    }

                    if (_fluentCommandLineParser.Object.CsvDirectory.IsNullOrEmpty() == false ||
                        _fluentCommandLineParser.Object.JsonDirectory.IsNullOrEmpty() == false ||
                        _fluentCommandLineParser.Object.xHtmlDirectory.IsNullOrEmpty() == false)
                    {
                        foreach (var processedFile in _processedFiles)
                        {
                            var o = GetCsvFormat(processedFile);

                            try
                            {
                                foreach (var dateTimeOffset in processedFile.LastRunTimes)
                                {
                                    var t = new CsvOutTl();

                                    var exePath =
                                        processedFile.Filenames.FirstOrDefault(
                                            y => y.EndsWith(processedFile.Header.ExecutableFilename));

                                    if (exePath == null)
                                    {
                                        exePath = processedFile.Header.ExecutableFilename;
                                    }

                                    t.ExecutableName = exePath;
                                    t.RunTime        = dateTimeOffset.ToString(_fluentCommandLineParser.Object.DateTimeFormat);

                                    csvTl?.WriteRecord(t);
                                    csvTl?.NextRecord();
                                }
                            }
                            catch (Exception ex)
                            {
                                _logger.Error(
                                    $"Error getting time line record for '{processedFile.SourceFilename}' to '{_fluentCommandLineParser.Object.CsvDirectory}'. Error: {ex.Message}");
                            }

                            try
                            {
                                csv?.WriteRecord(o);
                                csv?.NextRecord();
                            }
                            catch (Exception ex)
                            {
                                _logger.Error(
                                    $"Error writing CSV record for '{processedFile.SourceFilename}' to '{_fluentCommandLineParser.Object.CsvDirectory}'. Error: {ex.Message}");
                            }

                            if (_fluentCommandLineParser.Object.JsonDirectory?.Length > 0)
                            {
                                SaveJson(processedFile, _fluentCommandLineParser.Object.JsonPretty,
                                         _fluentCommandLineParser.Object.JsonDirectory);
                            }

                            //XHTML
                            xml?.WriteStartElement("Container");
                            xml?.WriteElementString("SourceFile", o.SourceFilename);
                            xml?.WriteElementString("SourceCreated", o.SourceCreated);
                            xml?.WriteElementString("SourceModified", o.SourceModified);
                            xml?.WriteElementString("SourceAccessed", o.SourceAccessed);

                            xml?.WriteElementString("LastRun", o.LastRun);

                            xml?.WriteElementString("PreviousRun0", $"{o.PreviousRun0}");
                            xml?.WriteElementString("PreviousRun1", $"{o.PreviousRun1}");
                            xml?.WriteElementString("PreviousRun2", $"{o.PreviousRun2}");
                            xml?.WriteElementString("PreviousRun3", $"{o.PreviousRun3}");
                            xml?.WriteElementString("PreviousRun4", $"{o.PreviousRun4}");
                            xml?.WriteElementString("PreviousRun5", $"{o.PreviousRun5}");
                            xml?.WriteElementString("PreviousRun6", $"{o.PreviousRun6}");

                            xml?.WriteStartElement("ExecutableName");
                            xml?.WriteAttributeString("title",
                                                      "Note: The name of the executable tracked by the pf file");
                            xml?.WriteString(o.ExecutableName);
                            xml?.WriteEndElement();

                            xml?.WriteElementString("RunCount", $"{o.RunCount}");

                            xml?.WriteStartElement("Size");
                            xml?.WriteAttributeString("title", "Note: The size of the executable in bytes");
                            xml?.WriteString(o.Size);
                            xml?.WriteEndElement();

                            xml?.WriteStartElement("Hash");
                            xml?.WriteAttributeString("title",
                                                      "Note: The calculated hash for the pf file that should match the hash in the source file name");
                            xml?.WriteString(o.Hash);
                            xml?.WriteEndElement();

                            xml?.WriteStartElement("Version");
                            xml?.WriteAttributeString("title",
                                                      "Note: The operating system that generated the prefetch file");
                            xml?.WriteString(o.Version);
                            xml?.WriteEndElement();

                            xml?.WriteElementString("Note", o.Note);

                            xml?.WriteElementString("Volume0Name", o.Volume0Name);
                            xml?.WriteElementString("Volume0Serial", o.Volume0Serial);
                            xml?.WriteElementString("Volume0Created", o.Volume0Created);

                            xml?.WriteElementString("Volume1Name", o.Volume1Name);
                            xml?.WriteElementString("Volume1Serial", o.Volume1Serial);
                            xml?.WriteElementString("Volume1Created", o.Volume1Created);


                            xml?.WriteStartElement("Directories");
                            xml?.WriteAttributeString("title",
                                                      "A comma separated list of all directories accessed by the executable");
                            xml?.WriteString(o.Directories);
                            xml?.WriteEndElement();

                            xml?.WriteStartElement("FilesLoaded");
                            xml?.WriteAttributeString("title",
                                                      "A comma separated list of all files that were loaded by the executable");
                            xml?.WriteString(o.FilesLoaded);
                            xml?.WriteEndElement();

                            xml?.WriteEndElement();
                        }


                        //Close CSV stuff
                        streamWriter?.Flush();
                        streamWriter?.Close();

                        streamWriterTl?.Flush();
                        streamWriterTl?.Close();

                        //Close XML
                        xml?.WriteEndElement();
                        xml?.WriteEndDocument();
                        xml?.Flush();
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error($"Error exporting data! Error: {ex.Message}");
                }
            }
        }
Beispiel #13
0
        // 解析告警图片文件夹
        private List <AlarmImage> ParseAlarmImage(string alarmImagePath)
        {
            if (Directory.Exists(alarmImagePath))
            {
                List <AlarmImage> images = new List <AlarmImage>();
                // 递归获取所有jpg文件
                string[] alarmImages = Utility.Director(alarmImagePath).Where(f =>
                {
                    string ex = Path.GetExtension(f);
                    return(ex == ".jpg" || ex == ".png" || ex == ".bmp");
                }).ToArray();

                // 图片命名方式: 视频名___事件_帧号.jpg
                int           _id       = 0;
                List <string> error_msg = new List <string>();
                foreach (string img in alarmImages)
                {
                    string   name = Path.GetFileNameWithoutExtension(img);
                    string[] strs = Regex.Split(name, "___", RegexOptions.IgnoreCase);
                    if (strs.Length < 2)
                    {
                        //MessageWindow.Show("告警图片命名格式错误\n" + img, this);
                        error_msg.Add(img);
                        continue;
                    }
                    string[] infos = strs[1].Split('_');
                    string   _scene;
                    string   _incident = infos[0];
                    string   _video    = strs[0];
                    var      _list     = videoInfoList.Where(f => Path.GetFileNameWithoutExtension(f.VideoName) == _video).ToList();
                    if (_list.Count > 0)
                    {
                        _video = _list[0].VideoName;
                        _scene = _list[0].Scene;
                    }
                    else
                    {
                        _video += ".h264";
                        _scene  = "UnKnown";
                    }

                    // 场景下拉列表
                    if (Scenes.Count(item => item.Name == _scene) == 0)
                    {
                        Scenes.Add(new SceneItem {
                            Display = _scene, Name = _scene
                        });
                    }

                    // 事件类型下拉列表
                    if (Incidents.Count(item => item.Name == _incident) == 0)
                    {
                        Incidents.Add(new IncidentItem {
                            Display = _incident, Name = _incident
                        });
                    }

                    var _alarmDataItem = new AlarmImage
                    {
                        ID            = _id++,
                        ImagePath     = img,
                        Video         = _video,
                        Scene         = _scene,
                        Incident      = _incident,
                        Frame         = Convert.ToInt32(infos[1]),
                        State         = DetectType.UnKnown,
                        IncidentCount = 0
                    };
                    images.Add(_alarmDataItem);
                }

                // 错误信息
                if (error_msg.Count > 0)
                {
                    StringBuilder error_str = new StringBuilder("告警图片格式错误:" + "\n");
                    error_msg.ForEach(it => error_str.Append(it + "\n"));
                    MessageWindow.Show(error_str.ToString());
                }
                return(images);
            }
            else
            {
                MessageWindow.ShowDialog($"无法访问告警图片文件夹 [{alarmImagePath}]", this);
            }
            return(null);
        }