예제 #1
0
        public override async Task <IScriptCommand> ExecuteAsync(ParameterDic pm)
        {
            IEntryModel[] srcEntries = null;
            IEntryModel   destEntry  = null;

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

                destEntry = await pm.GetValueAsEntryModelAsync(DestinationDirectoryEntryKey, null);
            }
            catch (ArgumentException ex)
            {
                return(ResultCommand.Error(ex));
            }

            if (!destEntry.IsDirectory)
            {
                return(ResultCommand.Error(new ArgumentException(DestinationDirectoryEntryKey + " is not a folder.")));
            }
            if (srcEntries.Length == 0)
            {
                return(ResultCommand.Error(new ArgumentException("Nothing to transfer.")));
            }

            var srcProfile  = srcEntries.First().Profile as IDiskProfile;
            var destProfile = destEntry.Profile as IDiskProfile;

            if (srcEntries == null || destProfile == null)
            {
                return(ResultCommand.Error(new ArgumentException("Either source or dest is not IDiskProfile.")));
            }

            var progress = pm.GetProgress() ?? NullTransferProgress.Instance;


            if (AllowCustomImplementation)
            {
                logger.Info(String.Format("{0} {1} -> {2} using CustomImplementation",
                                          RemoveOriginal ? "Move" : "Copy", srcEntries.GetDescription(), destEntry.Name));
                return(destProfile.DiskIO
                       .GetTransferCommand(SourceEntryKey, DestinationDirectoryEntryKey, DestinationKey, RemoveOriginal, NextCommand));
            }
            else
            {
                var srcMapper   = srcProfile.DiskIO.Mapper;
                var destMapping = destProfile.DiskIO.Mapper[destEntry];

                if (!destMapping.IsVirtual && RemoveOriginal && srcEntries.All(entry => !srcMapper[entry].IsVirtual))
                {
                    return(await transferSystemIOAsync(pm, srcEntries, destEntry, DestinationKey));
                }
                else
                {
                    return(await transferScriptCommandAsync(pm, srcEntries, destEntry, DestinationKey));
                }
            }
        }
