Esempio n. 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);
        }
Esempio n. 2
0
        public static void Write()
        {
            if (File.Exists(Program.rvSettings.CacheFile))
            {
                string bname = Program.rvSettings.CacheFile + "Backup";
                if (File.Exists(bname))
                {
                    File.Delete(bname);
                }
                File.Move(Program.rvSettings.CacheFile, bname);
            }
            FileStream   fs = new FileStream(Program.rvSettings.CacheFile, FileMode.CreateNew, FileAccess.Write);
            BinaryWriter bw = new BinaryWriter(fs);

            DBVersion.VersionNow = DBVersion.Version;
            bw.Write(DBVersion.Version);
            DirTree.Write(bw);

            bw.Write(EndCacheMarker);

            bw.Flush();
            bw.Close();

            fs.Close();
            fs.Dispose();
        }
Esempio n. 3
0
        public static void Write()
        {
            string tname = Settings.rvSettings.CacheFile + "_tmp";

            if (File.Exists(tname))
            {
                File.Delete(tname);

                while (File.Exists(tname))
                {
                    Thread.Sleep(50);
                }
            }

            try
            {
                using (FileStream fs = new FileStream(tname, FileMode.CreateNew, FileAccess.Write))
                {
                    using (BinaryWriter bw = new BinaryWriter(fs, Encoding.UTF8, true))
                    {
                        DBVersion.VersionNow = DBVersion.Version;
                        bw.Write(DBVersion.Version);
                        DirRoot.Write(bw);

                        bw.Write(EndCacheMarker);

                        bw.Flush();
                        bw.Close();
                    }

                    fs.Close();
                }
            }
            catch (Exception e)
            {
                ReportError.UnhandledExceptionHandler($"Error Writing Cache File, your cache is now out of date, fix this error and rescan: {e.Message}");
                return;
            }

            if (File.Exists(Settings.rvSettings.CacheFile))
            {
                string bname = Settings.rvSettings.CacheFile + "Backup";
                if (File.Exists(bname))
                {
                    File.Delete(bname);

                    while (File.Exists(bname))
                    {
                        Thread.Sleep(50);
                    }
                }
                File.Move(Settings.rvSettings.CacheFile, bname);
                while (File.Exists(Settings.rvSettings.CacheFile))
                {
                    Thread.Sleep(50);
                }
            }

            File.Move(tname, Settings.rvSettings.CacheFile);
        }
Esempio n. 4
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);
        }
Esempio n. 5
0
        public static void Read(ThreadWorker thWrk)
        {
            ThWrk = thWrk;
            if (!File.Exists(Settings.rvSettings.CacheFile))
            {
                OpenDefaultDB();
                ThWrk = null;
                return;
            }
            DirRoot = new RvFile(FileType.Dir);
            using (FileStream fs = new FileStream(Settings.rvSettings.CacheFile, FileMode.Open, FileAccess.Read))
            {
                if (fs.Length < 4)
                {
                    ReportError.UnhandledExceptionHandler("Cache is Corrupt, revert to Backup.");
                }

                using (BinaryReader br = new BinaryReader(fs, Encoding.UTF8, true))
                {
                    DivideProgress = fs.Length / 1000;

                    DivideProgress = DivideProgress == 0 ? 1 : DivideProgress;

                    ThWrk?.Report(new bgwSetRange(1000));

                    DBVersion.VersionNow = br.ReadInt32();

                    if (DBVersion.VersionNow != DBVersion.Version)
                    {
                        ReportError.Show(
                            "Data Cache version is out of date you should now rescan your dat directory and roms directory.");
                        br.Close();
                        fs.Close();
                        fs.Dispose();

                        OpenDefaultDB();
                        ThWrk = null;
                        return;
                    }
                    else
                    {
                        DirRoot.Read(br, null);
                    }

                    if (fs.Position > fs.Length - 8)
                    {
                        ReportError.UnhandledExceptionHandler("Cache is Corrupt, revert to Backup.");
                    }

                    ulong testEOF = br.ReadUInt64();
                    if (testEOF != EndCacheMarker)
                    {
                        ReportError.UnhandledExceptionHandler("Cache is Corrupt, revert to Backup.");
                    }
                }
            }

            ThWrk = null;
        }
