public override async Task <IScriptCommand> ExecuteAsync(ParameterDic pm)
        {
            Dictionary <string, Stream> compressDic = new Dictionary <string, Stream>();

            try
            {
                IEntryModel[] srcEntries = await pm.GetValueAsEntryModelArrayAsync(SourceEntryKey);

                ISzsItemModel destEntry = await pm.GetValueAsEntryModelAsync(DestinationDirectoryEntryKey, null) as ISzsItemModel;

                //If destination is not SzsRoot, use DiskTransfer instead.
                SzsProfile destProfile = destEntry.Profile as SzsProfile;
                if (destProfile == null)
                {
                    logger.Warn(String.Format("{0} isn't Szs based entry, DiskTransfer is used instead.", destEntry.Name));
                    return(IOScriptCommands.DiskTransfer(SourceEntryKey, DestinationDirectoryEntryKey, null, RemoveOriginal, false, NextCommand));
                }
                if (!destEntry.IsDirectory)
                {
                    return(ResultCommand.Error(new ArgumentException(DestinationDirectoryEntryKey + " is not a folder.")));
                }

                Func <IEntryModel, bool> fileAndArchiveOnly = em => !em.IsDirectory || (em is SzsRootModel);
                Func <IEntryModel, bool> lookupDirectoryNotArchiveFilter = em => em.IsDirectory && !(em is SzsRootModel);

                IProgress <TransferProgress> progress = pm.GetProgress();

                string archiveType = destProfile.Path.GetExtension((destEntry as ISzsItemModel).Root.Name);
                logger.Info(String.Format("Compressing {0} -> {1} using SzsDiskTransfer",
                                          srcEntries.GetDescription(), destEntry.Name));

                await Task.Run(async() =>
                {
                    #region OpenStream of files
                    foreach (var srcEntry in srcEntries)
                    {
                        IDiskProfile srcProfile = srcEntry.Profile as IDiskProfile;
                        if (srcProfile == null)
                        {
                            break;
                        }


                        if (fileAndArchiveOnly(srcEntry))
                        {
                            logger.Debug(String.Format("Added to Dictionary : {0} -> {1}", srcEntry.FullPath, srcEntry.Name));
                            progress.Report(TransferProgress.SetMessage(ProgressType.Running, srcEntry.Name));
                            compressDic.Add(srcEntry.Name, await srcProfile.DiskIO
                                            .OpenStreamAsync(srcEntry, Defines.FileAccess.Read, pm.CancellationToken));
                        }
                        else
                        {
                            IList <IEntryModel> srcSubEntries = await srcProfile.ListRecursiveAsync(srcEntry, pm.CancellationToken,
                                                                                                    fileAndArchiveOnly, lookupDirectoryNotArchiveFilter, false);

                            foreach (var srcSubEntry in srcSubEntries)
                            {
                                string relativePath =
                                    destProfile.Path.Combine(
                                        destEntry.RelativePath,
                                        srcSubEntry.FullPath.Replace(srcEntry.Parent.FullPath, "").TrimStart('\\')
                                        );
                                logger.Debug(String.Format("Added to Dictionary : {0} -> {1}", srcSubEntry.FullPath, relativePath));
                                progress.Report(TransferProgress.SetMessage(ProgressType.Running, relativePath));
                                compressDic.Add(relativePath, await srcProfile.DiskIO
                                                .OpenStreamAsync(srcSubEntry, Defines.FileAccess.Read, pm.CancellationToken));
                            }
                        }
                    }
                    #endregion

                    Progress <Defines.ProgressEventArgs> progress1 = new Progress <Defines.ProgressEventArgs>(
                        (pea) =>
                    {
                        if (!String.IsNullOrEmpty(pea.Message))
                        {
                            progress.Report(TransferProgress.SetMessage(Defines.ProgressType.Running, pea.Message));
                        }
                        if (!String.IsNullOrEmpty(pea.File))
                        {
                            progress.Report(TransferProgress.From(pea.File));
                        }
                        if (pea.CurrentProgress != -1 && pea.TotalProgress != -1)
                        {
                            progress.Report(TransferProgress.UpdateCurrentProgress((short)((float)pea.CurrentProgress / (float)pea.TotalProgress * 100.0)));
                        }
                    }
                        );

                    progress.Report(TransferProgress.To(destEntry.Name));
                    using (await destProfile.WorkingLock.LockAsync())
                        using (var stream = await destProfile.DiskIO.OpenStreamAsync(destEntry, Defines.FileAccess.ReadWrite, pm.CancellationToken))
                            destProfile.Wrapper.CompressMultiple(archiveType, stream, compressDic, progress1);

                    logger.Info(String.Format("{0} items transfered", compressDic.Count()));
                    return(CoreScriptCommands.NotifyEntryChanged(ChangeType.Changed, destEntry, NextCommand));
                });


                return(NextCommand);
            }
            finally
            {
                #region Dispose Streams
                if (compressDic != null)
                {
                    foreach (var stream in compressDic.Values)
                    {
                        stream.Dispose();
                    }
                }
                #endregion
            }
        }