예제 #2
0
        public async Task RunAsync(Queue <IScriptCommand> cmds, ParameterDic initialParameters)
        {
            ParameterDic pd = initialParameters;

            pd["ScriptRunner"] = this;

            while (cmds.Any())
            {
                try
                {
                    var current = cmds.Dequeue();

                    if (current.CanExecute(pd))
                    {
                        pd.CommandHistory.Add(current.CommandKey);
                        //logger.Info("Running " + current.CommandKey);

                        try
                        {
                            var retCmd = await current.ExecuteAsync(pd)
                                         .ConfigureAwait(current.RequireCaptureContext());

                            if (retCmd != null)
                            {
                                if (pd.Error != null)
                                {
                                    logger.Error("Error when running script", pd.Error);
                                    return;
                                }
                                cmds.Enqueue(retCmd);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                    else
                    {
                        throw new Exception(String.Format("Cannot execute {0}", current));
                    }
                }
                catch (Exception ex)
                {
                    pd.Error = ex;
                    logger.Error("Error when running script", ex);
                    var progress = pd.GetProgress();
                    if (progress != null)
                    {
                        progress.Report(Defines.TransferProgress.Error(ex));
                    }
                    throw ex;
                }
            }
        }
예제 #3
0
        private async Task <IScriptCommand> transferScriptCommandAsync(ParameterDic pm, IEntryModel[] srcEntries, IEntryModel destEntry, string destinationKey)
        {
            var progress = pm.GetProgress() ?? NullTransferProgress.Instance;

            var srcProfile  = srcEntries.First().Profile as IDiskProfile;
            var destProfile = destEntry.Profile as IDiskProfile;

            var srcMapper   = srcProfile.DiskIO.Mapper;
            var destMapping = destProfile.DiskIO.Mapper[destEntry];
            List <IScriptCommand> notifyChangeCommands = new List <IScriptCommand>();

            List <string> changedPath = new List <string>();

            progress.Report(TransferProgress.IncrementTotalEntries(srcEntries.Count()));
            foreach (var srcEntry in srcEntries)
            {
                var    srcMapping   = srcMapper[srcEntry];
                string destName     = PathFE.GetFileName(srcMapping.IOPath);
                string destFullName = destProfile.Path.Combine(destEntry.FullPath, destName);

                progress.Report(TransferProgress.From(srcEntry.FullPath, destEntry.FullPath));

                if (srcEntry.IsDirectory)
                {
                    await ScriptRunner.RunScriptAsync(pm,
                                                      ScriptCommands.Assign("{DT-SrcDirectory}", srcEntry, false,
                                                                            ScriptCommands.Assign("{DT-DestProfile}", destEntry.Profile, false,
                                                                                                  CoreScriptCommands.DiskParseOrCreateFolder("{DT-DestProfile}", destFullName, "{DT-DestDirectory}",
                                                                                                                                             IOScriptCommands.DiskTransferChild("{DT-SrcDirectory}", "{DT-DestDirectory}", RemoveOriginal, AllowCustomImplementation,
                                                                                                                                                                                ScriptCommands.Reset(ResultCommand.NoError, "{DT-DestDirectory}", "{DT-SrcDirectory}"))))));
                }
                else
                {
                    await ScriptRunner.RunScriptAsync(pm,
                                                      ScriptCommands.Assign("{DT-SrcFile}", srcEntry, false,
                                                                            ScriptCommands.Assign("{DT-SrcProfile}", srcEntry.Profile, false,
                                                                                                  ScriptCommands.Assign("{DT-DestProfile}", destEntry.Profile, false,
                                                                                                                        CoreScriptCommands.DiskParseOrCreateFile("{DT-DestProfile}", destFullName, "{DT-DestFile}",
                                                                                                                                                                 CoreScriptCommands.DiskCopyFile("{DT-SrcProfile}", "{DT-SrcFile}", "{DT-DestProfile}", "{DT-DestFile}",
                                                                                                                                                                                                 ScriptCommands.Reset(ResultCommand.NoError, "{DT-SrcFile}", "{DT-DestFile}")))))));
                }

                progress.Report(TransferProgress.IncrementProcessedEntries());
            }

            logger.Info(String.Format("{0} {1} -> {2} using ScriptCommand",
                                      RemoveOriginal ? "Move" : "Copy", srcEntries.GetDescription(), destEntry.Name));

            return(await GetAssignDestinationCommandAsync(pm, srcEntries, destEntry, destinationKey, NextCommand));
        }
예제 #4
0
        public override async Task <IScriptCommand> ExecuteAsync(ParameterDic pm)
        {
            IEnumerable e = pm.GetValue <IEnumerable>(ItemsKey);

            if (e == null)
            {
                return(ResultCommand.Error(new ArgumentException(ItemsKey)));
            }

            IProgress <TransferProgress> progress = NullTransferProgress.Instance;

            if (IsProgressEnabled)
            {
                List <object> list;
                e        = list = e.Cast <object>().ToList();
                progress = pm.GetProgress();
                progress.Report(TransferProgress.IncrementTotalEntries(list.Count));
            }

            uint counter = 0;

            pm.SetValue <bool>(BreakKey, false);
            foreach (var item in e)
            {
                if (pm.GetValue <bool>(BreakKey))
                {
                    break;
                }

                counter++;
                pm.SetValue(CurrentItemKey, item);
                await ScriptRunner.RunScriptAsync(pm, NextCommand);

                progress.Report(TransferProgress.IncrementProcessedEntries());
                if (pm.Error != null)
                {
                    pm.SetValue <Object>(CurrentItemKey, null);
                    return(ResultCommand.Error(pm.Error));
                }
            }
            logger.Info("Looped {0} items", counter);
            pm.SetValue <Object>(CurrentItemKey, null);

            return(ThenCommand);
        }
예제 #5
0
        public void Run(Queue <IScriptCommand> cmds, ParameterDic initialParameters)
        {
            ParameterDic pd = initialParameters;

            pd["ScriptRunner"] = this;

            while (cmds.Any())
            {
                try
                {
                    var current = cmds.Dequeue();
                    //logger.Info("Running " + current.CommandKey);
                    if (current.CanExecute(pd))
                    {
                        pd.CommandHistory.Add(current.CommandKey);
                        var retCmd = current.Execute(pd);
                        if (retCmd != null)
                        {
                            if (pd.Error != null)
                            {
                                throw pd.Error;
                            }
                            cmds.Enqueue(retCmd);
                        }
                    }
                    else
                    if (!(current is NullScriptCommand))
                    {
                        throw new Exception(String.Format("Cannot execute {0}", current));
                    }
                }
                catch (Exception ex)
                {
                    pd.Error = ex;
                    logger.Error("Error when running script", ex);
                    var progress = pd.GetProgress();
                    if (progress != null)
                    {
                        progress.Report(Defines.TransferProgress.Error(ex));
                    }
                    throw ex;
                }
            }
        }
예제 #6
0
        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
            }
        }