Esempio n. 6
0
        // if we are fixing a zip/7z file then we use zipFileOut to open an output compressed stream
        // if we are just making a file then we use filenameOut to open an output filestream
        private static ReturnCode OpenOutputStream(RvFile fileOut, RvFile fileIn, ICompress zipFileOut, string filenameOut, ushort compressionMethod, bool rawCopy, bool sourceTrrntzip, long?dateTime, out Stream writeStream, out string error)
        {
            writeStream = null;

            if (fileOut.FileType == FileType.ZipFile || fileOut.FileType == FileType.SevenZipFile)
            {
                // if ZipFileOut == null then we have not open the output zip yet so open it from writing.
                if (zipFileOut == null)
                {
                    error = "zipFileOut cannot be null";
                    return(ReturnCode.FileSystemError);
                }

                if (zipFileOut.ZipOpen != ZipOpenType.OpenWrite)
                {
                    error = "Output Zip File is not set to OpenWrite, Logic Error.";
                    return(ReturnCode.LogicError);
                }

                if (fileIn.Size == null)
                {
                    error = "Null File Size found in Fixing File :" + fileIn.FullName;
                    return(ReturnCode.LogicError);
                }
                TimeStamps ts = null;
                if (dateTime != null)
                {
                    ts = new TimeStamps {
                        ModTime = dateTime
                    };
                }

                ZipReturn zr = zipFileOut.ZipFileOpenWriteStream(rawCopy, sourceTrrntzip, fileOut.Name, (ulong)fileIn.Size, compressionMethod, out writeStream, ts);
                if (zr != ZipReturn.ZipGood)
                {
                    error = "Error Opening Write Stream " + zr;
                    return(ReturnCode.FileSystemError);
                }
            }
            else
            {
                if (File.Exists(filenameOut) && fileOut.GotStatus != GotStatus.Corrupt)
                {
                    error = "Rescan needed, File Changed :" + filenameOut;
                    return(ReturnCode.RescanNeeded);
                }
                int errorCode = FileStream.OpenFileWrite(filenameOut, out writeStream);
                if (errorCode != 0)
                {
                    error = new Win32Exception(errorCode).Message + ". " + filenameOut;
                    return(ReturnCode.FileSystemError);
                }
            }


            error = "";
            return(ReturnCode.Good);
        }
Esempio n. 7
0
        public static void Read(object sender, DoWorkEventArgs e)
        {
            Bgw = sender as BackgroundWorker;
            Program.SyncCont = e.Argument as SynchronizationContext;

            if (!File.Exists(Program.rvSettings.CacheFile))
            {
                OpenDefaultDB();
                Bgw = null;
                Program.SyncCont = null;
                return;
            }
            DirTree = new RvDir(FileType.Dir);
            FileStream fs = new FileStream(Program.rvSettings.CacheFile, FileMode.Open, FileAccess.Read);

            if (fs.Length < 4)
            {
                ReportError.UnhandledExceptionHandler("Cache is Corrupt, revert to Backup.");
            }


            BinaryReader br = new BinaryReader(fs);

            Bgw?.ReportProgress(0, new bgwSetRange((int)fs.Length));

            DBVersion.VersionNow = br.ReadInt32();

            if (DBVersion.VersionNow != DBVersion.Version)
            {
                ReportError.Show(Resources.DB_Read_Data_Cache_version_is_out_of_date_you_should_now_rescan_your_dat_directory_and_roms_directory_);
                OpenDefaultDB();
            }
            else
            {
                DirTree.Read(br, null);
            }

            if (fs.Position > fs.Length - 8)
            {
                ReportError.UnhandledExceptionHandler("Cache is Corrupt, revert to Backup.");
            }

            ulong testEOF = br.ReadUInt64();

            if (testEOF != EndCacheMarker)
            {
                ReportError.UnhandledExceptionHandler("Cache is Corrupt, revert to Backup.");
            }

            br.Close();
            fs.Close();
            fs.Dispose();

            Bgw = null;
            Program.SyncCont = null;
        }
Esempio n. 8
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();
            }
        }
Esempio n. 9
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();
            }
        }
Esempio n. 10
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();
            }
        }
