Exemple #1
0
        private static Settings ReadConfig()
        {
            string configPath = Path.Combine(Environment.CurrentDirectory, "RomVault3cfg.xml");

            if (!File.Exists(configPath))
            {
                Console.WriteLine($"{configPath} not Found");
                return(null);
            }
            Console.WriteLine($"Reading {configPath}");
            string strXml = System.IO.File.ReadAllText(configPath);

            // converting old enum to new:
            strXml = strXml.Replace("TrrntZipLevel", "Level");

            Settings retSettings;

            using (TextReader sr = new StringReader(strXml))
            {
                XmlSerializer x = new XmlSerializer(typeof(Settings));
                retSettings = (Settings)x.Deserialize(sr);
            }

            foreach (var rule in retSettings.DatRules)
            {
                if (rule.Merge == MergeType.CHDsMerge)
                {
                    rule.Merge  = MergeType.Merge;
                    rule.Filter = FilterType.CHDsOnly;
                }
            }

            return(retSettings);
        }
Exemple #2
0
        private static void CreateDirForFile(string sFilename)
        {
            string strTemp = Path.GetDirectoryName(sFilename);

            if (string.IsNullOrEmpty(strTemp))
            {
                return;
            }

            if (Directory.Exists(strTemp))
            {
                return;
            }


            while ((strTemp.Length > 0) && !Directory.Exists(strTemp))
            {
                int pos = strTemp.LastIndexOf(Path.DirectorySeparatorChar);
                if (pos < 0)
                {
                    pos = 0;
                }
                strTemp = strTemp.Substring(0, pos);
            }

            while (sFilename.IndexOf(Path.DirectorySeparatorChar, strTemp.Length + 1) > 0)
            {
                strTemp = sFilename.Substring(0, sFilename.IndexOf(Path.DirectorySeparatorChar, strTemp.Length + 1));
                Directory.CreateDirectory(strTemp);
            }
        }
Exemple #3
0
        private static Settings ReadConfig()
        {
            if (!File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "RomVault3cfg.xml")))
            {
                return(null);
            }

            Settings retSettings;

            using (StreamReader sr = new StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "RomVault3cfg.xml")))
            {
                XmlSerializer x = new XmlSerializer(typeof(Settings));
                retSettings = (Settings)x.Deserialize(sr);
            }

            foreach (var rule in retSettings.DatRules)
            {
                if (rule.Merge == MergeType.CHDsMerge)
                {
                    rule.Merge  = MergeType.Merge;
                    rule.Filter = FilterType.CHDsOnly;
                }
            }

            return(retSettings);
        }
Exemple #4
0
        private static void ProcessDir(string dirName)
        {
            Console.WriteLine("Checking Dir : " + dirName);

            DirectoryInfo di = new DirectoryInfo(dirName);

            FileInfo[] fi = di.GetFiles();
            foreach (FileInfo f in fi)
            {
                string filename = f.FullName;
                string ext      = Path.GetExtension(filename)?.ToLower();
                if (!string.IsNullOrEmpty(ext) && (ext == ".zip" || ext == ".7z" || ext == ".iso"))
                {
                    tz.Process(new FileInfo(filename));
                }
            }

            if (_noRecursion)
            {
                return;
            }

            string[] directories = System.IO.Directory.GetDirectories(dirName);
            foreach (string dir in directories)
            {
                ProcessDir(dir);
            }
        }
Exemple #5
0
        public static void FromAFile(RvFile file, string directory, EScanLevel eScanLevel, ThreadWorker bgw, ref bool fileErrorAbort)
        {
            string    filename   = Path.Combine(directory, file.Name);
            ICompress fileToScan = new Compress.File.File();
            ZipReturn zr         = fileToScan.ZipFileOpen(filename, file.FileModTimeStamp);

            if (zr == ZipReturn.ZipFileLocked)
            {
                file.GotStatus = GotStatus.FileLocked;
                return;
            }

            if (zr != ZipReturn.ZipGood)
            {
                ReportError.Show("File: " + filename + " Error: " + zr + ". Scan Aborted.");
                file.GotStatus = GotStatus.FileLocked;
                fileErrorAbort = true;
                return;
            }

            if (_fs == null)
            {
                _fs = new FileScan();
            }
            List <FileScan.FileResults> fr = _fs.Scan(fileToScan, true, eScanLevel == EScanLevel.Level2 || eScanLevel == EScanLevel.Level3);

            file.HeaderFileType = fr[0].HeaderFileType;
            file.Size           = fr[0].Size;
            file.CRC            = fr[0].CRC;
            file.SHA1           = fr[0].SHA1;
            file.MD5            = fr[0].MD5;
            file.AltSize        = fr[0].AltSize;
            file.AltCRC         = fr[0].AltCRC;
            file.AltSHA1        = fr[0].AltSHA1;
            file.AltMD5         = fr[0].AltMD5;


            file.FileStatusSet(
                FileStatus.SizeVerified |
                (file.HeaderFileType != HeaderFileType.Nothing ? FileStatus.HeaderFileTypeFromHeader : 0) |
                (file.CRC != null ? FileStatus.CRCVerified : 0) |
                (file.SHA1 != null ? FileStatus.SHA1Verified : 0) |
                (file.MD5 != null ? FileStatus.MD5Verified : 0) |
                (file.AltSize != null ? FileStatus.AltSizeVerified : 0) |
                (file.AltCRC != null ? FileStatus.AltCRCVerified : 0) |
                (file.AltSHA1 != null ? FileStatus.AltSHA1Verified : 0) |
                (file.AltMD5 != null ? FileStatus.AltMD5Verified : 0)
                );

            if (fr[0].HeaderFileType == HeaderFileType.CHD)
            {
                CHD.CheckFile(file, directory);
                if (eScanLevel == EScanLevel.Level2 || eScanLevel == EScanLevel.Level3)
                {
                    Utils.ChdManCheck(file, directory, bgw, ref fileErrorAbort);
                }
            }
            fileToScan.ZipFileClose();
        }
Exemple #6
0
        private static bool LoadDirFromDat(RvDat rvDat, string rootName, HeaderFileType datFileType)
        {
            if (DatFileLoader.Next != "(")
            {
                DatUpdate.SendAndShowDat("( not found after game", DatFileLoader.Filename);
                return(false);
            }
            DatFileLoader.Gn();

            if (DatFileLoader.Next.ToLower() != "name")
            {
                DatUpdate.SendAndShowDat("Name not found as first object in ( )", DatFileLoader.Filename);
                return(false);
            }
            string fullname = VarFix.CleanFullFileName(DatFileLoader.GnRest());

            fullname = Path.Combine(rootName, fullname);

            DatFileLoader.Gn();

            while (DatFileLoader.Next != ")")
            {
                switch (DatFileLoader.Next.ToLower())
                {
                case "dir":
                    DatFileLoader.Gn();
                    if (!LoadDirFromDat(rvDat, fullname, datFileType))
                    {
                        return(false);
                    }
                    DatFileLoader.Gn();
                    break;

                case "game":
                    DatFileLoader.Gn();
                    if (!LoadGameFromDat(rvDat, fullname, datFileType))
                    {
                        return(false);
                    }
                    DatFileLoader.Gn();
                    break;

                case "resource":
                    DatFileLoader.Gn();
                    if (!LoadGameFromDat(rvDat, fullname, datFileType))
                    {
                        return(false);
                    }
                    DatFileLoader.Gn();
                    break;

                default:
                    DatUpdate.SendAndShowDat("Error Keyword " + DatFileLoader.Next + " not know in dir", DatFileLoader.Filename);
                    DatFileLoader.Gn();
                    break;
                }
            }
            return(true);
        }
