public static void WriteTo(IArchiveEntry archiveEntry, Stream streamToWriteTo)
 {
     if ((archiveEntry.Archive.Type == ArchiveType.Rar) && archiveEntry.Archive.IsSolid)
     {
         throw new InvalidFormatException("Cannot use Archive random access on SOLID Rar files.");
     }
     if (archiveEntry.IsDirectory)
     {
         throw new ExtractionException("Entry is a file directory and cannot be extracted.");
     }
     IArchiveExtractionListener archive = archiveEntry.Archive as IArchiveExtractionListener;
     archive.EnsureEntriesLoaded();
     archive.FireEntryExtractionBegin(archiveEntry);
     archive.FireFilePartExtractionBegin(archiveEntry.Key, archiveEntry.Size, archiveEntry.CompressedSize);
     Stream stream = archiveEntry.OpenEntryStream();
     if (stream != null)
     {
         using (stream)
         {
             using (Stream stream2 = new ListeningStream(archive, stream))
             {
                 Utility.TransferTo(stream2, streamToWriteTo);
             }
         }
         archive.FireEntryExtractionEnd(archiveEntry);
     }
 }
Пример #2
0
 internal ExtractFileEventArgs(FileInfo aArchive, IArchiveEntry aItem, ExtractionStage aStage)
 {
   ContinueOperation = true;
   Archive = aArchive;
   Item = aItem;
   Stage = aStage;
 }
        public static void WriteTo(/*this*/ IArchiveEntry archiveEntry, Stream streamToWriteTo)
        {
            if (archiveEntry.Archive.Type == ArchiveType.Rar && archiveEntry.Archive.IsSolid)
            {
                throw new InvalidFormatException("Cannot use Archive random access on SOLID Rar files.");
            }

            if (archiveEntry.IsDirectory)
            {
                throw new ExtractionException("Entry is a file directory and cannot be extracted.");
            }

            var streamListener = archiveEntry.Archive as IArchiveExtractionListener;
            streamListener.EnsureEntriesLoaded();
            streamListener.FireEntryExtractionBegin(archiveEntry);
            streamListener.FireFilePartExtractionBegin(archiveEntry.Key, archiveEntry.Size, archiveEntry.CompressedSize);
            var entryStream = archiveEntry.OpenEntryStream();
            if (entryStream == null)
            {
                return;
            }
            using(entryStream)
            using (Stream s = new ListeningStream(streamListener, entryStream))
            {
                //s.TransferTo(streamToWriteTo);
                Utility.TransferTo(s,streamToWriteTo);
            }
            streamListener.FireEntryExtractionEnd(archiveEntry);
        }
Пример #4
0
        internal ArchiveEntry(IArchiveEntry archiveEntry, string archivePath, ArchiveFormat archiveFormat)
        {
            Index = (uint) archiveEntry.Index;
            Path = archiveEntry.FilePath;
            Size = (ulong)archiveEntry.Size;
			Name = System.IO.Path.GetFileName(archiveEntry.FilePath);
            CompressedSize = 0; // Not supported in SevenZipSharp (yet)
            ModifiedDate = archiveEntry.LastModifiedTime.GetValueOrDefault ();            
            IsEncrypted = archiveEntry.IsEncrypted;
            IsFolder = archiveEntry.IsDirectory;
            ArchivePath = archivePath;
            Format = archiveFormat;
            CRC = archiveEntry.Crc;
			UnderlyingObject = archiveEntry;
        }
Пример #5
0
        private FileSystemItem CreateModel(IArchiveEntry entry)
        {
            DateTime date = _archive is SevenZipArchive
                                ? DateTime.MinValue
                                : (entry.LastModifiedTime ??
                                   entry.LastAccessedTime ??
                                   entry.CreatedTime ??
                                   entry.ArchivedTime ??
                                   DateTime.MinValue);

            return CreateModel(entry.FilePath, 
                               entry.IsDirectory,
                               date,
                               entry.IsDirectory ? (long?) null : entry.Size);
        }
Пример #6
0
 private OverwriteAction OverwritePrompt(Task task, FileInfo Dest, IArchiveEntry Entry)
 {
     overwritePromptMutex.WaitOne();
     try {
         if (task.Action != OverwriteAction.Unspecified)
         {
             return(task.Action);
         }
         if (actionRemembered != OverwriteAction.Unspecified)
         {
             return(actionRemembered);
         }
         using (var oi = new OverwritePromptInfo(task, Dest, Entry)) {
             Invoke(new OverwriteExecuteDelegate(OverwriteExecute), oi);
             return(oi.Action);
         }
     }
     finally {
         overwritePromptMutex.ReleaseMutex();
     }
 }