Esempio n. 11
0
        public ZipReturn ZipFileOpen(string filename, long timestamp, bool readHeaders)
        {
            ZipFileClose();
            _memoryZipFile = null;
            Debug.WriteLine(filename);
            #region open file stream

            try
            {
                if (!File.Exists(filename))
                {
                    ZipFileClose();
                    return(ZipReturn.ZipErrorFileNotFound);
                }
                _zipFileInfo = new FileInfo(filename);
                if ((timestamp != -1) && (_zipFileInfo.LastWriteTime != timestamp))
                {
                    ZipFileClose();
                    return(ZipReturn.ZipErrorTimeStamp);
                }
                int errorCode = FileStream.OpenFileRead(filename, out _zipFs);
                if (errorCode != 0)
                {
                    ZipFileClose();
                    return(ZipReturn.ZipErrorOpeningFile);
                }
            }
            catch (PathTooLongException)
            {
                ZipFileClose();
                return(ZipReturn.ZipFileNameToLong);
            }
            catch (IOException)
            {
                ZipFileClose();
                return(ZipReturn.ZipErrorOpeningFile);
            }

            #endregion

            ZipOpen   = ZipOpenType.OpenRead;
            ZipStatus = ZipStatus.None;

            return(ZipFileReadHeaders());
        }
Esempio n. 12
0
        public ZipReturn ReadGZip(string filename, bool deepScan)
        {
            _filename = "";
            if (!File.Exists(filename))
            {
                return(ZipReturn.ZipErrorFileNotFound);
            }
            _filename = filename;

            int errorCode = FileStream.OpenFileRead(filename, out _zipFs);

            if (errorCode != 0)
            {
                if (errorCode == 32)
                {
                    return(ZipReturn.ZipFileLocked);
                }
                return(ZipReturn.ZipErrorOpeningFile);
            }
            return(ReadBody(deepScan));
        }
Esempio n. 13
0
        public ZipReturn GetRawStream(out Stream st)
        {
            st = null;
            if (!File.Exists(_filename))
            {
                return(ZipReturn.ZipErrorFileNotFound);
            }

            int errorCode = FileStream.OpenFileRead(_filename, out st);

            if (errorCode != 0)
            {
                if (errorCode == 32)
                {
                    return(ZipReturn.ZipFileLocked);
                }
                return(ZipReturn.ZipErrorOpeningFile);
            }

            st.Position = datapos;

            return(ZipReturn.ZipGood);
        }
Esempio n. 14
0
        public static void Write()
        {
            if (File.Exists(Settings.rvSettings.CacheFile))
            {
                string bname = Settings.rvSettings.CacheFile + "Backup";
                if (File.Exists(bname))
                {
                    File.Delete(bname);

                    while (File.Exists(bname))
                    {
                        Thread.Sleep(50);
                    }
                }
                File.Move(Settings.rvSettings.CacheFile, bname);
                while (File.Exists(Settings.rvSettings.CacheFile))
                {
                    Thread.Sleep(50);
                }
            }
            FileStream fs = new FileStream(Settings.rvSettings.CacheFile, FileMode.CreateNew, FileAccess.Write);

            using (BinaryWriter bw = new BinaryWriter(fs, Encoding.UTF8, true))
            {
                DBVersion.VersionNow = DBVersion.Version;
                bw.Write(DBVersion.Version);
                DirTree.Write(bw);

                bw.Write(EndCacheMarker);

                bw.Flush();
                bw.Close();
            }

            fs.Close();
            fs.Dispose();
        }
