Skip to content

Commit

Permalink
Simplified FilesystemOperations
Browse files Browse the repository at this point in the history
  • Loading branch information
gave92 committed Aug 21, 2021
1 parent af74cdb commit 5ed2952
Show file tree
Hide file tree
Showing 6 changed files with 56 additions and 135 deletions.
127 changes: 14 additions & 113 deletions Files/Filesystem/FilesystemOperations/FilesystemOperations.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public FilesystemOperations(IShellPage associatedInstance)
var newEntryInfo = await RegistryHelper.GetNewContextMenuEntryForType(Path.GetExtension(source.Path));
if (newEntryInfo == null)
{
BaseStorageFolder folder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(source.Path));
BaseStorageFolder folder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(PathNormalization.GetParentDir(source.Path));
item = await folder.CreateFileAsync(Path.GetFileName(source.Path));
}
else
Expand All @@ -78,7 +78,7 @@ public FilesystemOperations(IShellPage associatedInstance)

case FilesystemItemType.Directory:
{
BaseStorageFolder folder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(source.Path));
BaseStorageFolder folder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(PathNormalization.GetParentDir(source.Path));
item = await folder.CreateFolderAsync(Path.GetFileName(source.Path));

break;
Expand Down Expand Up @@ -145,7 +145,7 @@ await DialogDisplayHelper.ShowDialogAsync(
if (source.ItemType == FilesystemItemType.Directory)
{
if (!string.IsNullOrWhiteSpace(source.Path) &&
Path.GetDirectoryName(destination).IsSubPathOf(source.Path)) // We check if user tried to copy anything above the source.ItemPath
PathNormalization.GetParentDir(destination).IsSubPathOf(source.Path)) // We check if user tried to copy anything above the source.ItemPath
{
var destinationName = destination.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).Last();
var sourceName = source.Path.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).Last();
Expand All @@ -171,11 +171,11 @@ await DialogDisplayHelper.ShowDialogAsync(
}
return null;
}
else if (!FtpHelpers.IsFtpPath(destination) && !FtpHelpers.IsFtpPath(source.Path))
else
{
// CopyFileFromApp only works on file not directories
var fsSourceFolder = await source.ToStorageItemResult(associatedInstance);
var fsDestinationFolder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(destination));
var fsDestinationFolder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(PathNormalization.GetParentDir(destination));
var fsResult = (FilesystemResult)(fsSourceFolder.ErrorCode | fsDestinationFolder.ErrorCode);

