コード例 #1
0
ファイル: Download.cs プロジェクト: francisrc/FileExplorer
        public override async Task <IScriptCommand> ExecuteAsync(ParameterDic pm)
        {
            var    pdv = pm.GetValue <IProgress <TransferProgress> >("{Progress}", NullTransferProgress.Instance);
            string url = pm.GetValue <string>(UrlKey);

            if (url == null)
            {
                return(ResultCommand.Error(new ArgumentException("Unspecified Url.")));
            }

            try
            {
                using (var httpClient =
                           pm.ContainsKey(HttpClientKey) && pm[HttpClientKey] is Func <HttpClient>?((Func <HttpClient>)pm[HttpClientKey])() :
                               new HttpClient())
                {
                    var response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, pm.CancellationToken);

                    if (!response.IsSuccessStatusCode)
                    {
                        throw new WebException(String.Format("{0} when downloading {1}", response.StatusCode, url));
                    }

                    MemoryStream destStream = new MemoryStream();
                    logger.Info(String.Format("{0} = Stream of {1}", DestinationKey, url));
                    using (Stream srcStream = await response.Content.ReadAsStreamAsync())
                    {
                        pdv.Report(TransferProgress.From(url));
                        byte[] buffer         = new byte[1024];
                        ulong  totalBytesRead = 0;
                        ulong  totalBytes     = 0;
                        try { totalBytes = (ulong)srcStream.Length; }
                        catch (NotSupportedException) { }

                        int byteRead = await srcStream.ReadAsync(buffer, 0, buffer.Length, pm.CancellationToken);

                        while (byteRead > 0)
                        {
                            await destStream.WriteAsync(buffer, 0, byteRead, pm.CancellationToken);

                            totalBytesRead = totalBytesRead + (uint)byteRead;
                            short percentCompleted = (short)((float)totalBytesRead / (float)totalBytes * 100.0f);
                            pdv.Report(TransferProgress.UpdateCurrentProgress(percentCompleted));

                            byteRead = await srcStream.ReadAsync(buffer, 0, buffer.Length, pm.CancellationToken);
                        }
                        await destStream.FlushAsync();
                    }

                    pm.SetValue(DestinationKey, destStream.ToByteArray());
                    return(NextCommand);
                }
            }
            catch (Exception ex)
            {
                return(ResultCommand.Error(ex));
            }
        }
コード例 #2
0
        public void ProgressDialog()
        {
            ScriptRunner.RunScript(
                WPFScriptCommands.ShowProgress(_windowManager, "Testing",
                                               WPFScriptCommands.ReportProgress(TransferProgress.From("C:\\Demo\\FileExplorer3.txt", "http://fileexplorer.codeplex.com/FileExplorer3.txt"),
                                                                                WPFScriptCommands.ReportProgress(TransferProgress.IncrementTotalEntries(100),
                                                                                                                 WPFScriptCommands.ReportProgress(TransferProgress.IncrementProcessedEntries(20),
                                                                                                                                                  WPFScriptCommands.ReportProgress(TransferProgress.UpdateCurrentProgress(50))))))
                );
            //_windowManager.ShowDialog(new ProgressDialogViewModel(new ParameterDic()
            //{

            //}));
        }