Esempio n. 15
0
        private void ReadConfig()
        {
            if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "RomVault2cfg.xml")))
            {
                using (StreamReader sr = new StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "RomVault2cfg.xml")))
                {
                    XmlSerializer x = new XmlSerializer(Program.rvSettings.GetType());
                    Program.rvSettings = (Settings)x.Deserialize(sr);
                }
                return;
            }

            if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "RomVault2.cfg")))
            {
                FileStream   fs = new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "RomVault2.cfg"), FileMode.Open, FileAccess.Read);
                BinaryReader br = new BinaryReader(fs);

                int ver = br.ReadInt32();
                if (ver == 1)
                {
                    DatRoot   = br.ReadString();
                    ScanLevel = eScanLevel.Level1;
                    FixLevel  = (eFixLevel)br.ReadInt32();

                    IgnoreFiles = new List <string>();
                    int c = br.ReadInt32();
                    for (int i = 0; i < c; i++)
                    {
                        IgnoreFiles.Add(br.ReadString());
                    }

                    DirPathMap = new List <DirMap>();
                    c          = br.ReadInt32();
                    for (int i = 0; i < c; i++)
                    {
                        DirPathMap.Add(new DirMap(br.ReadString(), br.ReadString()));
                    }
                }
                if (ver == 2)
                {
                    DatRoot   = br.ReadString();
                    ScanLevel = (eScanLevel)br.ReadInt32();
                    FixLevel  = (eFixLevel)br.ReadInt32();

                    IgnoreFiles = new List <string>();
                    int c = br.ReadInt32();
                    for (int i = 0; i < c; i++)
                    {
                        IgnoreFiles.Add(br.ReadString());
                    }

                    DirPathMap = new List <DirMap>();
                    c          = br.ReadInt32();
                    for (int i = 0; i < c; i++)
                    {
                        DirPathMap.Add(new DirMap(br.ReadString(), br.ReadString()));
                    }
                }
                if (ver == 3)
                {
                    DatRoot          = br.ReadString();
                    ScanLevel        = (eScanLevel)br.ReadInt32();
                    FixLevel         = (eFixLevel)br.ReadInt32();
                    DebugLogsEnabled = br.ReadBoolean();

                    IgnoreFiles = new List <string>();
                    int c = br.ReadInt32();
                    for (int i = 0; i < c; i++)
                    {
                        IgnoreFiles.Add(br.ReadString());
                    }

                    DirPathMap = new List <DirMap>();
                    c          = br.ReadInt32();
                    for (int i = 0; i < c; i++)
                    {
                        DirPathMap.Add(new DirMap(br.ReadString(), br.ReadString()));
                    }
                }

                if (ver == 4)
                {
                    DatRoot          = br.ReadString();
                    ScanLevel        = (eScanLevel)br.ReadInt32();
                    FixLevel         = (eFixLevel)br.ReadInt32();
                    DebugLogsEnabled = br.ReadBoolean();

                    IgnoreFiles = new List <string>();
                    int c = br.ReadInt32();
                    for (int i = 0; i < c; i++)
                    {
                        IgnoreFiles.Add(br.ReadString());
                    }

                    DirPathMap = new List <DirMap>();
                    c          = br.ReadInt32();
                    for (int i = 0; i < c; i++)
                    {
                        DirPathMap.Add(new DirMap(br.ReadString(), br.ReadString()));
                    }

                    CacheSaveTimerEnabled = br.ReadBoolean();
                    CacheSaveTimePeriod   = br.ReadInt32();
                }

                if (ver == 5)
                {
                    DatRoot          = br.ReadString();
                    ScanLevel        = (eScanLevel)br.ReadInt32();
                    FixLevel         = (eFixLevel)br.ReadInt32();
                    DebugLogsEnabled = br.ReadBoolean();

                    IgnoreFiles = new List <string>();
                    int c = br.ReadInt32();
                    for (int i = 0; i < c; i++)
                    {
                        IgnoreFiles.Add(br.ReadString());
                    }

                    DirPathMap = new List <DirMap>();
                    c          = br.ReadInt32();
                    for (int i = 0; i < c; i++)
                    {
                        DirPathMap.Add(new DirMap(br.ReadString(), br.ReadString()));
                    }

                    CacheSaveTimerEnabled = br.ReadBoolean();
                    CacheSaveTimePeriod   = br.ReadInt32();

                    DoubleCheckDelete = br.ReadBoolean();
                }

                if (ver == 6)
                {
                    DatRoot          = br.ReadString();
                    ScanLevel        = (eScanLevel)br.ReadInt32();
                    FixLevel         = (eFixLevel)br.ReadInt32();
                    DebugLogsEnabled = br.ReadBoolean();
                    bool UserLongFilenames = br.ReadBoolean();

                    IgnoreFiles = new List <string>();
                    int c = br.ReadInt32();
                    for (int i = 0; i < c; i++)
                    {
                        IgnoreFiles.Add(br.ReadString());
                    }

                    DirPathMap = new List <DirMap>();
                    c          = br.ReadInt32();
                    for (int i = 0; i < c; i++)
                    {
                        DirPathMap.Add(new DirMap(br.ReadString(), br.ReadString()));
                    }

                    CacheSaveTimerEnabled = br.ReadBoolean();
                    CacheSaveTimePeriod   = br.ReadInt32();

                    DoubleCheckDelete = br.ReadBoolean();
                }


                br.Close();
                fs.Close();
            }
        }
