Exemplo n.º 1
0
        public override async Task <IScriptCommand> ExecuteAsync(ParameterDic pm)
        {
            IEntryModel entryModel = pm.GetValue <IEntryModel>(EntryKey);

            if (entryModel == null)
            {
                return(ResultCommand.Error(new ArgumentException(EntryKey + " is not found or not IEntryModel")));
            }

            IDiskProfile profile = entryModel.Profile as IDiskProfile;

            if (profile == null)
            {
                return(ResultCommand.Error(new NotSupportedException(EntryKey + "'s Profile is not IDiskProfile")));
            }

            using (var stream = await profile.DiskIO.OpenStreamAsync(entryModel, Access, pm.CancellationToken))
            {
                ParameterDic pmClone = pm.Clone();
                pmClone.SetValue(StreamKey, stream);
                logger.Debug(String.Format("{0} = Stream of {1}", StreamKey, EntryKey));
                await ScriptRunner.RunScriptAsync(pmClone, NextCommand);
            }

            if (Access == FileAccess.ReadWrite || Access == FileAccess.Write)
            {
                return(CoreScriptCommands.NotifyEntryChangedProfile(ChangeType.Changed, null, EntryKey, ThenCommand));
            }
            else
            {
                return(ThenCommand);
            }
        }
Exemplo n.º 2
0
 public static IScriptCommand DiskDeleteMultiple(string entriesKey, bool notifyChange, IScriptCommand nextCommand = null)
 {
     if (notifyChange)
     {
         nextCommand = CoreScriptCommands.NotifyEntryChanged(Defines.ChangeType.Deleted, null, entriesKey, nextCommand);
     }
     return(ScriptCommands.ForEach(entriesKey, "{CurrentDeleteItem}",
                                   CoreScriptCommands.DiskDelete("{CurrentDeleteItem}"), nextCommand));
 }
Exemplo n.º 3
0
        public override async Task <IScriptCommand> ExecuteAsync(ParameterDic pm)
        {
            IEntryModel[] entryModels = DirectoryEntryKey == null ? new IEntryModel[] { } :
            (await pm.GetValueAsEntryModelArrayAsync(DirectoryEntryKey));

            object evnt = new RootChangedEvent(ChangeType, entryModels);;

            return(CoreScriptCommands.BroadcastEvent(EventsKey, evnt, NextCommand));
        }
Exemplo n.º 4
0
 /// <summary>
 /// Download a web stream to a file.
 /// </summary>
 /// <param name="urlVariable">Url to access</param>
 /// <param name="destinationFileVariable">Destination file name.</param>
 /// <param name="nextCommand"></param>
 /// <returns></returns>
 public static IScriptCommand DownloadFile(string urlVariable = "{Url}",
                                           string destinationProfileVariable = "{Profile}", string destinationFileVariable = "{DestinationFile}",
                                           IScriptCommand nextCommand        = null)
 {
     return(CoreScriptCommands.Download(urlVariable, "{DownloadStream}",
                                        CoreScriptCommands.DiskParseOrCreateFile(destinationProfileVariable, destinationFileVariable, "{Destination}",
                                                                                 CoreScriptCommands.DiskOpenStream("{Destination}", "{DestinationStream}", FileExplorer.Defines.FileAccess.Write,
                                                                                                                   CoreScriptCommands.CopyStream("{DownloadStream}", "{DestinationStream}",
                                                                                                                                                 ScriptCommands.Reset(nextCommand, "{DownloadStream}", "{Destination}"))))));
 }
Exemplo n.º 5
0
 /// <summary>
 /// Not serializable, Copy contents from srcFile to destFile.
 /// </summary>
 /// <param name="srcFile"></param>
 /// <param name="destFile"></param>
 /// <param name="nextCommand"></param>
 /// <returns></returns>
 public static IScriptCommand DiskCopyFile(IEntryModel srcFile, IEntryModel destFile, IScriptCommand nextCommand = null)
 {
     return(ScriptCommands.Assign("{DiskCopyFile-Source}", srcFile, false,
                                  ScriptCommands.Assign("{DiskCopyFile-Dest}", destFile, false,
                                                        CoreScriptCommands.DiskOpenStream(dcSourceVariable, "{SourceStream}", FileExplorer.Defines.FileAccess.Read,
                                                                                          CoreScriptCommands.DiskOpenStream(dcDestVariable, "{DestinationStream}", FileExplorer.Defines.FileAccess.Write,
                                                                                                                            CoreScriptCommands.CopyStream("{CopyStream-Source}", "{CopyStream-Dest}",
                                                                                                                                                          CoreScriptCommands.NotifyEntryChanged(ChangeType.Created, null, dcSourceVariable, null, dcDestVariable,
                                                                                                                                                                                                ScriptCommands.Reset(nextCommand, dcSourceVariable, dcDestVariable))))))));
 }