if (fsResult)
Expand Down Expand Up @@ -218,38 +218,16 @@ await DialogDisplayHelper.ShowDialogAsync(
return null;
}
}
else if (FtpHelpers.IsFtpPath(destination) && !FtpHelpers.IsFtpPath(source.Path))
{
var fsSourceFolder = await source.ToStorageItemResult(associatedInstance);
var ftpDestFolder = await new StorageFolderWithPath(null, destination).ToStorageItemResult(associatedInstance);
var fsCopyResult = await FilesystemTasks.Wrap(() => CloneDirectoryToFtpAsync((BaseStorageFolder)fsSourceFolder, (FtpStorageFolder)ftpDestFolder.Result, collision.Convert()));

if (fsCopyResult == FileSystemStatusCode.AlreadyExists)
{
errorCode?.Report(FileSystemStatusCode.AlreadyExists);
progress?.Report(100.0f);
return null;
}

errorCode?.Report(fsCopyResult ? FileSystemStatusCode.Success : FileSystemStatusCode.Generic);
progress?.Report(100.0f);
return null;
}
else
{
errorCode?.Report(FileSystemStatusCode.Generic);
return null;
}
}
else if (source.ItemType == FilesystemItemType.File && !string.IsNullOrEmpty(source.Path) && !FtpHelpers.IsFtpPath(destination))
else if (source.ItemType == FilesystemItemType.File)
{
var fsResult = (FilesystemResult)await Task.Run(() => NativeFileOperationsHelper.CopyFileFromApp(source.Path, destination, true));

if (!fsResult)
{
Debug.WriteLine(System.Runtime.InteropServices.Marshal.GetLastWin32Error());

FilesystemResult<BaseStorageFolder> destinationResult = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(destination));
FilesystemResult<BaseStorageFolder> destinationResult = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(PathNormalization.GetParentDir(destination));
var sourceResult = await source.ToStorageItemResult(associatedInstance);
fsResult = sourceResult.ErrorCode | destinationResult.ErrorCode;

Expand Down Expand Up @@ -299,67 +277,8 @@ await DialogDisplayHelper.ShowDialogAsync(
return null;
}
}
else if (string.IsNullOrEmpty(source.Path) && !FtpHelpers.IsFtpPath(destination))
{
var fsResult = source.Item is BaseStorageFile file ? await FilesystemTasks.Wrap(async () =>
await file.CopyAsync(
await StorageFileExtensions.DangerousGetFolderFromPathAsync(Path.GetDirectoryName(destination)),
file.Name,
collision)) : new FilesystemResult<BaseStorageFile>(null, FileSystemStatusCode.Generic);

if (!fsResult)
{
errorCode?.Report(fsResult.ErrorCode);
return null;
}
}
else if (FtpHelpers.IsFtpPath(destination))
{
using var ftpClient = new FtpClient();
ftpClient.Host = FtpHelpers.GetFtpHost(destination);
ftpClient.Port = FtpHelpers.GetFtpPort(destination);
ftpClient.Credentials = FtpManager.Credentials.Get(ftpClient.Host, FtpManager.Anonymous);

if (!await ftpClient.EnsureConnectedAsync())
{
errorCode?.Report(FileSystemStatusCode.Generic);
return null;
}

if (source.Item is BaseStorageFile file)
{
void ReportFtpPorgress(object sender, FtpProgress p)
{
progress?.Report((float)p.Progress);
}

using var stream = await file.OpenStreamForReadAsync();

var ftpProgress = new Progress<FtpProgress>();
ftpProgress.ProgressChanged += ReportFtpPorgress;

var result = await ftpClient.UploadAsync(stream, FtpHelpers.GetFtpPath(destination), collision switch
{
NameCollisionOption.ReplaceExisting => FtpRemoteExists.Overwrite,
_ => FtpRemoteExists.Skip,
}, false, ftpProgress, cancellationToken);

ftpProgress.ProgressChanged -= ReportFtpPorgress;

if (result != FtpStatus.Success)
{
errorCode?.Report(FileSystemStatusCode.Generic);
return null;
}
}
}
else
{
errorCode?.Report(FileSystemStatusCode.Generic);
return null;
}