Esempio n. 16
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);
            }
        }
Esempio n. 17
0
        public static hdErr CheckFile(string file, string directory, bool isLinux, ref bool deepCheck, out uint?chdVersion, out byte[] chdSHA1, out byte[] chdMD5, ref bool fileErrorAbort)
        {
            chdSHA1    = null;
            chdMD5     = null;
            chdVersion = null;
            string filename = Path.Combine(directory, file);

            fileProcess?.Invoke(filename);

            //string ext = Path.GetExtension(filename).ToLower();
            //if (ext != ".chd")
            //{
            //    return hdErr.HDERR_INVALID_FILE;
            //}

            if (!File.Exists(filename))
            {
                fileSystemError?.Invoke("File: " + filename + " Error: File Could not be opened.");
                fileErrorAbort = true;
                return(hdErr.HDERR_CANNOT_OPEN_FILE);
            }

            Stream s;
            int    retval = FileStream.OpenFileRead(filename, out s);

            if (retval != 0)
            {
                fileSystemError?.Invoke("File: " + filename + " Error: File Could not be opened.");
                fileErrorAbort = true;
                return(hdErr.HDERR_CANNOT_OPEN_FILE);
            }
            if (s == null)
            {
                fileSystemError?.Invoke("File: " + filename + " Error: File Could not be opened.");
                fileErrorAbort = true;
                return(hdErr.HDERR_CANNOT_OPEN_FILE);
            }
            if (s.Length < MaxHeader)
            {
                s.Close();
                s.Dispose();
                return(hdErr.HDERR_INVALID_FILE);
            }
            hard_disk_info hdi = new hard_disk_info();
            hdErr          res = ReadCHDHeader(s, ref hdi);

            if (res != hdErr.HDERR_NONE)
            {
                return(res);
            }
            chdVersion = hdi.version;
            chdMD5     = hdi.md5;
            chdSHA1    = hdi.sha1;


            if (!deepCheck)
            {
                s.Close();
                s.Dispose();
                return(res);
            }

            string error = null;

            if (hdi.version < 4 && hdi.compression < 3)
            {
                hdi.file = s;
                CHDLocalCheck clc = new CHDLocalCheck();
                res = clc.ChdCheck(fileProgress, hdi, out error);

                s.Close();
                s.Dispose();
            }
            else
            {
                s.Close();
                s.Dispose();

                CHDManCheck cmc = new CHDManCheck();
                res = cmc.ChdCheck(fileProgress, isLinux, filename, out error);
            }

            switch (res)
            {
            case hdErr.HDERR_NONE:
                break;

            case hdErr.HDERR_CHDMAN_NOT_FOUND:
                deepCheck = false;
                res       = hdErr.HDERR_NONE;
                break;

            case hdErr.HDERR_DECOMPRESSION_ERROR:
                fileError?.Invoke(filename, error);
                break;

            case hdErr.HDERR_FILE_NOT_FOUND:
                fileSystemError?.Invoke("File: " + filename + " Error: Not Found scan Aborted.");
                fileErrorAbort = true;
                break;

            default:
                generalError?.Invoke(res + " " + error);
                break;
            }

            return(res);
        }