Exemple #7
0
        public static bool ReadDat(string strFilename, out RvDat rvDat)
        {
            HeaderFileType datFileType = HeaderFileType.Nothing;

            rvDat = new RvDat();
            int errorCode = DatFileLoader.LoadDat(strFilename);

            if (errorCode != 0)
            {
                DatUpdate.ShowDat(new Win32Exception(errorCode).Message, strFilename);
                return(false);
            }

            string filename = Path.GetFileName(strFilename);

            DatFileLoader.Gn();
            if (DatFileLoader.EndOfStream())
            {
                return(false);
            }

            if (DatFileLoader.Next.ToLower() == "doscenter")
            {
                DatFileLoader.Gn();
                if (!LoadHeaderFromDat(filename, rvDat, out datFileType))
                {
                    return(false);
                }

                DatFileLoader.Gn();
            }

            while (!DatFileLoader.EndOfStream())
            {
                switch (DatFileLoader.Next.ToLower())
                {
                case "game":
                    DatFileLoader.Gn();
                    if (!LoadGameFromDat(rvDat, "", datFileType))
                    {
                        return(false);
                    }

                    DatFileLoader.Gn();
                    break;

                default:
                    DatUpdate.SendAndShowDat("Error on line " + DatFileLoader.LineNumber + ": key word '" + DatFileLoader.Next + "' not known", DatFileLoader.Filename);
                    DatFileLoader.Gn();
                    break;
                }
            }

            DatFileLoader.Close();
            return(true);
        }
Exemple #8
0
        public string FileNameInsideGame()
        {
            RvDir d = this as RvDir;

            if (d?.Game != null)
            {
                return(Name);
            }

            return(Path.Combine(Parent.FileNameInsideGame(), Name));
        }
Exemple #9
0
 public string ToSort()
 {
     foreach (DirMap t in DirPathMap)
     {
         if (t.DirKey == "ToSort")
         {
             return(t.DirPath);
         }
     }
     return(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ToSort"));
 }
Exemple #10
0
        public LocalFile GetLocalFile(int i)
        {
            LocalFile lf = new()
            {
                Filename         = Path.GetFileName(ZipFilename),
                UncompressedSize = UnCompressedSize,
                CRC          = this.CRC,
                IsDirectory  = false,
                ModifiedTime = MTime == 0 ? null : (long?)CompressUtils.UtcTicksFromUnixDateTime((int)MTime)
            };

            return(lf);
        }
Exemple #11
0
        public static void WriteConfig(Settings settings)
        {
            if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "RomVault3cfg.xml")))
            {
                File.Delete(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "RomVault3cfg.xml"));
            }

            using (StreamWriter sw = new StreamWriter(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "RomVault3cfg.xml")))
            {
                XmlSerializer x = new XmlSerializer(typeof(Settings));
                x.Serialize(sw, settings);
                sw.Flush();
            }
        }
Exemple #12
0
        public LocalFile GetLocalFile(int i)
        {
            LocalFile lf = new()
            {
                Filename         = Path.GetFileName(ZipFilename),
                UncompressedSize = _fileInfo != null ? (ulong)_fileInfo.Length : (ulong)_inStream.Length,
                CRC          = _crc,
                IsDirectory  = RVIO.Directory.Exists(ZipFilename),
                ModifiedTime = _fileInfo?.LastWriteTime,
                AccessedTime = _fileInfo?.LastAccessTime,
                CreatedTime  = _fileInfo?.CreationTime
            };

            return(lf);
        }
Exemple #13
0
        public static string GetPhysicalPath(string dirTree)
        {
            if (dirTree == null)
            {
                return(null);
            }

            string strFullPath = "";
            int    lenFound    = 0;

            foreach (DatRule dirPathMap in Settings.rvSettings.DatRules)
            {
                if (string.IsNullOrWhiteSpace(dirPathMap.DirPath))
                {
                    continue;
                }

                string dirKey    = dirPathMap.DirKey;
                int    dirKeyLen = dirKey.Length;

                if (dirTree.Length == dirKeyLen && string.Compare(dirTree, dirKey, StringComparison.Ordinal) == 0)
                {
                    if (lenFound < dirKeyLen)
                    {
                        string dirPath = dirPathMap.DirPath;
                        lenFound    = dirKeyLen;
                        strFullPath = dirPath;
                        continue;
                    }
                }

                if (dirTree.Length > dirKeyLen && string.Compare(dirTree.Substring(0, dirKeyLen + 1), dirKey + System.IO.Path.DirectorySeparatorChar, StringComparison.Ordinal) == 0)
                {
                    if (lenFound < dirKeyLen)
                    {
                        string dirPath = dirPathMap.DirPath;
                        lenFound    = dirKeyLen;
                        strFullPath = Path.Combine(dirPath, dirTree.Substring(dirKeyLen + 1));
                    }
                }
            }

            if (strFullPath == "")
            {
                strFullPath = dirTree;
            }
            return(strFullPath);
        }
Exemple #14
0
        public static void WriteConfig(Settings settings)
        {
            string configPath = Path.Combine(Environment.CurrentDirectory, "RomVault3cfg.xml");

            if (File.Exists(configPath))
            {
                File.Delete(configPath);
            }

            using (StreamWriter sw = new StreamWriter(configPath))
            {
                XmlSerializer x = new XmlSerializer(typeof(Settings));
                x.Serialize(sw, settings);
                sw.Flush();
            }
        }
Exemple #15
0
        public void WriteConfig()
        {
            //if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "RomVault2.cfg")))
            //    File.Delete(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "RomVault2.cfg"));
            if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "RomVault2cfg.xml")))
            {
                File.Delete(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "RomVault2cfg.xml"));
            }

            using (StreamWriter sw = new StreamWriter(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "RomVault2cfg.xml")))
            {
                XmlSerializer x = new XmlSerializer(Program.rvSettings.GetType());
                x.Serialize(sw, Program.rvSettings);
                sw.Flush();
            }
        }
Exemple #16
0
 private string SuperDatFileName(RvDat dat)
 {
     if (dat.AutoAddDirectory)
     {
         if ((Parent?.Parent == null) || (Parent.Parent.Dat != dat))
         {
             return(Name);
         }
     }
     else
     {
         if ((Parent == null) || (Parent.Dat != dat))
         {
             return(Name);
         }
     }
     return(Path.Combine(Parent.SuperDatFileName(dat), Name));
 }
Exemple #17
0
        public static void ChdManCheck(RvFile tFile, string directory, ThreadWorker thWrk, ref bool fileErrorAbort)
        {
            string filename = Path.Combine(directory, tFile.Name);

            if (tFile.FileStatusIs(FileStatus.AltSHA1FromHeader | FileStatus.AltSHA1Verified))
            {
                return;
            }
            thWrk.Report(new bgwText2(filename));

            CHD.CHDManCheck res = CHD.ChdmanCheck(filename, thWrk, out string error);
            switch (res)
            {
            case CHD.CHDManCheck.Good:
                tFile.FileStatusSet(
                    (tFile.AltSHA1 != null ? FileStatus.AltSHA1Verified : 0) |
                    (tFile.AltMD5 != null ? FileStatus.AltMD5Verified : 0)
                    );
                return;

            case CHD.CHDManCheck.Corrupt:
                thWrk.Report(new bgwShowError(filename, error));
                tFile.GotStatus = GotStatus.Corrupt;
                return;

            case CHD.CHDManCheck.CHDReturnError:
            case CHD.CHDManCheck.CHDUnknownError:
                thWrk.Report(new bgwShowError(filename, error));
                return;

            case CHD.CHDManCheck.ChdmanNotFound:
                return;

            case CHD.CHDManCheck.CHDNotFound:
                ReportError.Show("File: " + filename + " Error: Not Found scan Aborted.");
                fileErrorAbort = true;
                return;

            default:
                ReportError.UnhandledExceptionHandler(error);
                return;
            }
        }