Exemplo n.º 6
0
 public static IScriptCommand DiskTransferChild(string srcDirectoryVariable  = "{Source}",
                                                string destDirectoryVariable = "{DestinationDirectory}",
                                                string mask         = "*", ListOptions listOptions = ListOptions.File | ListOptions.Folder,
                                                bool removeOriginal = false, bool allowCustomImplementation = true, IScriptCommand nextCommand = null)
 {
     return(CoreScriptCommands.List(srcDirectoryVariable, "{DTC-ItemToTransfer}", mask, listOptions,
                                    ScriptCommands.ForEach("{DTC-ItemToTransfer}", "{DTC-CurrentItem}",
                                                           IOScriptCommands.DiskTransfer("{DTC-CurrentItem}", destDirectoryVariable, null, removeOriginal, allowCustomImplementation),
                                                           ScriptCommands.Reset(nextCommand, "{DTC-DestDirectory}", "{DTC-SrcDirectory}"))));
 }
Exemplo n.º 7
0
 public static IScriptCommand DiskParseOrCreateArchive(string profileVariable     = "{Profile}", string pathVariable = "{Path}", string destVariable = "{Entry}",
                                                       IScriptCommand nextCommand = null)
 {
     return
         (CoreScriptCommands.ParsePath(profileVariable, pathVariable, destVariable,
                                       nextCommand, //FoundCommand
                                                    //NotFoundCommand
                                       CoreScriptCommands.DiskCreatePath(profileVariable, pathVariable, false, destVariable, NameGenerationMode.NoRename,
                                                                         IOScriptCommands.AssignArchiveBytes(pathVariable, "{ArchiveBytes}",
                                                                                                             CoreScriptCommands.DiskOpenStream(destVariable, "{DestStream}", FileAccess.Write,
                                                                                                                                               CoreScriptCommands.CopyStream("{ArchiveBytes}", "{DestStream}"),
                                                                                                                                               CoreScriptCommands.ParsePath(profileVariable, pathVariable, destVariable, nextCommand))))));
 }
Exemplo n.º 8
0
 /// <summary>
 /// Serializable, Copy contents from file1 to file2
 /// </summary>
 /// <param name="sourceFileVariable">Filepath of source</param>
 /// <param name="destinationFileVariable">Filepath of destination</param>
 /// <param name="nextCommand"></param>
 /// <returns></returns>
 public static IScriptCommand DiskCopyFile(string sourceProfileVariable      = "{SourceProfile}", string sourceFileVariable = "{SourceFile}",
                                           string destinationProfileVariable = "{DestinationProfile}", string destinationFileVariable = "{DestinationFile}",
                                           IScriptCommand nextCommand        = null)
 {
     return(CoreScriptCommands.ParsePath(sourceProfileVariable, sourceFileVariable, dcSourceVariable,
                                         CoreScriptCommands.DiskParseOrCreateFile(destinationProfileVariable, destinationFileVariable, dcDestVariable,
                                                                                  CoreScriptCommands.DiskOpenStream(dcSourceVariable, "{SourceStream}", FileExplorer.Defines.FileAccess.Read,
                                                                                                                    CoreScriptCommands.DiskOpenStream(dcDestVariable, "{DestinationStream}", FileExplorer.Defines.FileAccess.Write,
                                                                                                                                                      CoreScriptCommands.CopyStream("{SourceStream}", "{DestinationStream}",
                                                                                                                                                                                    CoreScriptCommands.NotifyEntryChanged(ChangeType.Created, null, dcSourceVariable, null, dcDestVariable,
                                                                                                                                                                                                                          ScriptCommands.Reset(nextCommand, dcSourceVariable, dcDestVariable)))))),
                                         ResultCommand.Error(new FileNotFoundException(sourceFileVariable))));
 }
Exemplo n.º 9
0
        public static IScriptCommand DiskDelete(string entryKey, bool notifyChange,
                                                IScriptCommand nextCommand = null)
        {
            if (notifyChange)
            {
                nextCommand = CoreScriptCommands.NotifyEntryChangedProfile(ChangeType.Deleted, null, entryKey, nextCommand);
            }

            return(new DiskDelete()
            {
                EntryKey = entryKey,
                NextCommand = (ScriptCommandBase)nextCommand
            });
        }