Esempio n. 18
0
        private static ReturnCode OpenInputStream(RvFile fileIn, bool rawCopy, out ICompress zipFileIn, out bool sourceTrrntzip, out Stream readStream, out ulong streamSize, out ushort compressionMethod, out string error)
        {
            zipFileIn         = null;
            sourceTrrntzip    = false;
            readStream        = null;
            streamSize        = 0;
            compressionMethod = 0;

            if (fileIn.FileType == FileType.ZipFile || fileIn.FileType == FileType.SevenZipFile) // Input is a ZipFile
            {
                RvFile zZipFileIn = fileIn.Parent;
                if (zZipFileIn.FileType != DBTypeGet.DirFromFile(fileIn.FileType))
                {
                    error = "File Open but Source File is not correct type, Logic Error.";
                    return(ReturnCode.LogicError);
                }

                string    fileNameIn = zZipFileIn.FullNameCase;
                ZipReturn zr1;


                if (zZipFileIn.FileType == FileType.SevenZip)
                {
                    sourceTrrntzip = false;
                    zipFileIn      = new SevenZ();
                    zr1            = zipFileIn.ZipFileOpen(fileNameIn, zZipFileIn.FileModTimeStamp);
                }
                else
                {
                    sourceTrrntzip = (zZipFileIn.ZipStatus & ZipStatus.TrrntZip) == ZipStatus.TrrntZip;
                    zipFileIn      = new Zip();
                    zr1            = zipFileIn.ZipFileOpen(fileNameIn, zZipFileIn.FileModTimeStamp, fileIn.ZipFileHeaderPosition == null);
                }

                switch (zr1)
                {
                case ZipReturn.ZipGood:
                    break;

                case ZipReturn.ZipErrorFileNotFound:
                    error = "File not found, Rescan required before fixing " + fileIn.Name;
                    return(ReturnCode.RescanNeeded);

                case ZipReturn.ZipErrorTimeStamp:
                    error = "File has changed, Rescan required before fixing " + fileIn.Name;
                    return(ReturnCode.RescanNeeded);

                default:
                    error = "Error Open Zip" + zr1 + ", with File " + fileIn.DatTreeFullName;
                    return(ReturnCode.FileSystemError);
                }

                if (fileIn.FileType == FileType.SevenZipFile)
                {
                    ((SevenZ)zipFileIn).ZipFileOpenReadStream(fileIn.ZipFileIndex, out readStream, out streamSize);
                }
                else
                {
                    if (fileIn.ZipFileHeaderPosition != null)
                    {
                        ((Zip)zipFileIn).ZipFileOpenReadStreamQuick((ulong)fileIn.ZipFileHeaderPosition, rawCopy, out readStream, out streamSize, out compressionMethod);
                    }
                    else
                    {
                        ((Zip)zipFileIn).ZipFileOpenReadStream(fileIn.ZipFileIndex, rawCopy, out readStream, out streamSize, out compressionMethod);
                    }
                }
            }
            else // Input is a regular file
            {
                string fileNameIn = fileIn.FullName;
                if (!File.Exists(fileNameIn))
                {
                    error = "Rescan needed, File Not Found :" + fileNameIn;
                    return(ReturnCode.RescanNeeded);
                }
                FileInfo fileInInfo = new FileInfo(fileNameIn);
                if (fileInInfo.LastWriteTime != fileIn.FileModTimeStamp)
                {
                    error = "Rescan needed, File Changed :" + fileNameIn;
                    return(ReturnCode.RescanNeeded);
                }
                int errorCode = FileStream.OpenFileRead(fileNameIn, out readStream);
                if (errorCode != 0)
                {
                    error = new Win32Exception(errorCode).Message + ". " + fileNameIn;
                    return(ReturnCode.FileSystemError);
                }
                if (fileIn.Size == null)
                {
                    error = "Null File Size found in Fixing File :" + fileNameIn;
                    return(ReturnCode.LogicError);
                }
                streamSize = (ulong)fileIn.Size;
                if ((ulong)readStream.Length != streamSize)
                {
                    error = "Rescan needed, File Length Changed :" + fileNameIn;
                    return(ReturnCode.RescanNeeded);
                }
            }

            error = "";
            return(ReturnCode.Good);
        }