Exemple #18
0
        public void SetDefaults()
        {
            CacheFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "RomVault2_" + DBVersion.Version + ".Cache");

            DatRoot = "DatRoot";

            ScanLevel = eScanLevel.Level2;
            FixLevel  = eFixLevel.TrrntZipLevel2;

            IgnoreFiles = new List <string> {
                "_ReadMe_.txt"
            };

            eInfo = new List <EmulatorInfo>();

            ResetDirectories();

            ReadConfig();

            DirPathMap.Sort();
        }
Exemple #19
0
        private static void Compare(RvFile dbDir, RvFile fileDir, bool report, bool enableCancel)
        {
            string   fullDir = dbDir.FullName;
            FileType ft      = dbDir.FileType;

            // now we scan down the dbDir and the scanDir, comparing them.
            // if we find a match we mark dbDir as found.
            // if we are missing a file in fileDir we mark that file in dbDir as missing.
            // if we find extra files in fileDir we add it to dbDir and mark it as unknown.
            // we also recurse into any sub directories.
            int dbIndex   = 0;
            int fileIndex = 0;


            while (dbIndex < dbDir.ChildCount || fileIndex < fileDir.ChildCount)
            {
                RvFile dbChild   = null;
                RvFile fileChild = null;
                int    res       = 0;

                if (dbIndex < dbDir.ChildCount && fileIndex < fileDir.ChildCount)
                {
                    dbChild   = dbDir.Child(dbIndex);
                    fileChild = fileDir.Child(fileIndex);
                    //Debug.WriteLine($@"{dbChild.Name} , {fileChild.Name}");
                    res = DBHelper.CompareName(dbChild, fileChild);
                }
                else if (fileIndex < fileDir.ChildCount)
                {
                    //Get any remaining filedir's
                    fileChild = fileDir.Child(fileIndex);
                    res       = 1;
                }
                else if (dbIndex < dbDir.ChildCount)
                {
                    //Get any remaining dbDir's
                    dbChild = dbDir.Child(dbIndex);
                    res     = -1;
                }

                if (report)
                {
                    if (fileChild != null)
                    {
                        long timenow = DateTime.Now.Ticks;
                        if (timenow - _lastUpdateTime > TimeSpan.TicksPerSecond / 10)
                        {
                            _lastUpdateTime = timenow;
                            _thWrk.Report(new bgwValue2(fileIndex + 1));
                            _thWrk.Report(new bgwText2(Path.Combine(fullDir, fileChild.Name)));
                        }
                    }
                }

                // if this file was found in the DB
                switch (res)
                {
                case 0:

                    if (dbChild == null || fileChild == null)
                    {
                        ReportError.SendAndShow("Error in File Scanning Code.");
                        break;
                    }

                    //Complete MultiName Compare
                    List <RvFile> dbs        = new List <RvFile>();
                    List <RvFile> files      = new List <RvFile>();
                    int           dbsCount   = 1;
                    int           filesCount = 1;

                    dbs.Add(dbChild);
                    files.Add(fileChild);

                    while (dbIndex + dbsCount < dbDir.ChildCount && DBHelper.CompareName(dbChild, dbDir.Child(dbIndex + dbsCount)) == 0)
                    {
                        dbs.Add(dbDir.Child(dbIndex + dbsCount));
                        dbsCount += 1;
                    }
                    while (fileIndex + filesCount < fileDir.ChildCount && DBHelper.CompareName(fileChild, fileDir.Child(fileIndex + filesCount)) == 0)
                    {
                        files.Add(fileDir.Child(fileIndex + filesCount));
                        filesCount += 1;
                    }

                    bool caseTest = files.Count > 1;
                    // if we only have one file, we don't need to test twice.
                    // so we need to do a case sensitive match first and then a case insensitive match
                    // indexCase=0 means do full case filename test
                    // indexCase=1 means do case insensitive test
                    for (int indexCase = (caseTest ? 0 : 1); indexCase < 2; indexCase += 1)
                    {
                        for (int indexfile = 0; indexfile < filesCount; indexfile++)
                        {
                            if (files[indexfile].SearchFound)
                            {
                                continue;
                            }

                            for (int indexdb = 0; indexdb < dbsCount; indexdb++)
                            {
                                if (dbs[indexdb].SearchFound)
                                {
                                    continue;
                                }

                                bool matched = Scanner.Compare.Phase1Test(dbs[indexdb], files[indexfile], EScanLevel, indexCase, out bool matchedAlt);
                                if (!matched)
                                {
                                    continue;
                                }

                                MatchFound(dbs[indexdb], files[indexfile], matchedAlt);
                                dbs[indexdb].SearchFound     = true;
                                files[indexfile].SearchFound = true;
                            }

                            if (files[indexfile].SearchFound)
                            {
                                continue;
                            }

                            for (int indexdb = 0; indexdb < dbsCount; indexdb++)
                            {
                                if (dbs[indexdb].SearchFound)
                                {
                                    continue;
                                }

                                bool matched = Scanner.Compare.Phase2Test(dbs[indexdb], files[indexfile], EScanLevel, indexCase, fullDir, _thWrk, ref _fileErrorAbort, out bool matchedAlt);
                                if (!matched)
                                {
                                    continue;
                                }

                                MatchFound(dbs[indexdb], files[indexfile], matchedAlt);
                                dbs[indexdb].SearchFound     = true;
                                files[indexfile].SearchFound = true;
                            }
                        }
                    }

                    for (int indexdb = 0; indexdb < dbsCount; indexdb++)
                    {
                        if (dbs[indexdb].SearchFound)
                        {
                            dbIndex++;
                            continue;
                        }
                        DBFileNotFound(dbs[indexdb], dbDir, ref dbIndex);
                    }

                    for (int indexfile = 0; indexfile < filesCount; indexfile++)
                    {
                        if (files[indexfile].SearchFound)
                        {
                            continue;
                        }
                        if (NewFileFound(files[indexfile], dbDir, dbIndex))
                        {
                            dbIndex++;
                        }
                    }

                    fileIndex += filesCount;
                    break;

                case 1:
                    if (NewFileFound(fileChild, dbDir, dbIndex))
                    {
                        dbIndex++;
                    }
                    fileIndex++;
                    break;

                case -1:
                    DBFileNotFound(dbChild, dbDir, ref dbIndex);
                    break;
                }

                if (_fileErrorAbort)
                {
                    return;
                }
                if (enableCancel && !DBTypeGet.isCompressedDir(ft) && _thWrk.CancellationPending)
                {
                    return;
                }
            }
        }