if (Path.GetDirectoryName(destination) == associatedInstance.FilesystemViewModel.WorkingDirectory.TrimPath())
if (PathNormalization.GetParentDir(destination) == associatedInstance.FilesystemViewModel.WorkingDirectory.TrimPath())
{
await Windows.ApplicationModel.Core.CoreApplication.MainView.DispatcherQueue.EnqueueAsync(async () =>
{
Expand Down Expand Up @@ -444,7 +363,7 @@ await DialogDisplayHelper.ShowDialogAsync(
if (source.ItemType == FilesystemItemType.Directory)
{
if (!string.IsNullOrWhiteSpace(source.Path) &&
Path.GetDirectoryName(destination).IsSubPathOf(source.Path)) // We check if user tried to move anything above the source.ItemPath
PathNormalization.GetParentDir(destination).IsSubPathOf(source.Path)) // We check if user tried to move anything above the source.ItemPath
{
var destinationName = destination.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).Last();
var sourceName = source.Path.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).Last();
Expand Down Expand Up @@ -479,7 +398,7 @@ await DialogDisplayHelper.ShowDialogAsync(
Debug.WriteLine(System.Runtime.InteropServices.Marshal.GetLastWin32Error());

var fsSourceFolder = await source.ToStorageItemResult(associatedInstance);
var fsDestinationFolder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(destination));
var fsDestinationFolder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(PathNormalization.GetParentDir(destination));
fsResult = fsSourceFolder.ErrorCode | fsDestinationFolder.ErrorCode;

if (fsResult)
Expand Down Expand Up @@ -528,7 +447,7 @@ await DialogDisplayHelper.ShowDialogAsync(
{
Debug.WriteLine(System.Runtime.InteropServices.Marshal.GetLastWin32Error());

FilesystemResult<BaseStorageFolder> destinationResult = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(destination));
FilesystemResult<BaseStorageFolder> destinationResult = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(PathNormalization.GetParentDir(destination));
var sourceResult = await source.ToStorageItemResult(associatedInstance);
fsResult = sourceResult.ErrorCode | destinationResult.ErrorCode;

Expand Down Expand Up @@ -566,7 +485,7 @@ await DialogDisplayHelper.ShowDialogAsync(
errorCode?.Report(fsResult.ErrorCode);
}

if (Path.GetDirectoryName(destination) == associatedInstance.FilesystemViewModel.WorkingDirectory.TrimPath())
if (PathNormalization.GetParentDir(destination) == associatedInstance.FilesystemViewModel.WorkingDirectory.TrimPath())
{
await Windows.ApplicationModel.Core.CoreApplication.MainView.DispatcherQueue.EnqueueAsync(async () =>
{
Expand Down Expand Up @@ -844,7 +763,7 @@ public async Task<IStorageHistory> RestoreFromTrashAsync(IStorageItemWithPath so
if (source.ItemType == FilesystemItemType.Directory)
{
FilesystemResult<BaseStorageFolder> sourceFolder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(source.Path);
FilesystemResult<BaseStorageFolder> destinationFolder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(destination));
FilesystemResult<BaseStorageFolder> destinationFolder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(PathNormalization.GetParentDir(destination));

fsResult = sourceFolder.ErrorCode | destinationFolder.ErrorCode;
errorCode?.Report(fsResult);
Expand All @@ -860,7 +779,7 @@ public async Task<IStorageHistory> RestoreFromTrashAsync(IStorageItemWithPath so
else
{
FilesystemResult<BaseStorageFile> sourceFile = await associatedInstance.FilesystemViewModel.GetFileFromPathAsync(source.Path);
FilesystemResult<BaseStorageFolder> destinationFolder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(destination));
FilesystemResult<BaseStorageFolder> destinationFolder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(PathNormalization.GetParentDir(destination));

fsResult = sourceFile.ErrorCode | destinationFolder.ErrorCode;
errorCode?.Report(fsResult);
Expand Down Expand Up @@ -935,24 +854,6 @@ private async static Task<BaseStorageFolder> CloneDirectoryAsync(BaseStorageFold
return createdRoot;
}

private async static Task CloneDirectoryToFtpAsync(BaseStorageFolder sourceFolder, FtpStorageFolder destinationFolder, CreationCollisionOption collision = CreationCollisionOption.FailIfExists)
{
var result = await FilesystemTasks.Wrap(async () => await destinationFolder.CreateFolderAsync(sourceFolder.Name, collision));

if (result)
{
foreach (BaseStorageFile fileInSourceDir in await sourceFolder.GetFilesAsync())
{
await destinationFolder.UploadFileAsync(fileInSourceDir, fileInSourceDir.Name, NameCollisionOption.FailIfExists);
}

foreach (BaseStorageFolder folderinSourceDir in await sourceFolder.GetFoldersAsync())
{
await CloneDirectoryToFtpAsync(folderinSourceDir, destinationFolder.CloneWithPath($"{destinationFolder.Path}/{sourceFolder.Name}"));
}
}
}

private static async Task<BaseStorageFolder> MoveDirectoryAsync(BaseStorageFolder sourceFolder, BaseStorageFolder destinationDirectory, string sourceRootName, CreationCollisionOption collision = CreationCollisionOption.FailIfExists, bool deleteSource = false)
{
BaseStorageFolder createdRoot = await destinationDirectory.CreateFolderAsync(sourceRootName, collision);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using Files.Enums;
using Files.Extensions;
using Files.Filesystem.FilesystemHistory;
using Files.Filesystem.StorageItems;
using Files.Helpers;
using Files.Interacts;
using Files.ViewModels;
Expand Down Expand Up @@ -618,11 +617,11 @@ public async Task<ReturnResult> CopyItemsFromClipboard(DataPackageView packageVi
{
binItems ??= await recycleBinHelpers.EnumerateRecycleBin();
var matchingItem = binItems.FirstOrDefault(x => x.RecyclePath == item.Path); // Get original file name
destinations.Add(Path.Combine(destination, matchingItem?.FileName ?? item.Name));
destinations.Add(PathNormalization.Combine(destination, matchingItem?.FileName ?? item.Name));
}
else
{
destinations.Add(Path.Combine(destination, item.Name));
destinations.Add(PathNormalization.Combine(destination, item.Name));
}
}

Expand Down Expand Up @@ -846,11 +845,11 @@ public async Task<ReturnResult> MoveItemsFromClipboard(DataPackageView packageVi
{
binItems ??= await recycleBinHelpers.EnumerateRecycleBin();
var matchingItem = binItems.FirstOrDefault(x => x.RecyclePath == item.Path); // Get original file name
destinations.Add(Path.Combine(destination, matchingItem?.FileName ?? item.Name));
destinations.Add(PathNormalization.Combine(destination, matchingItem?.FileName ?? item.Name));
}
else
{
destinations.Add(Path.Combine(destination, item.Name));
destinations.Add(PathNormalization.Combine(destination, item.Name));
}
}

Expand Down
2 changes: 1 addition & 1 deletion Files/Filesystem/ListedItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,7 @@ public FtpItem(FtpListItem item, string folder, string dateReturnFormat = null)
ItemDateModifiedReal = item.RawModified < DateTime.FromFileTimeUtc(0) ? DateTimeOffset.MinValue : item.RawModified;
ItemName = item.Name;
FileExtension = Path.GetExtension(item.Name);
ItemPath = Path.Combine(folder, item.Name).Replace("\\", "/");
ItemPath = PathNormalization.Combine(folder, item.Name);
PrimaryItemAttribute = isFile ? StorageItemTypes.File : StorageItemTypes.Folder;
ItemPropertiesInitialized = false;

Expand Down
17 changes: 14 additions & 3 deletions Files/Filesystem/StorageFileHelpers/StorageFileExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,11 @@ public static bool AreItemsAlreadyInFolder(this IEnumerable<IStorageItem> storag

public static BaseStorageFolder AsBaseStorageFolder(this IStorageItem item)
{
if (item.IsOfType(StorageItemTypes.Folder))
if (item == null)
{
return null;
}
else if (item.IsOfType(StorageItemTypes.Folder))
{
if (item is StorageFolder folder)
{
Expand All @@ -301,7 +305,11 @@ public static BaseStorageFolder AsBaseStorageFolder(this IStorageItem item)

public static BaseStorageFile AsBaseStorageFile(this IStorageItem item)
{
if (item.IsOfType(StorageItemTypes.File))
if (item == null)
{
return null;
}
else if (item.IsOfType(StorageItemTypes.File))
{
if (item is StorageFile file)
{
Expand All @@ -322,7 +330,10 @@ public static async Task<List<IStorageItem>> ToStandardStorageItemsAsync(this IE
{
try
{
if (item.IsOfType(StorageItemTypes.File))
if (item == null)
{
}
else if (item.IsOfType(StorageItemTypes.File))
{
newItems.Add(await item.AsBaseStorageFile().ToStorageFileAsync());
}
Expand Down
Loading

0 comments on commit 5ed2952

Please sign in to comment.