Example #2
0
 public HardDriveDiskIOHelper(IDiskProfile profile)
     : base(profile)
 {
 }
 public static IScriptCommand ParseOrCreatePath(IDiskProfile profile, string path,
                                                bool isFolder, Func <IEntryModel, IScriptCommand> thenFunc)
 {
     return(WPFScriptCommands.ParsePath(new[] { profile }, path, thenFunc,
                                        WPFScriptCommands.CreatePath(profile, path, isFolder, false, thenFunc)));
 }
 protected DiskIOHelperBase(IDiskProfile profile)
 {
     Mapper  = new IODiskPatheMapper();
     Profile = profile;
 }
        public override void NotifySelectionChanged(IEntryModel[] appliedModels)
        {
            List <ICommandModel> subCommands = new List <ICommandModel>();

            if (appliedModels.Length >= 1 &&
                !(appliedModels.Any(em => em.FullPath.StartsWith("::"))))
            {
                #region Decompress - When selected archive.
                if (appliedModels.All(em => em is ISzsItemModel))
                {
                    bool isRoot = appliedModels.All(em => em is SzsRootModel);
                    Func <IEntryModel, IScriptCommand, IScriptCommand> transferCommandFunc =
                        (destModel, thenCommand) =>
                        isRoot?
                        IOScriptCommands.DiskTransferChild(appliedModels, destModel, false, true, thenCommand) :
                            IOScriptCommands.DiskTransfer(appliedModels, destModel, false, true, thenCommand);


                    //Extract to ...
                    subCommands.Add(new CommandModel(
                                        WPFScriptCommands.ShowDirectoryPicker(_initializer, null,
                                                                              dm =>
                                                                              WPFScriptCommands.ShowProgress("Extract", transferCommandFunc(dm, WPFScriptCommands.HideProgress())),
                                                                              ResultCommand.NoError))
                    {
                        Header = "Extract to ...", IsEnabled = true, IsVisibleOnMenu = true
                    });

                    if (isRoot)
                    {
                        SzsRootModel firstRoot = appliedModels[0] as SzsRootModel;

                        IPathHelper path = firstRoot.Profile.Path;
                        Header = path.GetExtension(firstRoot.Name).TrimStart('.').FirstCharToUppercase();
                        string parentPath = path.GetDirectoryName(firstRoot.FullPath);

                        //Extract Here
                        subCommands.Add(new CommandModel(
                                            WPFScriptCommands.ShowProgress("Extract",
                                                                           transferCommandFunc(firstRoot.Parent, WPFScriptCommands.HideProgress())))
                        {
                            Header = "Extract Here", IsEnabled = true, IsVisibleOnMenu = true
                        });


                        if (appliedModels.Length == 1)
                        {
                            //Extract to \\ArchiveName
                            subCommands.Add(new CommandModel(
                                                WPFScriptCommands.ParseOrCreatePath(firstRoot.Parent.Profile as IDiskProfile,
                                                                                    path.Combine(parentPath, path.RemoveExtension(appliedModels[0].Name)), true,
                                                                                    destFolder => transferCommandFunc(destFolder, WPFScriptCommands.HideProgress())))
                            {
                                Header          = "Extract to \\" + path.RemoveExtension(appliedModels[0].Name),
                                IsEnabled       = true,
                                IsVisibleOnMenu = true
                            });
                        }
                        else
                        {
                            subCommands.Add(new CommandModel(
                                                WPFScriptCommands.ShowProgress("Extract",
                                                                               ScriptCommands.ForEach(appliedModels, am =>
                                                                                                      WPFScriptCommands.ParseOrCreatePath(firstRoot.Parent.Profile as IDiskProfile,
                                                                                                                                          path.Combine(parentPath, path.RemoveExtension(am.Name)), true,
                                                                                                                                          destFolder => transferCommandFunc(destFolder, WPFScriptCommands.HideProgress())))))
                            {
                                Header = "Extract to {ArchiveName}\\", IsEnabled = true, IsVisibleOnMenu = true
                            });
                        }
                    }
                }

                //if (appliedModels.All(em => em is SzsRootModel))
                //{
                //    SzsRootModel firstRoot = appliedModels[0] as SzsRootModel;

                //    IPathHelper path = firstRoot.Profile.Path;
                //    Header = path.GetExtension(firstRoot.Name).TrimStart('.').FirstCharToUppercase();
                //    string parentPath = path.GetDirectoryName(firstRoot.FullPath);


                //    //Extract to ...
                //    subCommands.Add(new CommandModel(
                //        ScriptCommands.ShowDirectoryPicker(_initializer, null,
                //        dm =>
                //         ScriptCommands.ShowProgress("Extract",
                //         ScriptCommands.ForEach(appliedModels, am =>
                //                     IOScriptCommands.TransferChild(am, dm, null, false),
                //              ScriptCommands.HideProgress())),
                //              ResultCommand.NoError)) { Header = "Extract to ...", IsEnabled = true, IsVisibleOnMenu = true });

                //    //Extract Here
                //    subCommands.Add(new CommandModel(
                //           ScriptCommands.ShowProgress("Extract",
                //           ScriptCommands.ForEach(appliedModels, am =>
                //                       IOScriptCommands.TransferChild(am, firstRoot.Parent, null, false),
                //                ScriptCommands.HideProgress()))) { Header = "Extract Here", IsEnabled = true, IsVisibleOnMenu = true });


                //    if (appliedModels.Length == 1)
                //    {
                //        //Extract to \\ArchiveName
                //        subCommands.Add(new CommandModel(
                //            ScriptCommands.ParseOrCreatePath(firstRoot.Parent.Profile as IDiskProfile,
                //            path.Combine(parentPath, path.RemoveExtension(appliedModels[0].Name)), true,
                //            destFolder =>
                //                ScriptCommands.ShowProgress("Extract",
                //                    IOScriptCommands.TransferChild(appliedModels[0], destFolder, null, false,
                //                      ScriptCommands.HideProgress()))))
                //                      {
                //                          Header = "Extract to \\" + path.RemoveExtension(appliedModels[0].Name),
                //                          IsEnabled = true,
                //                          IsVisibleOnMenu = true
                //                      });
                //    }
                //    else
                //        subCommands.Add(new CommandModel(
                //                ScriptCommands.ShowProgress("Extract",
                //                ScriptCommands.ForEach(appliedModels, am =>
                //                     ScriptCommands.ParseOrCreatePath(firstRoot.Parent.Profile as IDiskProfile,
                //                        path.Combine(parentPath, path.RemoveExtension(am.Name)), true,
                //                        destFolder =>
                //                            IOScriptCommands.TransferChild(am, destFolder, null, false)),
                //                     ScriptCommands.HideProgress()))) { Header = "Extract to {ArchiveName}\\", IsEnabled = true, IsVisibleOnMenu = true });

                //}
                #endregion


                #region Compress

                if (!appliedModels.Any(em => em is SzsChildModel) && !(appliedModels.Length == 1 && appliedModels[0] is SzsRootModel))
                {
                    Header = "Compress";
                    IEntryModel  firstEntry   = appliedModels[0];
                    IDiskProfile firstProfile = firstEntry.Profile as IDiskProfile;

                    if (firstProfile != null && !firstEntry.FullPath.StartsWith("::{") &&
                        firstEntry.Parent != null)
                    {
                        IPathHelper path = firstEntry.Profile.Path;
                        //Header = path.GetExtension(firstEntry.Name).TrimStart('.').FirstCharToUppercase();
                        string parentPath = path.GetDirectoryName(firstEntry.FullPath);

                        //e.g. C:\temp\abc.txt => C:\temp\temp.zip
                        string parentArchiveName = path.ChangeExtension(firstEntry.Parent.Name, ".zip");
                        string parentArchivePath = path.Combine(firstEntry.Parent.FullPath, parentArchiveName);

                        string firstArchiveName = path.ChangeExtension(firstEntry.Name, ".zip");
                        string firstArchivePath = path.Combine(firstEntry.Parent.FullPath, firstArchiveName);

                        subCommands.Add(new CommandModel(
                                            ScriptCommands.Assign(new Dictionary <string, object>()
                        {
                            { "{Profile}", firstEntry.Parent.Profile },
                            { "{Header}", "Compress" },
                            { "{CompressFiles}", appliedModels },
                            { "{StartupPath}", firstEntry.Parent.FullPath },
                            { "{FileName}", firstArchiveName }
                        }, false,
                                                                  IOScriptCommands.FileSave("Zip archives (.zip)|*.zip|7z archives (.7z)|*.7z", "{ArchivePath}",
                                                                                            WPFScriptCommands.ShowProgress("Compress",
                                                                                                                           IOScriptCommands.DiskParseOrCreateArchive("{Profile}", "{ArchivePath}", "{Archive}",
                                                                                                                                                                     IOScriptCommands.SzsDiskTransfer("{CompressFiles}", "{Archive}", false))),
                                                                                            UIScriptCommands.MessageBoxOK("Compress", "Compress is canceled."))))

                        {
                            Header          = "Compress to ...",
                            IsEnabled       = true,
                            IsVisibleOnMenu = true
                        });

                        Action <string, string> addCompressToPath = (destName, destPath) =>
                        {
                            subCommands.Add(new CommandModel(
                                                WPFScriptCommands.ShowProgress("Compress",
                                                                               IOScriptCommands.ParseOrCreateArchive(firstProfile, destPath,
                                                                                                                     pm => IOScriptCommands.DiskTransfer(appliedModels, pm, false, true,
                                                                                                                                                         null))))
                            {
                                Header          = "Compress to " + destName,
                                IsEnabled       = true,
                                IsVisibleOnMenu = true
                            });
                        };

                        addCompressToPath(firstArchiveName, firstArchivePath);
                        addCompressToPath(parentArchiveName, parentArchivePath);
                    }
                }
                #endregion
            }

            SubCommands     = subCommands;
            IsVisibleOnMenu = SubCommands.Count() > 0;
        }