コード例 #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)
        {
            var destProfile = _destDirModel.Profile as IDiskProfile;

            var    destMapping  = (_destDirModel.Profile as IDiskProfile).DiskIO.Mapper[_destDirModel];
            var    srcMapping   = (_srcModel.Profile as IDiskProfile).DiskIO.Mapper[_srcModel];
            string destName     = PathFE.GetFileName(srcMapping.IOPath);
            string destFullName = destProfile.Path.Combine(_destDirModel.FullPath, destName); //PathFE.Combine(destMapping.IOPath, destName);

            IEntryModel destModel = await _destDirModel.Profile.ParseAsync(destFullName);

            if (destModel == null)
            {
                destModel = await destProfile.DiskIO.CreateAsync(destFullName, true, pm.CancellationToken);

                destModel = (await _destDirModel.Profile.ListAsync(_destDirModel, CancellationToken.None, em =>
                                                                   em.FullPath.Equals(destFullName,
                                                                                      StringComparison.CurrentCultureIgnoreCase), true)).FirstOrDefault();
                _destDirModel.Profile.Events.PublishOnUIThread(new EntryChangedEvent(ChangeType.Created, destFullName));
            }

            if (destModel == null)
            {
                return(ResultCommand.Error(new Exception("Cannot construct destination " + destFullName)));
            }
            else
            {
                _progress.Report(TransferProgress.From(_srcModel.FullPath, destFullName));
                _progress.Report(TransferProgress.IncrementProcessedEntries()); //dest directory created
            }
            var srcSubModels = (await _srcModel.Profile.ListAsync(_srcModel, CancellationToken.None)).ToList();

            _progress.Report(TransferProgress.IncrementTotalEntries(srcSubModels.Count())); //source entries

            var resultCommands = srcSubModels.Select(m =>
                                                     (IScriptCommand) new FileTransferScriptCommand(m, destModel, _removeOriginal)).ToList();

            resultCommands.Add(new NotifyChangedCommand(_destDirModel.Profile, destFullName, ChangeType.Created));

            //if (_removeOriginal)
            //    resultCommands.Add(new DeleteEntryCommand(_srcModel));

            return(new RunInSequenceScriptCommand(resultCommands.ToArray()));
        }
コード例 #5
0
        private async Task <IScriptCommand> transferAsync(ParameterDic pm, IEntryModel[] ems,
                                                          IProgress <TransferProgress> progress, IScriptCommand thenCommand)
        {
            Dictionary <string, Stream> compressDic = new Dictionary <string, Stream>();
            IDiskProfile srcProfile    = _srcModel.Profile as IDiskProfile;
            string       srcParentPath = srcProfile.Path.GetDirectoryName(_srcModel.FullPath);

            foreach (var em in ems)
            {
                string relativePath = em.FullPath.Replace(srcParentPath, "").TrimStart('\\');
                compressDic.Add(relativePath, await srcProfile.DiskIO.OpenStreamAsync(em, Defines.FileAccess.Read, pm.CancellationToken));
            }

            var    destProfile = _destDirModel.Profile as SzsProfile;
            string archiveType = destProfile.Path.GetExtension(_destDirModel.Name);

            using (await destProfile.WorkingLock.LockAsync())
                await Task.Run(async() =>
                {
                    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(_destDirModel.Name));
                    using (var stream = await destProfile.DiskIO.OpenStreamAsync(_destDirModel, Defines.FileAccess.ReadWrite, pm.CancellationToken))
                        destProfile.Wrapper.CompressMultiple(archiveType, stream, compressDic, progress1);
                });

            return(thenCommand);
        }
コード例 #6
0
        public override async Task <IScriptCommand> ExecuteAsync(ParameterDic pm)
        {
            var    srcProfile   = _srcModel.Profile as IDiskProfile;
            var    destProfile  = _destDirModel.Profile as IDiskProfile;
            string destName     = _srcModel.GetName();
            string srcFullName  = _srcModel.FullPath;
            string destFullName = _destDirModel.Combine(destName);

            ChangeType ct = ChangeType.Created;

            if (destFullName.StartsWith("::"))
            {
                return(ResultCommand.Error(new ArgumentException("Transfer does not work with shell folders.")));
            }
            if (File.Exists(destFullName))
            {
                File.Delete(destFullName);
                ct = ChangeType.Changed;
            }

            using (var srcStream = await srcProfile.DiskIO.OpenStreamAsync(_srcModel.FullPath,
                                                                           FileExplorer.Defines.FileAccess.Read, pm.CancellationToken))
                using (var destStream = await destProfile.DiskIO.OpenStreamAsync(destFullName,
                                                                                 FileExplorer.Defines.FileAccess.Write, pm.CancellationToken))
                {
                    _progress.Report(TransferProgress.From(srcFullName, destFullName));
                    await StreamUtils.CopyStreamAsync(srcStream, destStream, false, false, false,
                                                      p => _progress.Report(new TransferProgress()
                    {
                        CurrentProgressPercent = p
                    })).ConfigureAwait(false);
                }
            if (_removeOriginal)
            {
                await srcProfile.DiskIO.DeleteAsync(_srcModel, pm.CancellationToken).ConfigureAwait(false);
            }

            _progress.Report(TransferProgress.IncrementProcessedEntries());

            return(new NotifyChangedCommand(_destDirModel.Profile, destFullName,
                                            _srcModel.Profile, srcFullName, ct));
        }