Пример #7
0
            public ArchiveItem(IArchiveEntry item, string rootFolder, ZipUpdater source)
            {
                Source      = source;
                _sourceItem = item ?? throw new ArgumentNullException(nameof(item));

                ItemSize     = item.Size;
                ModifiedTime = _sourceItem.LastModifiedTime ?? _sourceItem.CreatedTime ?? _sourceItem.ArchivedTime ?? _sourceItem.LastAccessedTime ?? DateTime.MinValue;
                Name         = Path.GetFileName(item.Key);
                IsDirectory  = item.IsDirectory;
                IsFile       = !item.IsDirectory;

                if (rootFolder != null)
                {
                    _rootFolder = rootFolder;
                    if (!item.Key.StartsWith(_rootFolder))
                    {
                        throw new IOException($"Remote item full path {_sourceItem.Key} doesn't start with the specified root path {_rootFolder}");
                    }
                    ClientRelativeFileName = item.Key.Substring(_rootFolder.Length);
                }
            }
        /// <summary>
        /// Extract to specific file
        /// </summary>
        public static void WriteToFile(this IArchiveEntry entry, string destinationFileName,
                                       ExtractionOptions options = null)
        {
            FileMode fm = FileMode.Create;

            options = options ?? new ExtractionOptions()
            {
                Overwrite = true
            };


            if (!options.Overwrite)
            {
                fm = FileMode.CreateNew;
            }
            using (FileStream fs = File.Open(destinationFileName, fm))
            {
                entry.WriteTo(fs);
            }

            entry.PreserveExtractionOptions(destinationFileName, options);
        }
        /// <summary>
        /// Extract to specific directory, retaining filename
        /// </summary>
        public static void WriteToDirectory(this IArchiveEntry entry, string destinationDirectory,
                                            ExtractOptions options = ExtractOptions.Overwrite)
        {
            string destinationFileName;
            string file = Path.GetFileName(entry.Key);

            if (options.HasFlag(ExtractOptions.ExtractFullPath))
            {
                string folder  = Path.GetDirectoryName(entry.Key);
                string destdir = Path.Combine(destinationDirectory, folder);
                if (!Directory.Exists(destdir))
                {
                    Directory.CreateDirectory(destdir);
                }
                destinationFileName = Path.Combine(destdir, file);
            }
            else
            {
                destinationFileName = Path.Combine(destinationDirectory, file);
            }
            entry.WriteToFile(destinationFileName, options);
        }
Пример #10
0
        private void UnpackArchiveEntry(IArchiveEntry archiveEntry, string zipArchiveName)
        {
            var outputPath = Path.Combine(importFolderConfiguration.InitialFolder, archiveEntry.Name);

            Console.WriteLine(outputPath);
            try
            {
                using (var outputStream = fileSystem.OpenWrite(outputPath))
                {
                    var archiveStream = archiveEntry.GetStream();

                    StreamUtil.CopyAndClose(archiveStream, outputStream);
                }

                CreateDoneFileForUnpackedFile(Path.ChangeExtension(outputPath, doneFileExtension));
            }
            catch (Exception exception)
            {
                Console.WriteLine(string.Format("Error during archive entry unpack. Archive {0}, entry{1}", zipArchiveName,
                                                archiveEntry.Name), exception);
            }
        }
Пример #11
0
        private bool HandleGameFileIWad(IGameFile gameFile, ISourcePort sourcePort, StringBuilder sb, LauncherPath gameFileDirectory, LauncherPath tempDirectory)
        {
            try
            {
                using (IArchiveReader reader = ArchiveReader.Create(Path.Combine(gameFileDirectory.GetFullPath(), gameFile.FileName)))
                {
                    IArchiveEntry entry       = reader.Entries.First();
                    string        extractFile = Path.Combine(tempDirectory.GetFullPath(), entry.Name);
                    if (ExtractFiles && entry.ExtractRequired)
                    {
                        entry.ExtractToFile(extractFile, true);
                    }

                    if (!entry.ExtractRequired)
                    {
                        extractFile = entry.FullName;
                    }

                    sb.Append(sourcePort.IwadParameter(new SpData(extractFile, gameFile, AdditionalFiles)));
                }
            }
            catch (FileNotFoundException)
            {
                LastError = string.Format("File not found: {0}", gameFile.FileName);
                return(false);
            }
            catch (IOException)
            {
                LastError = string.Format("File in use: {0}", gameFile.FileName);
                return(false);
            }
            catch (Exception)
            {
                LastError = string.Format("There was an issue with the IWad: {0}. Corrupted file?", gameFile.FileName);
                return(false);
            }

            return(true);
        }
        private void ProcessByLevel(IArchiveEntry entry)
        {
            var pf = GetPathFragments(entry.Key);

            // process folders. When entry is a directory, all fragments are folders.
            pf.Take(entry.IsDirectory ? pf.Length : pf.Length - 1)
            .ForEach(f =>
            {
                // skip if current dir is already added
                if (_fileEntries.ContainsKey(f))
                {
                    return;
                }

                ArchiveFileEntry parent;
                _fileEntries.TryGetValue(GetDirectoryName(f), out parent);

                var afe = new ArchiveFileEntry(Path.GetFileName(f), true, parent);

                _fileEntries.Add(f, afe);
            });

            // add the last path fragments, which is a file
            if (!entry.IsDirectory)
            {
                var file = pf.Last();

                ArchiveFileEntry parent;
                _fileEntries.TryGetValue(GetDirectoryName(file), out parent);

                _fileEntries.Add(file, new ArchiveFileEntry(Path.GetFileName(entry.Key), false, parent)
                {
                    Encrypted    = entry.IsEncrypted,
                    Size         = (ulong)entry.Size,
                    ModifiedDate = entry.LastModifiedTime ?? new DateTime()
                });
            }
        }