Esempio n. 19
0
        public static ReturnCode MoveFile(RvFile fileIn, RvFile fileOut, string outFilename, out bool fileMoved, out string error)
        {
            error     = "";
            fileMoved = false;

            bool fileMove = TestFileMove(fileIn, fileOut);

            if (!fileMove)
            {
                return(ReturnCode.Good);
            }

            byte[] bCRC;
            byte[] bMD5  = null;
            byte[] bSHA1 = null;

            string fileNameIn = fileIn.FullName;

            if (!File.Exists(fileNameIn))
            {
                error = "Rescan needed, File Not Found :" + fileNameIn;
                return(ReturnCode.RescanNeeded);
            }
            FileInfo fileInInfo = new FileInfo(fileNameIn);

            if (fileInInfo.LastWriteTime != fileIn.FileModTimeStamp)
            {
                error = "Rescan needed, File Changed :" + fileNameIn;
                return(ReturnCode.RescanNeeded);
            }

            string fileNameOut = outFilename ?? fileOut.FullName;

            File.Move(fileNameIn, fileNameOut);

            bCRC = fileIn.CRC.Copy();
            if (fileIn.FileStatusIs(FileStatus.MD5Verified))
            {
                bMD5 = fileIn.MD5.Copy();
            }

            if (fileIn.FileStatusIs(FileStatus.SHA1Verified))
            {
                bSHA1 = fileIn.SHA1.Copy();
            }

            FileInfo fi = new FileInfo(fileNameOut);

            fileOut.FileModTimeStamp = fi.LastWriteTime;

            ReturnCode retC = ValidateFileOut(fileIn, fileOut, true, bCRC, bSHA1, bMD5, out error);

            if (retC != ReturnCode.Good)
            {
                return(retC);
            }

            CheckDeleteFile(fileIn);

            fileMoved = true;
            return(ReturnCode.Good);
        }
Esempio n. 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);
            }
        }
Esempio n. 21
0
        private static ReturnCode OpenOutputStream(RvFile fileOut, RvFile fileIn, ref ICompress zipFileOut, string zipFilenameOut, ushort compressionMethod, bool rawCopy, bool sourceTrrntzip, out Stream writeStream, out string error)
        {
            writeStream = null;

            if ((fileOut.FileType == FileType.ZipFile) || (fileOut.FileType == FileType.SevenZipFile))
            {
                // if ZipFileOut == null then we have not open the output zip yet so open it from writing.
                if (zipFileOut == null)
                {
                    if (Path.GetFileName(zipFilenameOut) == "__RomVault.tmp")
                    {
                        if (File.Exists(zipFilenameOut))
                        {
                            File.Delete(zipFilenameOut);
                        }
                    }
                    else if (File.Exists(zipFilenameOut))
                    {
                        error = "Rescan needed, File Changed :" + zipFilenameOut;
                        return(ReturnCode.RescanNeeded);
                    }

                    if (fileOut.FileType == FileType.ZipFile)
                    {
                        zipFileOut = new ZipFile();
                    }
                    else
                    {
                        zipFileOut = new SevenZ();
                    }

                    ZipReturn zrf = zipFileOut.ZipFileCreate(zipFilenameOut);
                    if (zrf != ZipReturn.ZipGood)
                    {
                        error = "Error Opening Write Stream " + zrf;
                        return(ReturnCode.FileSystemError);
                    }
                }
                else
                {
                    if (zipFileOut.ZipOpen != ZipOpenType.OpenWrite)
                    {
                        error = "Output Zip File is not set to OpenWrite, Logic Error.";
                        return(ReturnCode.LogicError);
                    }

                    if (zipFileOut.ZipFilename != new FileInfo(zipFilenameOut).FullName)
                    {
                        error = "Output Zip file has changed name from " + zipFileOut.ZipFilename + " to " + zipFilenameOut + ". Logic Error";
                        return(ReturnCode.LogicError);
                    }
                }

                if (fileIn.Size == null)
                {
                    error = "Null File Size found in Fixing File :" + fileIn.FullName;
                    return(ReturnCode.LogicError);
                }
                ZipReturn zr = zipFileOut.ZipFileOpenWriteStream(rawCopy, sourceTrrntzip, fileOut.Name, (ulong)fileIn.Size, compressionMethod, out writeStream);
                if (zr != ZipReturn.ZipGood)
                {
                    error = "Error Opening Write Stream " + zr;
                    return(ReturnCode.FileSystemError);
                }
            }
            else
            {
                if (File.Exists(zipFilenameOut) && (fileOut.GotStatus != GotStatus.Corrupt))
                {
                    error = "Rescan needed, File Changed :" + zipFilenameOut;
                    return(ReturnCode.RescanNeeded);
                }
                int errorCode = FileStream.OpenFileWrite(zipFilenameOut, out writeStream);
                if (errorCode != 0)
                {
                    error = new Win32Exception(errorCode).Message + ". " + zipFilenameOut;
                    return(ReturnCode.FileSystemError);
                }
            }


            error = "";
            return(ReturnCode.Good);
        }