Exemple #20
0
        private static bool LoadBytes(RvFile tGame, string filename, out byte[] memBuffer)
        {
            memBuffer = null;

            int cCount = tGame.ChildCount;

            if (cCount == 0)
            {
                return(false);
            }

            int found = -1;

            for (int i = 0; i < cCount; i++)
            {
                RvFile rvf = tGame.Child(i);
                if (rvf.Name != filename || rvf.GotStatus != GotStatus.Got)
                {
                    continue;
                }
                found = i;
                break;
            }

            if (found == -1)
            {
                return(false);
            }

            try
            {
                switch (tGame.FileType)
                {
                case FileType.Zip:
                {
                    RvFile imagefile = tGame.Child(found);
                    if (imagefile.ZipFileHeaderPosition == null)
                    {
                        return(false);
                    }

                    Zip zf = new Zip();
                    if (zf.ZipFileOpen(tGame.FullNameCase, tGame.FileModTimeStamp, false) != ZipReturn.ZipGood)
                    {
                        return(false);
                    }

                    if (zf.ZipFileOpenReadStreamQuick((ulong)imagefile.ZipFileHeaderPosition, false,
                                                      out Stream stream, out ulong streamSize, out ushort _) != ZipReturn.ZipGood)
                    {
                        zf.ZipFileClose();
                        return(false);
                    }

                    memBuffer = new byte[streamSize];
                    stream.Read(memBuffer, 0, (int)streamSize);
                    zf.ZipFileClose();
                    return(true);
                }

                case FileType.Dir:
                {
                    string dirPath = tGame.FullNameCase;
                    string artwork = Path.Combine(dirPath, filename);
                    if (!File.Exists(artwork))
                    {
                        return(false);
                    }

                    RVIO.FileStream.OpenFileRead(artwork, out Stream stream);
                    memBuffer = new byte[stream.Length];
                    stream.Read(memBuffer, 0, memBuffer.Length);
                    stream.Close();
                    stream.Dispose();
                    return(true);
                }

                default:
                    return(false);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(false);
            }
        }
Exemple #21
0
        public static bool ReadDat(string strFilename, out RvDat rvDat)
        {
            HeaderFileType datFileType = HeaderFileType.Nothing;

            rvDat = new RvDat();
            int errorCode = DatFileLoader.LoadDat(strFilename);

            if (errorCode != 0)
            {
                DatUpdate.ShowDat(new Win32Exception(errorCode).Message, strFilename);
                return(false);
            }

            string filename = Path.GetFileName(strFilename);

            DatFileLoader.Gn();
            if (DatFileLoader.EndOfStream())
            {
                return(false);
            }

            if (DatFileLoader.Next.ToLower() == "[credits]")
            {
                if (!LoadHeaderFromDat(filename, rvDat, out datFileType, DatFileLoader.Next.ToLower()))
                {
                    return(false);
                }

                DatFileLoader.Gn();
            }
            else if (DatFileLoader.Next.ToLower() == "[dat]")
            {
                if (!LoadHeaderFromDat(filename, rvDat, out datFileType, DatFileLoader.Next.ToLower()))
                {
                    return(false);
                }

                DatFileLoader.Gn();
            }
            else if (DatFileLoader.Next.ToLower() == "[emulator]")
            {
                if (!LoadHeaderFromDat(filename, rvDat, out datFileType, DatFileLoader.Next.ToLower()))
                {
                    return(false);
                }

                DatFileLoader.Gn();
            }

            // Everything else if a rom/game
            string lastgame  = "";
            bool   foundgame = false;
            RvGame rvGame    = new RvGame();

            while (!DatFileLoader.EndOfStream())
            {
                // Set loop variables
                foundgame = true;
                string game = "", description = "", romof = "", cloneof = "";
                RvRom  rvRom = new RvRom();

                if (!LoadRomFromDat("", datFileType, out rvRom, out game, out description, out romof, out cloneof))
                {
                    return(false);
                }

                DatFileLoader.Gn();

                // If we have a new game finally, add the last one
                if (lastgame != game && lastgame != "")
                {
                    rvDat.AddGame(rvGame);
                    foundgame = false;
                    rvGame    = new RvGame();
                }

                // For everything else, add to the new rvGame
                rvGame.Name        = (String.IsNullOrEmpty(rvGame.Name) ? game : rvGame.Name);
                rvGame.Description = (String.IsNullOrEmpty(rvGame.Description) ? description : rvGame.Description);
                rvGame.CloneOf     = (String.IsNullOrEmpty(rvGame.CloneOf) ? cloneof : rvGame.CloneOf);
                rvGame.RomOf       = (String.IsNullOrEmpty(rvGame.RomOf) ? romof : rvGame.RomOf);
                rvGame.AddRom(rvRom);
                lastgame = game;
            }

            // If we had a lingering game, add it
            if (foundgame)
            {
                rvDat.AddGame(rvGame);
            }

            DatFileLoader.Close();
            return(true);
        }
Exemple #22
0
        public static bool ReadDat(ref RvDir tDat, string strFilename)
        {
            RvDir    tNow         = tDat;
            FileType thisFileType = FileType.ZipFile;

            int errorCode = DatFileLoader.LoadDat(strFilename);

            if (errorCode != 0)
            {
                DatUpdate.ShowDat(new Win32Exception(errorCode).Message, strFilename);
                return(false);
            }

            DatFileLoader.Gn();
            if (DatFileLoader.EndOfStream())
            {
                return(false);
            }
            if (DatFileLoader.Next.ToLower() == "clrmamepro")
            {
                _cleanFileNames = true;
                DatFileLoader.Gn();
                if (!LoadHeaderFromDat(ref tNow, ref thisFileType))
                {
                    return(false);
                }
                DatFileLoader.Gn();
            }
            if (DatFileLoader.Next.ToLower() == "romvault")
            {
                _cleanFileNames = false;
                DatFileLoader.Gn();
                if (!LoadHeaderFromDat(ref tNow, ref thisFileType))
                {
                    return(false);
                }
                DatFileLoader.Gn();
            }

            if (tNow.Dat == null)
            {
                tNow.Dat = new RvDat();
                string cleanedName = Path.GetFileNameWithoutExtension(strFilename);
                tNow.Dat.AddData(RvDat.DatData.DatName, cleanedName);
                tNow.Dat.AddData(RvDat.DatData.Description, cleanedName);
            }


            while (!DatFileLoader.EndOfStream())
            {
                switch (DatFileLoader.Next.ToLower())
                {
                case "dir":
                    DatFileLoader.Gn();
                    if (!LoadDirFromDat(ref tNow, ref thisFileType))
                    {
                        return(false);
                    }
                    DatFileLoader.Gn();
                    break;

                case "game":
                    DatFileLoader.Gn();
                    if (!LoadGameFromDat(ref tNow, false, thisFileType))
                    {
                        return(false);
                    }
                    DatFileLoader.Gn();
                    break;

                case "resource":
                    DatFileLoader.Gn();
                    if (!LoadGameFromDat(ref tNow, true, thisFileType))
                    {
                        return(false);
                    }
                    DatFileLoader.Gn();
                    break;

                case "emulator":
                    DatFileLoader.Gn();
                    if (!LoadEmulator())
                    {
                        return(false);
                    }
                    DatFileLoader.Gn();
                    break;

                default:
                    DatUpdate.SendAndShowDat(Resources.DatCmpReader_ReadDat_Error_keyword + DatFileLoader.Next + Resources.DatCmpReader_ReadDat_not_known, DatFileLoader.Filename);
                    DatFileLoader.Gn();
                    break;
                }
            }

            DatFileLoader.Close();

            return(true);
        }
Exemple #23
0
        public static RvFile FromADir(RvFile dbDir, EScanLevel eScanLevel, ThreadWorker bgw, ref bool fileErrorAbort)
        {
            string    fullDir   = dbDir.FullName;
            DatStatus datStatus = dbDir.IsInToSort ? DatStatus.InToSort : DatStatus.NotInDat;

            RvFile fileDir = new RvFile(FileType.Dir);


            DirectoryInfo oDir = new DirectoryInfo(fullDir);

            DirectoryInfo[] oDirs  = oDir.GetDirectories();
            FileInfo[]      oFiles = oDir.GetFiles();

            // add all the subdirectories into scanDir
            foreach (DirectoryInfo dir in oDirs)
            {
                RvFile tDir = new RvFile(FileType.Dir)
                {
                    Name             = dir.Name,
                    FileModTimeStamp = dir.LastWriteTime
                };
                tDir.SetStatus(datStatus, GotStatus.Got);
                fileDir.ChildAdd(tDir);
            }

            // add all the files into scanDir
            foreach (FileInfo oFile in oFiles)
            {
                string fName = oFile.Name;
                if (fName == "__RomVault.tmp")
                {
                    File.Delete(oFile.FullName);
                    continue;
                }
                string fExt = Path.GetExtension(oFile.Name);

                FileType ft = DBTypeGet.fromExtention(fExt);

                if (Settings.rvSettings.FilesOnly)
                {
                    ft = FileType.File;
                }

                RvFile tFile = new RvFile(ft)
                {
                    Name             = oFile.Name,
                    Size             = (ulong)oFile.Length,
                    FileModTimeStamp = oFile.LastWriteTime
                };
                tFile.FileStatusSet(FileStatus.SizeVerified);
                tFile.SetStatus(datStatus, GotStatus.Got);

                if (eScanLevel == EScanLevel.Level3 && tFile.FileType == FileType.File)
                {
                    FromAFile(tFile, fullDir, eScanLevel, bgw, ref fileErrorAbort);
                }

                fileDir.ChildAdd(tFile);
            }
            return(fileDir);
        }
Exemple #24
0
 public string Filename(int i)
 {
     return(Path.GetFileName(ZipFilename));
 }
Exemple #25
0
        public static TrrntZipStatus ReZipFiles(List <ZippedFile> zippedFiles, ICompress originalZipFile, byte[] buffer, StatusCallback statusCallBack, LogCallback logCallback, int threadId)
        {
            zipType inputType;

            switch (originalZipFile)
            {
            case Zip _:
                inputType = zipType.zip;
                break;

            case SevenZ _:
                inputType = zipType.sevenzip;
                break;

            case Compress.File.File _:
                inputType = zipType.iso;
                break;

            default:
                return(TrrntZipStatus.Unknown);
            }

            zipType outputType = Program.OutZip == zipType.both ? inputType : Program.OutZip;

            if (outputType == zipType.iso)
            {
                outputType = zipType.zip;
            }

            int bufferSize = buffer.Length;

            string filename    = originalZipFile.ZipFilename;
            string tmpFilename = Path.Combine(Path.GetDirectoryName(filename), Path.GetFileNameWithoutExtension(filename) + ".tmp");

            string outExt      = outputType == zipType.zip ? ".zip" : ".7z";
            string outfilename = Path.Combine(Path.GetDirectoryName(filename), Path.GetFileNameWithoutExtension(filename) + outExt);

            if (inputType != outputType)
            {
                if (File.Exists(outfilename))
                {
                    logCallback?.Invoke(threadId, "Error output " + outExt + " file already exists");
                    return(TrrntZipStatus.RepeatFilesFound);
                }
            }

            if (File.Exists(tmpFilename))
            {
                File.Delete(tmpFilename);
            }

            ICompress zipFileOut = outputType == zipType.zip ? new Zip() : (ICompress) new SevenZ();

            try
            {
                zipFileOut.ZipFileCreate(tmpFilename);


                ulong fileSizeTotal       = 0;
                ulong fileSizeProgress    = 0;
                int   filePercentReported = 20;
                foreach (ZippedFile f in zippedFiles)
                {
                    fileSizeTotal += f.Size;
                }

                // by now the zippedFiles have been sorted so just loop over them
                foreach (ZippedFile t in zippedFiles)
                {
                    if (Program.VerboseLogging)
                    {
                        logCallback?.Invoke(threadId, $"{t.Size,15}  {t.StringCRC}   {t.Name}");
                    }

                    Stream readStream = null;
                    ulong  streamSize = 0;

                    ZipReturn zrInput = ZipReturn.ZipUntested;
                    switch (originalZipFile)
                    {
                    case Zip z:
                        zrInput = z.ZipFileOpenReadStream(t.Index, false, out readStream, out streamSize, out ushort _);
                        break;

                    case SevenZ z7:
                        zrInput = z7.ZipFileOpenReadStream(t.Index, out readStream, out streamSize);
                        break;

                    case Compress.File.File zf:
                        zrInput = zf.ZipFileOpenReadStream(t.Index, out readStream, out streamSize);
                        break;
                    }


                    ZipReturn zrOutput = zipFileOut.ZipFileOpenWriteStream(false, true, t.Name, streamSize, 8, out Stream writeStream);

                    if ((zrInput != ZipReturn.ZipGood) || (zrOutput != ZipReturn.ZipGood))
                    {
                        //Error writing local File.
                        zipFileOut.ZipFileClose();
                        originalZipFile.ZipFileClose();
                        File.Delete(tmpFilename);
                        return(TrrntZipStatus.CorruptZip);
                    }

                    Stream crcCs = new CrcCalculatorStream(readStream, true);

                    ulong sizetogo = streamSize;
                    while (sizetogo > 0)
                    {
                        int sizenow = sizetogo > (ulong)bufferSize ? bufferSize : (int)sizetogo;

                        fileSizeProgress += (ulong)sizenow;
                        int filePercent = (int)((double)fileSizeProgress / fileSizeTotal * 20);
                        if (filePercent != filePercentReported)
                        {
                            statusCallBack?.Invoke(threadId, filePercent * 5);
                            filePercentReported = filePercent;
                        }

                        crcCs.Read(buffer, 0, sizenow);
                        writeStream.Write(buffer, 0, sizenow);
                        sizetogo = sizetogo - (ulong)sizenow;
                    }
                    writeStream.Flush();

                    crcCs.Close();
                    if (inputType != zipType.sevenzip)
                    {
                        originalZipFile.ZipFileCloseReadStream();
                    }

                    uint crc = (uint)((CrcCalculatorStream)crcCs).Crc;

                    if (t.CRC == null)
                    {
                        t.CRC = crc;
                    }

                    if (crc != t.CRC)
                    {
                        return(TrrntZipStatus.CorruptZip);
                    }

                    zipFileOut.ZipFileCloseWriteStream(t.ByteCRC);
                }
                statusCallBack?.Invoke(threadId, 100);

                zipFileOut.ZipFileClose();
                originalZipFile.ZipFileClose();
                File.Delete(filename);
                File.Move(tmpFilename, outfilename);

                return(TrrntZipStatus.ValidTrrntzip);
            }
            catch (Exception)
            {
                zipFileOut?.ZipFileCloseFailed();
                originalZipFile?.ZipFileClose();
                return(TrrntZipStatus.CorruptZip);
            }
        }
Exemple #26
0
        public static ReturnCode DecompressSource7ZipFile(RvFile zZipFileIn, bool includeGood, out string error)
        {
            byte[] buffer = new byte[BufferSize];

            RvFile cacheDir = DB.RvFileCache();

            string fileNameIn = zZipFileIn.FullName;

            SevenZ    zipFileIn = new SevenZ();
            ZipReturn zr1       = zipFileIn.ZipFileOpen(fileNameIn, zZipFileIn.TimeStamp, true);

            if (zr1 != ZipReturn.ZipGood)
            {
                error = "Error opening 7zip file for caching";
                return(ReturnCode.RescanNeeded);
            }

            RvFile outDir = new RvFile(FileType.Dir)
            {
                Name      = zZipFileIn.Name + ".cache",
                Parent    = cacheDir,
                DatStatus = DatStatus.InToSort,
                GotStatus = GotStatus.Got
            };

            int nameDirIndex = 0;

            while (cacheDir.ChildNameSearch(outDir, out int index) == 0)
            {
                nameDirIndex++;
                outDir.Name = zZipFileIn.Name + ".cache (" + nameDirIndex + ")";
            }
            cacheDir.ChildAdd(outDir);
            Directory.CreateDirectory(outDir.FullName);

            for (int i = 0; i < zipFileIn.LocalFilesCount(); i++)
            {
                if (zZipFileIn.Child(i).IsDir)
                {
                    continue;
                }
                RvFile thisFile = null;
                for (int j = 0; j < zZipFileIn.ChildCount; j++)
                {
                    if (zZipFileIn.Child(j).ZipFileIndex != i)
                    {
                        continue;
                    }
                    thisFile = zZipFileIn.Child(j);
                    break;
                }

                if (thisFile == null)
                {
                    error = "Error opening 7zip file for caching";
                    return(ReturnCode.RescanNeeded);
                }

                bool extract = true;

                // first check to see if we have a file  version of this compressed file somewhere else.
                foreach (RvFile f in thisFile.FileGroup.Files)
                {
                    if (f.FileType == FileType.File && f.GotStatus == GotStatus.Got)
                    {
                        extract = false;
                    }
                }
                if (!extract)
                {
                    continue;
                }


                extract = false;
                if (includeGood)
                {
                    // if this is the file we are fixing then pull out the correct files.
                    if (thisFile.RepStatus == RepStatus.Correct)
                    {
                        extract = true;
                    }
                }

                // next check to see if we need this extracted to fix another file
                foreach (RvFile f in thisFile.FileGroup.Files)
                {
                    if (f.RepStatus == RepStatus.CanBeFixed)
                    {
                        extract = true;
                        break;
                    }
                }

                if (!extract)
                {
                    continue;
                }

                string cleanedName = thisFile.Name;
                cleanedName = cleanedName.Replace("/", "-");
                cleanedName = cleanedName.Replace("\\", "-");

                RvFile outFile = new RvFile(FileType.File)
                {
                    Name           = cleanedName,
                    Size           = thisFile.Size,
                    CRC            = thisFile.CRC,
                    SHA1           = thisFile.SHA1,
                    MD5            = thisFile.MD5,
                    HeaderFileType = thisFile.HeaderFileType,
                    AltSize        = thisFile.AltSize,
                    AltCRC         = thisFile.AltCRC,
                    AltSHA1        = thisFile.AltSHA1,
                    AltMD5         = thisFile.AltMD5,
                    FileGroup      = thisFile.FileGroup
                };

                outFile.SetStatus(DatStatus.InToSort, GotStatus.Got);
                outFile.FileStatusSet(
                    FileStatus.HeaderFileTypeFromHeader |
                    FileStatus.SizeFromHeader | FileStatus.SizeVerified |
                    FileStatus.CRCFromHeader | FileStatus.CRCVerified |
                    FileStatus.SHA1FromHeader | FileStatus.SHA1Verified |
                    FileStatus.MD5FromHeader | FileStatus.MD5Verified |
                    FileStatus.AltSizeFromHeader | FileStatus.AltSizeVerified |
                    FileStatus.AltCRCFromHeader | FileStatus.AltCRCVerified |
                    FileStatus.AltSHA1FromHeader | FileStatus.AltSHA1Verified |
                    FileStatus.AltMD5FromHeader | FileStatus.AltMD5Verified
                    , thisFile);
                outFile.RepStatus = RepStatus.NeededForFix;

                zipFileIn.ZipFileOpenReadStream(i, out Stream readStream, out ulong unCompressedSize);

                string filenameOut = Path.Combine(outDir.FullName, outFile.Name);

                ThreadMD5  tmd5  = null;
                ThreadSHA1 tsha1 = null;

                ThreadCRC tcrc32 = new ThreadCRC();
                if (Settings.rvSettings.FixLevel != EFixLevel.Level1 && Settings.rvSettings.FixLevel != EFixLevel.TrrntZipLevel1)
                {
                    tmd5  = new ThreadMD5();
                    tsha1 = new ThreadSHA1();
                }

                int errorCode = FileStream.OpenFileWrite(filenameOut, out Stream writeStream);

                ulong sizetogo = unCompressedSize;
                while (sizetogo > 0)
                {
                    int sizenow = sizetogo > BufferSize ? BufferSize : (int)sizetogo;

                    try
                    {
                        readStream.Read(buffer, 0, sizenow);
                    }
                    catch (Exception ex)
                    {
                        if (ex is ZlibException || ex is DataErrorException)
                        {
                            ZipReturn zr = zipFileIn.ZipFileCloseReadStream();
                            if (zr != ZipReturn.ZipGood)
                            {
                                error = "Error Closing " + zr + " Stream :" + zipFileIn.ZipFilename;
                                return(ReturnCode.FileSystemError);
                            }

                            zipFileIn.ZipFileClose();
                            writeStream.Flush();
                            writeStream.Close();
                            if (filenameOut != null)
                            {
                                File.Delete(filenameOut);
                            }

                            thisFile.GotStatus = GotStatus.Corrupt;
                            error = "Unexpected corrupt archive file found:\n" + zZipFileIn.FullName +
                                    "\nRun Find Fixes, and Fix to continue fixing correctly.";
                            return(ReturnCode.SourceDataStreamCorrupt);
                        }

                        error = "Error reading Source File " + ex.Message;
                        return(ReturnCode.FileSystemError);
                    }

                    tcrc32.Trigger(buffer, sizenow);
                    tmd5?.Trigger(buffer, sizenow);
                    tsha1?.Trigger(buffer, sizenow);

                    tcrc32.Wait();
                    tmd5?.Wait();
                    tsha1?.Wait();

                    try
                    {
                        writeStream.Write(buffer, 0, sizenow);
                    }
                    catch (Exception e)
                    {
                        error = "Error writing out file. " + Environment.NewLine + e.Message;
                        return(ReturnCode.FileSystemError);
                    }
                    sizetogo = sizetogo - (ulong)sizenow;
                }
                writeStream.Flush();
                writeStream.Close();
                writeStream.Dispose();

                tcrc32.Finish();
                tmd5?.Finish();
                tsha1?.Finish();

                byte[] bCRC  = tcrc32.Hash;
                byte[] bMD5  = tmd5?.Hash;
                byte[] bSHA1 = tsha1?.Hash;

                tcrc32.Dispose();
                tmd5?.Dispose();
                tsha1?.Dispose();

                FileInfo fi = new FileInfo(filenameOut);
                outFile.TimeStamp = fi.LastWriteTime;

                if (bCRC != null && thisFile.CRC != null && !ArrByte.BCompare(bCRC, thisFile.CRC))
                {
                    // error in file.
                }
                if (bMD5 != null && thisFile.MD5 != null && !ArrByte.BCompare(bMD5, thisFile.MD5))
                {
                    // error in file.
                }
                if (bSHA1 != null && thisFile.SHA1 != null && !ArrByte.BCompare(bSHA1, thisFile.SHA1))
                {
                    // error in file.
                }

                thisFile.FileGroup.Files.Add(outFile);

                outDir.ChildAdd(outFile);
            }

            zipFileIn.ZipFileClose();

            error = "";
            return(ReturnCode.Good);
        }
Exemple #27
0
        public static void FromAFile(RvFile file, string directory, EScanLevel eScanLevel, ThreadWorker bgw, ref bool fileErrorAbort)
        {
            _bgw = bgw;
            string    filename   = Path.Combine(directory, string.IsNullOrWhiteSpace(file.FileName) ? file.Name : file.FileName);
            ICompress fileToScan = new Compress.File.File();
            ZipReturn zr         = fileToScan.ZipFileOpen(filename, file.FileModTimeStamp);

            if (zr == ZipReturn.ZipFileLocked)
            {
                file.GotStatus = GotStatus.FileLocked;
                return;
            }

            if (zr != ZipReturn.ZipGood)
            {
                ReportError.Show("File: " + filename + " Error: " + zr + ". Scan Aborted.");
                file.GotStatus = GotStatus.FileLocked;
                fileErrorAbort = true;
                return;
            }

            if (_fs == null)
            {
                _fs = new FileScan();
            }
            List <FileScan.FileResults> fr = _fs.Scan(fileToScan, true, eScanLevel == EScanLevel.Level2 || eScanLevel == EScanLevel.Level3);

            file.HeaderFileType = fr[0].HeaderFileType;
            file.Size           = fr[0].Size;
            file.CRC            = fr[0].CRC;
            file.SHA1           = fr[0].SHA1;
            file.MD5            = fr[0].MD5;
            file.AltSize        = fr[0].AltSize;
            file.AltCRC         = fr[0].AltCRC;
            file.AltSHA1        = fr[0].AltSHA1;
            file.AltMD5         = fr[0].AltMD5;


            file.FileStatusSet(
                FileStatus.SizeVerified |
                (file.HeaderFileType != HeaderFileType.Nothing ? FileStatus.HeaderFileTypeFromHeader : 0) |
                (file.CRC != null ? FileStatus.CRCVerified : 0) |
                (file.SHA1 != null ? FileStatus.SHA1Verified : 0) |
                (file.MD5 != null ? FileStatus.MD5Verified : 0) |
                (file.AltSize != null ? FileStatus.AltSizeVerified : 0) |
                (file.AltCRC != null ? FileStatus.AltCRCVerified : 0) |
                (file.AltSHA1 != null ? FileStatus.AltSHA1Verified : 0) |
                (file.AltMD5 != null ? FileStatus.AltMD5Verified : 0)
                );

            if (fr[0].HeaderFileType == HeaderFileType.CHD)
            {
                bool deepCheck = (eScanLevel == EScanLevel.Level2 || eScanLevel == EScanLevel.Level3);
                CHD.fileProcess     = FileProcess;
                CHD.fileProgress    = FileProgress;
                CHD.fileSystemError = FileSystemError;
                CHD.fileError       = FileError;
                CHD.generalError    = GeneralError;
                hdErr result = CHD.CheckFile(file.Name, directory, Settings.isLinux, ref deepCheck, out uint?chdVersion, out byte[] chdSHA1, out byte[] chdMD5, ref fileErrorAbort);
                switch (result)
                {
                case hdErr.HDERR_NONE:
                    file.CHDVersion = chdVersion;
                    if (chdSHA1 != null)
                    {
                        file.AltSHA1 = chdSHA1;
                        file.FileStatusSet(FileStatus.AltSHA1FromHeader);
                        if (deepCheck)
                        {
                            file.FileStatusSet(FileStatus.AltSHA1Verified);
                        }
                    }

                    if (chdMD5 != null)
                    {
                        file.AltMD5 = chdMD5;
                        file.FileStatusSet(FileStatus.AltMD5FromHeader);
                        if (deepCheck)
                        {
                            file.FileStatusSet(FileStatus.AltMD5Verified);
                        }
                    }
                    break;

                case hdErr.HDERR_OUT_OF_MEMORY:
                case hdErr.HDERR_INVALID_FILE:
                case hdErr.HDERR_INVALID_DATA:
                case hdErr.HDERR_READ_ERROR:
                case hdErr.HDERR_DECOMPRESSION_ERROR:
                case hdErr.HDERR_CANT_VERIFY:
                    file.GotStatus = GotStatus.Corrupt;
                    break;

                default:
                    ReportError.UnhandledExceptionHandler(result.ToString());
                    break;
                }
            }
            fileToScan.ZipFileClose();
        }
Exemple #28
0
        public static RvFile FromADir(RvFile dbDir, EScanLevel eScanLevel, ThreadWorker bgw, ref bool fileErrorAbort)
        {
            string    fullDir   = dbDir.FullName;
            DatStatus datStatus = dbDir.IsInToSort ? DatStatus.InToSort : DatStatus.NotInDat;

            RvFile fileDir = new RvFile(FileType.Dir);


            DirectoryInfo oDir = new DirectoryInfo(fullDir);

            DirectoryInfo[] oDirs  = oDir.GetDirectories();
            FileInfo[]      oFiles = oDir.GetFiles();

            // add all the subdirectories into scanDir
            foreach (DirectoryInfo dir in oDirs)
            {
                RvFile tDir = new RvFile(FileType.Dir)
                {
                    Name             = dir.Name,
                    FileModTimeStamp = dir.LastWriteTime
                };
                tDir.SetStatus(datStatus, GotStatus.Got);
                fileDir.ChildAdd(tDir);
            }

            // add all the files into scanDir
            foreach (FileInfo oFile in oFiles)
            {
                string fName = oFile.Name;
                if (fName == "__RomVault.tmp")
                {
                    File.Delete(oFile.FullName);
                    continue;
                }
                string fExt = Path.GetExtension(oFile.Name);

                FileType ft = DBTypeGet.fromExtention(fExt);

                if (Settings.rvSettings.FilesOnly)
                {
                    ft = FileType.File;
                }

                RvFile tFile = new RvFile(ft)
                {
                    Name             = oFile.Name,
                    Size             = (ulong)oFile.Length,
                    FileModTimeStamp = oFile.LastWriteTime
                };
                tFile.FileStatusSet(FileStatus.SizeVerified);
                tFile.SetStatus(datStatus, GotStatus.Got);

                if (eScanLevel == EScanLevel.Level3 && tFile.FileType == FileType.File)
                {
                    FromAFile(tFile, fullDir, eScanLevel, bgw, ref fileErrorAbort);
                }

                fileDir.ChildAdd(tFile);

                /*
                 * // if we find a zip file add it as zip files.
                 * // else
                 * if (ft == FileType.File)
                 * {
                 * // Scanning a file
                 * //
                 * // Level1 & 2 : (are the same for files) Fully checksum changed only files
                 * // Here we are just getting the TimeStamp of the File, and later
                 * // if the TimeStamp was not matched we will have to read the files CRC, MD5 & SHA1
                 * //
                 * // Level3: Fully checksum everything
                 * // Get everything about the file right here so
                 * // read CRC, MD5 & SHA1
                 *
                 * errorCode = CHD.CheckFile(oFile, out tFile.AltSHA1, out tFile.AltMD5, out tFile.CHDVersion);
                 *
                 * if (errorCode == 0)
                 * {
                 *  if (tFile.AltSHA1 != null)
                 *  {
                 *      tFile.FileStatusSet(FileStatus.AltSHA1FromHeader);
                 *  }
                 *  if (tFile.AltMD5 != null)
                 *  {
                 *      tFile.FileStatusSet(FileStatus.AltMD5FromHeader);
                 *  }
                 *
                 *  // if we are scanning at Level3 then we get all the info here
                 *  if (EScanLevel == EScanLevel.Level3)
                 *  {
                 *      FileResults(fullDir, tFile);
                 *      ChdManCheck(fullDir, tFile);
                 *  }
                 * }
                 * else if (errorCode == 32)
                 * {
                 *  tFile.GotStatus = GotStatus.FileLocked;
                 *  _bgw.Report(new bgwShowError(fullDir, "File Locked"));
                 * }
                 * else
                 * {
                 *  string filename = Path.Combine(fullDir, tFile.Name);
                 *  ReportError.Show("File: " + filename + " Error: " + new Win32Exception(errorCode).Message + ". Scan Aborted.");
                 *  _fileErrorAbort = true;
                 *  return fileDir;
                 * }
                 * }
                 */
            }
            return(fileDir);
        }
Exemple #29
0
        private static void ScanRomRoot(string directory)
        {
            _bgw.ReportProgress(0, new bgwText("Scanning Dir : " + directory));
            DirectoryInfo di = new DirectoryInfo(directory);

            FileInfo[] fi = di.GetFiles();

            _bgw.ReportProgress(0, new bgwRange2Visible(true));
            _bgw.ReportProgress(0, new bgwSetRange2(fi.Count()));

            for (int j = 0; j < fi.Count(); j++)
            {
                if (_bgw.CancellationPending)
                {
                    return;
                }

                FileInfo f = fi[j];
                _bgw.ReportProgress(0, new bgwValue2(j));
                _bgw.ReportProgress(0, new bgwText2(f.Name));
                string ext = Path.GetExtension(f.Name);

                if (ext.ToLower() == ".gz")
                {
                    gZip      gZipTest  = new gZip();
                    ZipReturn errorcode = gZipTest.ZipFileOpen(f.FullName);
                    if (errorcode != ZipReturn.ZipGood)
                    {
                        _bgw.ReportProgress(0, new bgwShowError(f.FullName, "gz File corrupt"));
                        if (!Directory.Exists("corrupt"))
                        {
                            Directory.CreateDirectory("corrupt");
                        }
                        File.Move(f.FullName, Path.Combine("corrupt", f.Name));
                        continue;
                    }

                    RvFile tFile = RvFile.fromGZip(f.FullName, gZipTest.ExtraData, gZipTest.CompressedSize);
                    gZipTest.ZipFileClose();

                    FindStatus res = fileneededTest(tFile);

                    if (res != FindStatus.FoundFileInArchive)
                    {
                        if (deep)
                        {
                            gZipTest = new gZip();

                            try
                            {
                                errorcode = gZipTest.ZipFileOpen(f.FullName);
                                if (errorcode == ZipReturn.ZipGood)
                                {
                                    FileScan fs = new FileScan();
                                    List <FileScan.FileResults> gRes = fs.Scan(gZipTest, true, true);
                                    errorcode = gRes[0].FileStatus;
                                    gZipTest.ZipFileClose();
                                }
                            }
                            catch
                            {
                                gZipTest.ZipFileClose();
                                _bgw.ReportProgress(0, new bgwShowError(f.FullName, "gz Crashed Compression"));
                                if (!Directory.Exists("corrupt"))
                                {
                                    Directory.CreateDirectory("corrupt");
                                }
                                File.Move(f.FullName, Path.Combine("corrupt", f.Name));
                                continue;
                            }

                            if (errorcode != ZipReturn.ZipGood)
                            {
                                _bgw.ReportProgress(0, new bgwShowError(f.FullName, "gz File corrupt"));
                                if (!Directory.Exists("corrupt"))
                                {
                                    Directory.CreateDirectory("corrupt");
                                }
                                File.Move(f.FullName, Path.Combine("corrupt", f.Name));
                                continue;
                            }
                        }
                        tFile.DBWrite();
                    }
                }
                if (_bgw.CancellationPending)
                {
                    return;
                }
            }

            DirectoryInfo[] childdi = di.GetDirectories();
            foreach (DirectoryInfo d in childdi)
            {
                if (_bgw.CancellationPending)
                {
                    return;
                }
                ScanRomRoot(d.FullName);
            }
        }
Exemple #30
0
        private static void Main(string[] args)
        {
            try
            {
                if (args.Length == 0)
                {
                    Console.WriteLine("");
                    Console.WriteLine("trrntzip: missing path");
                    Console.WriteLine("Usage: trrntzip [OPTIONS] [PATH/ZIP FILES]");
                    return;
                }

                for (int i = 0; i < args.Length; i++)
                {
                    string arg = args[i];
                    if (arg.Length < 2)
                    {
                        continue;
                    }
                    if (arg.Substring(0, 1) != "-")
                    {
                        continue;
                    }

                    switch (arg.Substring(1, 1))
                    {
                    case "?":
                        Console.WriteLine($"TorrentZip.Net v{Assembly.GetExecutingAssembly().GetName().Version.ToString(3)}");
                        Console.WriteLine("");
                        Console.WriteLine("Copyright (C) 2020 GordonJ");
                        Console.WriteLine("Homepage : http://www.romvault.com/trrntzip");
                        Console.WriteLine("");
                        Console.WriteLine("Usage: trrntzip [OPTIONS] [PATH/ZIP FILE]");
                        Console.WriteLine("");
                        Console.WriteLine("Options:");
                        Console.WriteLine("");
                        Console.WriteLine("-? : show this help");
                        Console.WriteLine("-s : prevent sub-directory recursion");
                        Console.WriteLine("-f : force re-zip");
                        Console.WriteLine("-c : Check files only do not repair");
                        Console.WriteLine("-l : verbose logging");
                        Console.WriteLine("-v : show version");
                        Console.WriteLine("-g : pause when finished");
                        return;

                    case "s":
                        _noRecursion = true;
                        break;

                    case "f":
                        Trrntzip.Program.ForceReZip = true;
                        break;

                    case "c":
                        Trrntzip.Program.CheckOnly = true;
                        break;

                    case "l":
                        Trrntzip.Program.VerboseLogging = true;
                        string logtime = DateTime.Now.ToString("yyyy-MM-dd-HHmmss");
                        logStream = new StreamWriter($"outlog-{logtime}.txt");
                        break;

                    case "v":
                        Console.WriteLine("TorrentZip v{0}", Assembly.GetExecutingAssembly().GetName().Version);
                        return;

                    case "g":
                        _guiLaunch = true;
                        break;
                    }
                }

                tz = new TorrentZip
                {
                    StatusCallBack    = StatusCallBack,
                    StatusLogCallBack = StatusLogCallBack
                };

                foreach (string tArg in args)
                {
                    string arg = tArg;
                    if (arg.Length < 2)
                    {
                        continue;
                    }
                    if (arg.Substring(0, 1) == "-")
                    {
                        continue;
                    }

                    if (arg.Length > 2 && arg.Substring(0, 2) == ".\\")
                    {
                        arg = arg.Substring(2);
                    }
                    // first check if arg is a directory
                    if (Directory.Exists(arg))
                    {
                        ProcessDir(arg);
                        continue;
                    }

                    // now check if arg is a directory/filename with possible wild cards.

                    string dir = Path.GetDirectoryName(arg);
                    if (string.IsNullOrEmpty(dir))
                    {
                        dir = Environment.CurrentDirectory;
                    }

                    string filename = Path.GetFileName(arg);

                    DirectoryInfo dirInfo  = new DirectoryInfo(dir);
                    FileInfo[]    fileInfo = dirInfo.GetFiles(filename);
                    foreach (FileInfo file in fileInfo)
                    {
                        string ext = Path.GetExtension(file.FullName).ToLower();
                        if (!string.IsNullOrEmpty(ext) && ((ext == ".zip") || (ext == ".7z") || (ext == ".iso")))
                        {
                            tz.Process(new FileInfo(file.FullName));
                        }
                    }
                }

                logStream?.Flush();
                logStream?.Close();
                logStream?.Dispose();
                logStream = null;

                if (_guiLaunch)
                {
                    Console.WriteLine("Complete.");
                    Console.ReadLine();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} Exception caught.", e);
                logStream?.WriteLine("{0} Exception caught.", e);
                logStream?.Flush();
                logStream?.Close();
                logStream?.Dispose();
                logStream = null;
            }
        }