Пример #13
0
        private async Task <List <CompressFileUploadOutput> > ArchiveEntryRead(IArchiveEntry entry, ReaderOptions readerOptions,
                                                                               string compressFolder)
        {
            var lstFileInfo = new List <CompressFileUploadOutput>();
            var entryKey    = entry.Key;

            var fileExt      = Path.GetExtension(entryKey).ToLower();
            var tempFilePath = Path.Combine(_tempDir, $"{Guid.NewGuid().ToString("N").ToUpper()}{fileExt}");

            entry.WriteToFile(tempFilePath);

            var fileFolder = CombinePath(compressFolder, Path.GetDirectoryName(entryKey));

            if (IsPackage(fileExt))
            {
                //压缩包的文件名作为一层目录结构,并在后面加 ? 用于表示该一层目录为压缩包,主要为了区分文件夹名为test.rar情况
                var childerFolder = CombinePath(fileFolder, $"{Path.GetFileName(entryKey)}?");

                var childFileInfos = await ArchiveFileRead(tempFilePath, readerOptions, childerFolder);

                lstFileInfo.AddRange(childFileInfos);

                return(lstFileInfo);
            }

            var uploadFileInfo = new CompressFileUploadOutput
            {
                TempFilePath = tempFilePath,
                FileName     = Path.GetFileName(entryKey),
                FolderPath   = fileFolder?.Replace('\\', '/'), //层级机构统一使用 / ,不同的压缩格式,解压的路径Key分隔符不同
                FileMd5      = CalcMd5(tempFilePath)
            };

            lstFileInfo.Add(uploadFileInfo);

            return(lstFileInfo);
        }
Пример #14
0
        public static void ExtractEntry(this IArchive archive, IArchiveEntry entry, string filePath)
        {
            if (entry is null)
            {
                throw new ArgumentNullException(nameof(entry));
            }

            if (filePath is null)
            {
                throw new ArgumentNullException(nameof(filePath));
            }

            // Some implementations do not create the file path's directory automatically.

            string directoryPath    = Path.GetDirectoryName(filePath);
            bool   createdDirectory = false;

            if (!string.IsNullOrWhiteSpace(directoryPath) && !Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);

                createdDirectory = true;
            }

            try {
                using (FileStream fs = File.OpenWrite(filePath))
                    archive.ExtractEntry(entry, fs);
            }
            finally {
                // Delete the output directory if it is empty (we weren't able to extract the file).

                if (createdDirectory && !Directory.EnumerateFileSystemEntries(directoryPath).Any())
                {
                    Directory.Delete(directoryPath);
                }
            }
        }