Exemplo n.º 10
0
        public override async Task <IScriptCommand> ExecuteAsync(ParameterDic pm)
        {
            string path = pm.ReplaceVariableInsideBracketed(PathKey);

            if (path == null)
            {
                return(ResultCommand.Error(new ArgumentException("Path not specified.")));
            }

            IDiskProfile profile = pm.GetValue <IDiskProfile>(ProfileKey);

            if (profile == null)
            {
                return(ResultCommand.Error(new ArgumentException(ProfileKey + " is not assigned or not IDiskProfile.")));
            }

            string             parentPath     = profile.Path.GetDirectoryName(path);
            IFileNameGenerator fNameGenerator = FileNameGenerator.FromNameGenerationMode(NameGenerationMode,
                                                                                         profile.Path.GetFileName(path));

            string fileName = fNameGenerator.Generate();

            while (fileName != null &&
                   await profile.ParseAsync(profile.Path.Combine(parentPath, fileName)) != null)
            {
                fileName = fNameGenerator.Generate();
            }

            if (fileName == null)
            {
                return(ResultCommand.Error(new ArgumentException("Already exists.")));
            }

            string newEntryPath  = profile.Path.Combine(parentPath, fileName);
            var    createddModel = await profile.DiskIO.CreateAsync(newEntryPath, IsFolder, pm.CancellationToken);

            logger.Info(String.Format("{0} = {1} ({2})", DestinationKey, createddModel.FullPath, IsFolder ? "Folder" : "File"));
            pm.SetValue(DestinationKey, createddModel);

            return(CoreScriptCommands.NotifyEntryChanged(ChangeType.Created, null, DestinationKey, NextCommand));
        }
Exemplo n.º 11
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
            }
        }
Exemplo n.º 12
0
 /// <summary>
 /// Serializable, parse a path and go to specified directory.
 /// </summary>
 /// <param name="explorerVariable"></param>
 /// <param name="profileVariable"></param>
 /// <param name="pathOrPathVariable"></param>
 /// <param name="nextCommand"></param>
 /// <returns></returns>
 public static IScriptCommand ExplorerParseAndGoTo(string explorerVariable = "{Explorer}",
                                                   string profileVariable  = "{Profile}", string pathOrPathVariable = "", IScriptCommand nextCommand = null)
 {
     return(CoreScriptCommands.ParsePath(profileVariable, pathOrPathVariable, "{GoTo-Directory}",
                                         ExplorerGoTo(explorerVariable, "{Goto-Directory}", nextCommand)));
 }
Exemplo n.º 13
0
 /// <summary>
 /// Serializable, For DiskProfile only, parse a path, if not exists create it, store to destVariable (default Entry), then call next command.
 /// </summary>
 /// <param name="pathVariable">Actual path or reference variable (if Bracketed), e.g. C:\Temp or {Path}.</param>
 /// <param name="isFolder"></param>
 /// <param name="destVariable"></param>
 /// <param name="nameGenerationMode"></param>
 /// <param name="nextCommand"></param>
 /// <returns></returns>
 public static IScriptCommand DiskParseOrCreatePath(string profileVariable     = "{Profile}", string pathVariable = "{Path}", bool isFolder = false, string destVariable = "{Entry}",
                                                    IScriptCommand nextCommand = null)
 {
     return(ParsePath(profileVariable, pathVariable, destVariable, nextCommand, CoreScriptCommands.DiskCreatePath(profileVariable, pathVariable, isFolder, destVariable,
                                                                                                                  NameGenerationMode.NoRename, nextCommand)));
 }
Exemplo n.º 14
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));
        }
Exemplo n.º 15
0
        private async Task <IScriptCommand> transferSystemIOAsync(ParameterDic pm, IEntryModel[] srcEntries, IEntryModel destEntry, string destinationKey)
        {
            return(await Task.Run <IScriptCommand>(async() =>
            {
                var progress = pm.ContainsKey("Progress") ? pm["Progress"] as IProgress <TransferProgress> : 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 <string> createdPath = new List <string>();
                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)
                    {
                        if (Directory.Exists(destFullName))
                        {
                            changedPath.Add(destFullName);
                            //Directory.Delete(destFullName, true);
                        }
                        else
                        {
                            createdPath.Add(destFullName);
                        }

                        Directory.Move(srcMapping.IOPath, destFullName);     //Move directly.
                        progress.Report(TransferProgress.IncrementProcessedEntries());
                    }
                    else
                    {
                        if (File.Exists(destFullName))
                        {
                            changedPath.Add(destFullName);
                            File.Delete(destFullName);
                        }
                        else
                        {
                            createdPath.Add(destFullName);
                        }
                        File.Move(srcMapping.IOPath, destFullName);
                    }
                    progress.Report(TransferProgress.IncrementProcessedEntries());
                }

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


                return
                await GetAssignDestinationCommandAsync(pm, srcEntries, destEntry, destinationKey,
                                                       ScriptCommands.RunParallel(NextCommand,

                                                                                  CoreScriptCommands.NotifyEntryChangedPath(ChangeType.Created, destEntry.Profile, createdPath.ToArray()),
                                                                                  CoreScriptCommands.NotifyEntryChangedPath(ChangeType.Changed, destEntry.Profile, changedPath.ToArray())
                                                                                  ));
            }));
        }