コード例 #7
0
        public override async Task <IScriptCommand> ExecuteAsync(ParameterDic pm)
        {
            try
            {
                var srcProfile  = _srcModel.Profile as IDiskProfile;
                var destProfile = _destDirModel.Profile as IDiskProfile;
                var progress    = pm.ContainsKey("Progress") ? pm["Progress"] as IProgress <TransferProgress> : NullTransferProgress.Instance;

                var    destMapping  = (_destDirModel.Profile as IDiskProfile).DiskIO.Mapper[_destDirModel];
                var    srcMapping   = (_srcModel.Profile as IDiskProfile).DiskIO.Mapper[_srcModel];
                string destName     = PathFE.GetFileName(srcMapping.IOPath);
                string destFullName = destProfile.Path.Combine(_destDirModel.FullPath, destName); //PathFE.Combine(destMapping.IOPath, destName);


                if (!srcMapping.IsVirtual && !destMapping.IsVirtual && _removeOriginal)
                {
                    //Disk based transfer
                    progress.Report(TransferProgress.From(_srcModel.FullPath, destFullName));
                    if (_srcModel.IsDirectory)
                    {
                        if (Directory.Exists(destFullName))
                        {
                            Directory.Delete(destFullName, true);
                        }
                        Directory.Move(srcMapping.IOPath, destFullName); //Move directly.
                        progress.Report(TransferProgress.IncrementProcessedEntries());
                    }
                    else
                    {
                        if (File.Exists(destFullName))
                        {
                            File.Delete(destFullName);
                        }
                        File.Move(srcMapping.IOPath, destFullName);
                    }
                    progress.Report(TransferProgress.IncrementProcessedEntries());
                    return(new NotifyChangedCommand(_destDirModel.Profile, destFullName, _srcModel.Profile,
                                                    _srcModel.FullPath, ChangeType.Moved));
                }
                else
                {
                    if (_srcModel.IsDirectory)
                    {
                        return(new CopyDirectoryTransferCommand(_srcModel, _destDirModel, _removeOriginal, progress));
                    }
                    else
                    {
                        return(new StreamFileTransferCommand(_srcModel, _destDirModel, _removeOriginal, progress));
                    }
                }



                //switch (_transferMode)
                //{
                //    case DragDropEffects.Move:
                //
                //

                //    case DragDropEffects.Copy:
                //        Directory.CreateDirectory(destFullName);
                //        _destDirModel.Profile.Events.Publish(new EntryChangedEvent(destFullName, ChangeType.Created));

                //        var destModel = (await _destDirModel.Profile.ListAsync(_destDirModel, em =>
                //                em.FullPath.Equals(destFullName,
                //                StringComparison.CurrentCultureIgnoreCase))).FirstOrDefault();
                //        var srcSubModels = (await _srcModel.Profile.ListAsync(_srcModel)).ToList();

                //        var resultCommands = srcSubModels.Select(m =>
                //            (IScriptCommand)new FileTransferScriptCommand(m, destModel, _transferMode)).ToList();
                //        resultCommands.Insert(0, new NotifyChangedCommand(_destDirModel.Profile, destFullName, ChangeType.Created));

                //        return new RunInSequenceScriptCommand(resultCommands.ToArray());
                //    default:
                //        throw new NotImplementedException();
                //}

                //}
                //else
                //{

                //}

                return(ResultCommand.NoError);
            }
            catch (Exception ex)
            {
                return(ResultCommand.Error(ex));
            }
        }
コード例 #8
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
            }
        }
コード例 #9
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())
                                                                                  ));
            }));
        }