Пример #15
0
        /***
         * 将当前的entry写到指定目录,保留文件信息,如果文件存在, 覆盖文件
         * 返回临时目录
         * */
        public static string writeEntryToTemp(IArchiveEntry entry)
        {
            //string tempDir = ConfigurationManager.AppSettings["tempDir"];
            bool successed = false;

            try
            {
                entry.WriteToDirectory(tempDir, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
                successed = true;
            }
            catch (Exception ex)
            {
                if (File.Exists(Path.Combine(tempDir, entry.Key)))
                {
                    string msg = "!!!!!!!!!!发生异常, 但是文件解压成功:" + ex.Message + ex.StackTrace;
                    MessageUtil.DoAppendTBDetail(msg);
                    LogHelper.WriteExportErrorLog(msg);
                    successed = true;
                }
                else
                {
                    string msg = "!!!!!!!!!!发生异常, 解压失败:" + ex.Message + ex.StackTrace;
                    MessageUtil.DoAppendTBDetail(msg);
                    LogHelper.WriteExportErrorLog(msg);
                    successed = false;
                }
            }
            if (successed)
            {
                return(Path.Combine(tempDir, entry.Key));
            }
            else
            {
                return("");
            }
        }
Пример #16
0
 public static void viewFile(FileInfo path)
 {
     if (IO.ArchiveHelpers.isArchiveExtension(path.Extension))
     {
         try {
             using (IArchive archive = ArchiveFactory.Open(path)) {
                 string        helpString = "This is an archive and there's multiple files in it. Please choose which one you want to view the info for.";
                 IArchiveEntry choice     = chooseChoices(archive.Entries, "Key", helpString, "Choose File in Archive");
                 if (choice != null)
                 {
                     using (ROMFile f = new CompressedROMFile(choice, path)) {
                         viewFile(f);
                     }
                 }
             }
         } catch (Exception ex) {
             MessageBox.Show(ex.ToString(), "Uh oh spaghetti-o", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }
     else if (IO.ArchiveHelpers.isGCZ(path.Extension))
     {
         using (GCZROMFile gcz = new GCZROMFile(path)) {
             viewFile(gcz);
         }
     }
     else if (CueSheet.isCueExtension(path.Extension))
     {
         viewCueFile(path);
     }
     else
     {
         using (ROMFile f = new NormalROMFile(path)) {
             viewFile(f);
         }
     }
 }
Пример #17
0
        // 将压缩流还原成图片的base64数据
        public static string Read(IArchiveEntry entry)
        {
            try
            {
                if (entry.IsEncrypted)
                {
                    return(null);
                }

                using var stream = entry.OpenEntryStream();
                using var ms     = new MemoryStream();
                stream.CopyTo(ms);
                // bytes = ms.ToArray();

                return("data:image/*;base64," + Convert.ToBase64String(ms.ToArray()));
            }
            catch (Exception e)
            {
                Console.WriteLine("创建图片出现异常:");
                Console.WriteLine(e);
            }

            return(null);
        }
Пример #18
0
        //Takes a file 'MAP01.wad' and makes it 'MAP01_GUID.wad'.
        //Checks if file with prefix MAP01 exists with same file length and returns that file (same file).
        //Otherwise a new file is extracted and returned.
        public static string ExtractTempFile(string tempDirectory, IArchiveEntry entry)
        {
            // The file is a regular file and not an archive - return the FulName
            if (!entry.ExtractRequired)
            {
                return(entry.FullName);
            }

            string ext  = Path.GetExtension(entry.Name);
            string file = entry.Name.Replace(ext, string.Empty) + "_";

            string[] searchFiles = Directory.GetFiles(tempDirectory, file + "*");

            string matchingFile = searchFiles.FirstOrDefault(x => new FileInfo(x).Length == entry.Length);

            if (matchingFile == null)
            {
                string extractFile = Path.Combine(tempDirectory, string.Concat(file, Guid.NewGuid().ToString(), ext));
                entry.ExtractToFile(extractFile);
                return(extractFile);
            }

            return(matchingFile);
        }
Пример #19
0
        internal ProjectResourceImporter(ProjectExplorer projectExplorer, ProjectDirectory directory, IArchiveEntry archiveEntry, string projectKey)
        {
            ProjectExplorer = projectExplorer;
            Directory       = directory;
            ArchiveEntry    = archiveEntry;
            ProjectKey      = projectKey;

            ImporterTags = new HashSet <string>();
            Dependencies = new ProjectResourceImporterDependencyCollection(this);
        }
Пример #20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SevenZipArchiveEntryViewModel"/> class.
 /// </summary>
 /// <param name="archive">The archive<see cref="SevenZipArchiveViewModel"/>.</param>
 /// <param name="entry">The entry<see cref="IArchiveEntry"/>.</param>
 /// <param name="parent">The parent<see cref="SevenZipArchiveEntryViewModel"/>.</param>
 public SevenZipArchiveEntryViewModel(SevenZipArchiveViewModel archive, IArchiveEntry entry, SevenZipArchiveEntryViewModel parent = null)
 {
     this.archiveRoot = archive;
     Entry            = entry;
     Parent           = parent;
 }
Пример #21
0
 /// <summary>
 /// Writes an entry into the file.
 /// </summary>
 /// <param name="entry"></param>
 public void WriteNextEntry(IArchiveEntry entry)
 {
     base.PutNextEntry((ICSharpCode.SharpZipLib.Zip.ZipEntry)((ZipEntry)entry).BaseEntry);
 }
Пример #22
0
 public static void WriteTo(this IArchiveEntry entry, Stream stream)
 {
     entry.WriteTo(stream, new NullExtractionListener());
 }
Пример #23
0
 /// <summary>
 /// Extract to specific directory, retaining filename
 /// </summary>
 public static void WriteToDirectory(this IArchiveEntry entry, string destinationPath,
                                     ExtractOptions options = ExtractOptions.Overwrite)
 {
     entry.WriteToDirectory(destinationPath, new NullExtractionListener(), options);
 }
 public ArchiveEntryViewModel(IArchiveEntry archiveEntry)
 {
     ArchiveEntry = archiveEntry;
 }
        /// <summary>
        /// Begins the file extraction.
        /// </summary>
        /// <param name="file">The file within the archive.</param>
        /// <param name="archive">The archive.</param>
        private void ExtractFile(IArchiveEntry file, IArchive archive)
        {
            _td = new TaskDialog
                {
                    Title           = "Extracting...",
                    Instruction     = Path.GetFileName(file.FilePath),
                    Content         = "Extracting file...",
                    CommonButtons   = TaskDialogButton.Cancel,
                    ShowProgressBar = true
                };

            _td.Destroyed   += TaskDialogDestroyed;
            _td.ButtonClick += TaskDialogDestroyed;

            new Thread(() => _td.Show()).Start();

            _ext = Path.Combine(Path.GetDirectoryName(_file), Path.GetFileName(file.FilePath));

            var total = file.Size;
            var last = DateTime.MinValue;

            archive.CompressedBytesRead += (sender, args) =>
                {
                    if (args.CurrentFilePartCompressedBytesRead == total)
                    {
                        return;
                    }

                    if ((DateTime.Now - last).TotalMilliseconds < 150)
                    {
                        return;
                    }

                    last = DateTime.Now;

                    var perc = ((double)args.CurrentFilePartCompressedBytesRead / (double)total) * 100;
                    _td.ProgressBarPosition = (int)perc;
                    _td.Content = "Extracting file: " + Utils.GetFileSize(args.CurrentFilePartCompressedBytesRead) + " / " + perc.ToString("0.00") + "% done...";
                };
            archive.EntryExtractionEnd += (sender, args) =>
                {
                    _td.SimulateButtonClick(-1);

                    if (!File.Exists(_ext))
                    {
                        return;
                    }

                    new Thread(() =>
                        {
                            Thread.Sleep(250);
                            Utils.Run(_ext);

                            Thread.Sleep(10000);
                            AskAfterUse();
                        }).Start();
                };

            _thd = new Thread(() => file.WriteToFile(_ext));
            _thd.Start();
        }
Пример #26
0
 static string GetString(IArchiveEntry entry)
 {
     byte[] bytes = new byte[entry.Size];
     entry.OpenEntryStream().Read(bytes, 0, bytes.Length);
     return System.Text.Encoding.Default.GetString(bytes);
 }
Пример #27
0
 // Methods specific to ArchiveOutputStream
 /**
  * Writes the headers for an archive entry to the output stream.
  * The caller must then write the content to the stream and call
  * {@link #closeArchiveEntry()} to complete the process.
  *
  * @param entry describes the entry
  * @throws IOException
  */
 public virtual void PutArchiveEntry(IArchiveEntry entry)
 {
 }
Пример #28
0
 private void MenuItem_Click_2(object sender, RoutedEventArgs e)
 {
     archive = null;
     currentEntry = null;
     ImageViewer1.Source = null;
     ImageViewer1.Height = 0;
     ImageViewer1.Width = 0;
     currentIndex = 0;
     currentWidth = 0;
 }
Пример #29
0
        private void loadPage(Direction direction)
        {
            if (direction == Direction.Forward)
            {
                currentEntry = getNextEntry();
            }
            else
            {
                currentEntry = getPreviousEntry();
            }

            Bitmap bitmap = loadAndResizeBitmap(currentEntry);
            displayImage(bitmap);
            currentWidth = bitmap.Width;
        }
Пример #30
0
        private Bitmap loadAndResizeBitmap(IArchiveEntry fileEntry)
        {
            Bitmap bitmap = (Bitmap)Bitmap.FromStream(fileEntry.OpenEntryStream());

            if (bitmap.Height > System.Windows.SystemParameters.PrimaryScreenHeight)
            {
                System.Drawing.Size oldSize = new System.Drawing.Size(bitmap.Width, bitmap.Height);
                System.Drawing.Size newSize = getNewImageSize(oldSize);
                Bitmap newImage = ResizeImage(bitmap, newSize);
                bitmap = newImage;
            }
            return bitmap;
        }
Пример #31
0
 /**
  * Whether this stream is able to read the given entry.
  *
  * <p>
  * Some archive formats support variants or details that are not supported (yet).
  * </p>
  *
  * @param archiveEntry
  *            the entry to test
  * @return This implementation always returns true.
  *
  * @since 1.1
  */
 public bool CanReadEntryData(IArchiveEntry archiveEntry)
 {
     return true;
 }
 public ArchiveFileInfo(IArchiveEntry archiveEntry) {
     _archiveEntry = archiveEntry;
 }
Пример #33
0
 private bool SetupExtractDest(Task task, IArchiveEntry info, FileInfo dest)
 {
     bool rv = false;
       if (dest.Exists) {
     switch ((OverwriteAction)Config.OverwriteAction) {
       case OverwriteAction.Overwrite:
     info.Destination = dest;
     rv = true;
     break;
       default:
     switch (OverwritePrompt(task, dest, info)) {
       case OverwriteAction.Overwrite:
         info.Destination = dest;
         rv = true;
         break;
       case OverwriteAction.RenameDirectory:
       case OverwriteAction.Rename:
         info.Destination = MakeUnique(dest);
         rv = true;
         break;
       default:
         break;
     }
     break;
       case OverwriteAction.Rename:
     info.Destination = MakeUnique(dest);
     rv = true;
     break;
     }
       }
       else {
     rv = true;
     info.Destination = dest;
       }
       return rv;
 }
        /// <summary>
        /// 解压数据操作
        /// </summary>
        /// <param name="e">参数</param>
        private void DecompressDataWork(DecompressDataStartArgs e)
        {
            Exception error     = null;
            bool      cancelled = false;

            try
            {
                using (MemoryStream stream = new MemoryStream(e.Data))
                {
                    ReaderOptions readerOptions = new ReaderOptions();
                    readerOptions.ArchiveEncoding.Default = Encoding.Default;
                    using (IArchive archive = ArchiveFactory.Open(stream, readerOptions))
                    {
                        this.m_Progress.ToComplete = archive.TotalUncompressSize;
                        string            deleteEntry          = e.DeleteEntry;
                        string            lastEntry            = e.LastEntry;
                        string            destinationDirectory = e.DestinationDirectory;
                        ExtractionOptions extractionOptions    = new ExtractionOptions {
                            ExtractFullPath = true, Overwrite = true, PreserveFileTime = true
                        };
                        IArchiveEntry last = null;
                        foreach (IArchiveEntry entry in archive.Entries)
                        {
                            if (this.m_Cancelled)
                            {
                                cancelled = true;
                                return;
                            }
                            if (entry.IsDirectory)
                            {
                                continue;
                            }
                            if (last == null && entry.Key.Equals(lastEntry, StringComparison.OrdinalIgnoreCase))
                            {
                                last = entry;
                                continue;
                            }
                            if (entry.Key.Equals(deleteEntry, StringComparison.OrdinalIgnoreCase))
                            {
                                DeleteFromDirectory(entry, destinationDirectory, extractionOptions);
                            }
                            else
                            {
                                entry.WriteToDirectory(destinationDirectory, extractionOptions);
                            }
                            this.m_Progress.Completed += entry.Size;
                            this.PostDecompressProgressChanged(this.m_Progress, this.m_AsyncOp);
                        }
                        if (last != null)
                        {
                            if (this.m_Cancelled)
                            {
                                cancelled = true;
                                return;
                            }
                            if (last.Key.Equals(deleteEntry, StringComparison.OrdinalIgnoreCase))
                            {
                                DeleteFromDirectory(last, destinationDirectory, extractionOptions);
                            }
                            else
                            {
                                last.WriteToDirectory(destinationDirectory, extractionOptions);
                            }
                            this.m_Progress.Completed += last.Size;
                            this.PostDecompressProgressChanged(this.m_Progress, this.m_AsyncOp);
                        }
                    }
                }
            }
            catch (Exception exp)
            {
                error = exp;
            }
            finally
            {
                this.DecompressDataAsyncCallback(error, cancelled, this.m_AsyncOp);
            }
        }
Пример #35
0
		private async Task ReadCollectionFromZip(IArchiveEntry entry, ZipDirectory currentDirectory, string currentPath, Dictionary<string, IArchiveEntry> resourceEntries, Indiagram parent)
		{
			using (Stream entryStream = entry.OpenEntryStream())
			{
				XDocument xmlDocument = XDocument.Load(entryStream);

				XElement rootElement = xmlDocument.Element("indiagram");
				if (rootElement != null)
				{
					// the current element is an indiagram, just read it
					await CreateIndiagramFromXml(rootElement, false, parent, async (key, type) =>
					{
						return await Task.Run(() =>
						{
							if (resourceEntries.ContainsKey(key))
							{
								return resourceEntries[key].OpenEntryStream();
							}
							throw new IndexOutOfRangeException(string.Format("Key {0} is not available in resources", key));
						});
					});
				}
				else
				{
					// the current element is a category, read it + process its children
					rootElement = xmlDocument.Element("category");
					if (rootElement == null)
					{
						return;
					}

					Indiagram category = await CreateIndiagramFromXml(rootElement, true, parent, async (key, type) =>
					{
						return await Task.Run(() =>
						{
							if (resourceEntries.ContainsKey(key))
							{
								return resourceEntries[key].OpenEntryStream();
							}
							throw new IndexOutOfRangeException(string.Format("Key {0} is not available in resources", key));
						});
					});

					XElement indiagramsElement = rootElement.Element("indiagrams");
					if (indiagramsElement == null)
					{
						return;
					}
					foreach (XElement child in indiagramsElement.Elements("indiagram"))
					{
						// look for the entry
						string directoryName = Path.GetDirectoryName(child.Value);
						string fileName = Path.GetFileName(child.Value);

						ZipDirectory directory = GetSubZipDirectory(currentDirectory, currentPath, directoryName);

						if (directory.Files.ContainsKey(fileName))
						{
							await ReadCollectionFromZip(directory.Files[fileName], directory, directoryName, resourceEntries, category);
						}
						else
						{
							throw new IndexOutOfRangeException("file names mismatch");
						}
					}
				}
			}
		}
Пример #36
0
 /// <summary>
 /// Extract to specific file
 /// </summary>
 public static void WriteToFile(this IArchiveEntry entry, string destinationFileName,
                                ExtractOptions options = ExtractOptions.Overwrite)
 {
     entry.WriteToFile(destinationFileName, new NullExtractionListener(), options);
 }
Пример #37
0
 private OverwriteAction OverwritePrompt(Task task, FileInfo Dest, IArchiveEntry Entry)
 {
     overwritePromptMutex.WaitOne();
       try {
     if (task.Action != OverwriteAction.Unspecified) {
       return task.Action;
     }
     if (actionRemembered != OverwriteAction.Unspecified) {
       return actionRemembered;
     }
     using (var oi = new OverwritePromptInfo(task, Dest, Entry)) {
       Invoke(new OverwriteExecuteDelegate(OverwriteExecute), oi);
       return oi.Action;
     }
       }
       finally {
     overwritePromptMutex.ReleaseMutex();
       }
 }
 private static ArchiveFile CreateFileFromEntry(ArchiveDirectory parent, string name, IArchiveEntry entry)
 {
     return(new ArchiveFile(
                parent,
                name,
                entry.Length,
                entry.CompressedLength));
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ZipEntryWrapper"/> class.
 /// </summary>
 /// <param name="entry">The entry to wrap.</param>
 /// <exception cref="ArgumentNullException">entry</exception>
 public ZipEntryWrapper(IArchiveEntry entry)
 {
     this.entry = entry ?? throw new ArgumentNullException(nameof(entry));
 }
        private Bitmap LoadImage(IArchiveEntry fileEntry)
        {
            Bitmap bitmap = (Bitmap)Bitmap.FromStream(fileEntry.OpenEntryStream());

            return(bitmap);
        }
Пример #41
0
 public OverwritePromptInfo(Task aTask, FileInfo aDest, IArchiveEntry aEntry)
 {
     task = aTask;
     dest = aDest;
     entry = aEntry;
 }
Пример #42
0
 void IArchiveExtractionListener.FireEntryExtractionEnd(IArchiveEntry entry)
 {
     EntryExtractionEnd?.Invoke(this, new ArchiveExtractionEventArgs <IArchiveEntry>(entry));
 }
Пример #43
0
 public abstract void ExtractEntry(IArchiveEntry entry, Stream outputStream);
Пример #44
0
 /**
  * Whether this stream is able to write the given entry.
  *
  * <p>Some archive formats support variants or details that are
  * not supported (yet).</p>
  *
  * @param archiveEntry
  *            the entry to test
  * @return This implementation always returns true.
  * @since 1.1
  */
 public bool canWriteEntryData(IArchiveEntry archiveEntry)
 {
     return true;
 }
Пример #45
0
 private Task <EntryUnpackResult> UnpackEntryAsync(IArchiveEntry entry, string directory)
 {
     return(this.UnpackEntryAsync(entry.OpenEntryStream, entry, directory));
 }
Пример #46
0
        public void PutArchiveEntry(IArchiveEntry pEntry )
        {
            if(finished) {
                throw new IOException("Stream has already been finished");
            }

            ArArchiveEntry pArEntry = (ArArchiveEntry)pEntry;
            if (prevEntry == null)
            {
                WriteArchiveHeader();
            } else
            {
                if (prevEntry.GetLength() != entryOffset)
                {
                    throw new IOException("length does not match entry (" + prevEntry.GetLength() + " != " + entryOffset);
                }

                if (haveUnclosedEntry)
                {
                    CloseArchiveEntry();
                }
            }

            prevEntry = pArEntry;

            WriteEntryHeader(pArEntry);

            entryOffset = 0;
            haveUnclosedEntry = true;
        }
Пример #47
0
        protected IArchiveEntry SelectSubtitle(string lang, string mediaPath, Stream stream, out string selectedFormat)
        {
            _logger?.Info($"SubhdProvider, SelectSubtitle lang: {lang}, mediaPath: {mediaPath}");

            selectedFormat = "";
            lang           = NormailizeLang(lang);

            IArchiveEntry        currentEntry  = null;
            int                  currentScore  = 0;
            List <IArchiveEntry> entriesToSave = new List <IArchiveEntry>();

            using var archive = ArchiveFactory.Open(stream);
            try
            {
                foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
                {
                    string key = entry.Key;

                    _logger?.Info($"SubhdProvider, \t process entry: {key}");

                    int score   = 0;
                    int matches = MatchesLang(lang, key);
                    var format  = ExtractFormat(key);

                    if (ASS.Equals(format) || SSA.Equals(format))
                    {
                        score += 0xF;
                    }
                    else if (SRT.Equals(format))
                    {
                        score += 0x8;
                    }
                    else
                    {
                        continue;
                    }

                    entriesToSave.Add(entry);

                    // lang:
                    //  exactly: 0xF0, matches: 0x80, don't known: 0x00
                    // format:
                    //  ass/ssa: 0xF, srt: 0x8
                    if (matches == 1)
                    {
                        score = 0xF0;
                    }
                    else if (matches == 2)
                    {
                        score = 0x80;
                    }
                    else if (matches == 0)
                    {
                        score = 0;
                    }
                    else
                    {
                        continue;
                    }

                    _logger?.Info($"SubhdProvider, \t score: {score}");

                    if (score > currentScore)
                    {
                        currentScore   = score;
                        currentEntry   = entry;
                        selectedFormat = format;
                    }
                }

                //TrySaveSubtitles(mediaPath, entriesToSave.Where(entry => entry != currentEntry));
            }
            catch (InvalidFormatException)
            {
                throw;
            }
            catch (IndexOutOfRangeException)
            {
                throw;
            }

            _logger?.Info($"SubhdProvider, SelectSubtitle selectedEntry: {currentEntry.Key}, format: {selectedFormat}");
            return(currentEntry);
        }
Пример #48
0
 public FileListOutlineItem(IArchiveEntry entry)
 {
     this.name  = entry.FilePath.Split('/').Last();
     this.entry = entry;
 }
        /// <summary>
        /// Begins the file extraction.
        /// </summary>
        /// <param name="file">The file within the archive.</param>
        /// <param name="archive">The archive.</param>
        private void ExtractFile(IArchiveEntry file, IArchive archive)
        {
            _ext = Path.Combine(Path.GetDirectoryName(_file), Path.GetFileName(file.FilePath));
            _active = true;
            _tdstr = "Extracting file...";
            var mthd = new Thread(() => TaskDialog.Show(new TaskDialogOptions
                {
                    Title                   = "Extracting...",
                    MainInstruction         = Path.GetFileName(file.FilePath),
                    Content                 = _tdstr,
                    CustomButtons           = new[] { "Cancel" },
                    ShowProgressBar         = true,
                    EnableCallbackTimer     = true,
                    AllowDialogCancellation = true,
                    Callback                = (dialog, args, data) =>
                        {
                            dialog.SetProgressBarPosition(_tdpos);
                            dialog.SetContent(_tdstr);

                            if (args.ButtonId != 0)
                            {
                                if (_active)
                                {
                                    try { _thd.Abort(); _thd = null; } catch { }

                                    if (!string.IsNullOrWhiteSpace(_ext) && File.Exists(_ext))
                                    {
                                        new Thread(() =>
                                            {
                                                Thread.Sleep(1000);
                                                try { File.Delete(_ext); } catch { }
                                            }).Start();
                                    }
                                }

                                return false;
                            }

                            if (!_active)
                            {
                                dialog.ClickButton(500);
                                return false;
                            }

                            return true;
                        }
                }));
            mthd.SetApartmentState(ApartmentState.STA);
            mthd.Start();

            var total = file.Size;
            var last = DateTime.MinValue;

            archive.CompressedBytesRead += (sender, args) =>
                {
                    if (args.CurrentFilePartCompressedBytesRead == total)
                    {
                        return;
                    }

                    if ((DateTime.Now - last).TotalMilliseconds < 150)
                    {
                        return;
                    }

                    last = DateTime.Now;

                    var perc = ((double)args.CurrentFilePartCompressedBytesRead / (double)total) * 100;
                    _tdpos = (int)perc;
                    _tdstr = "Extracting file: " + Utils.GetFileSize(args.CurrentFilePartCompressedBytesRead) + " / " + perc.ToString("0.00") + "% done...";
                };
            archive.EntryExtractionEnd += (sender, args) =>
                {
                    _active = false;

                    if (!File.Exists(_ext))
                    {
                        return;
                    }

                    new Thread(() =>
                        {
                            Thread.Sleep(250);
                            Utils.Run(_ext);

                            Thread.Sleep(10000);
                            AskAfterUse();
                        }).Start();
                };

            _thd = new Thread(() => file.WriteToFile(_ext));
            _thd.Start();
        }
 void IWritableArchive.RemoveEntry(IArchiveEntry entry)
 {
     RemoveEntry((TEntry)entry);
 }
Пример #51
0
 public abstract void DeleteEntry(IArchiveEntry entry);