forked from files-community/Files
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFilesystemOperations.cs
964 lines (843 loc) · 45.7 KB
/
FilesystemOperations.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
using Files.Common;
using Files.Enums;
using Files.Extensions;
using Files.Filesystem.FilesystemHistory;
using Files.Helpers;
using Files.Interacts;
using Microsoft.Toolkit.Uwp;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Windows.ApplicationModel.AppService;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI.Xaml.Controls;
using FileAttributes = System.IO.FileAttributes;
namespace Files.Filesystem
{
public enum ImpossibleActionResponseTypes
{
Skip,
Abort
}
public class FilesystemOperations : IFilesystemOperations
{
#region Private Members
private IShellPage associatedInstance;
private ItemManipulationModel itemManipulationModel => associatedInstance.SlimContentPage?.ItemManipulationModel;
private RecycleBinHelpers recycleBinHelpers;
#endregion Private Members
#region Constructor
public FilesystemOperations(IShellPage associatedInstance)
{
this.associatedInstance = associatedInstance;
recycleBinHelpers = new RecycleBinHelpers();
}
#endregion Constructor
#region IFilesystemOperations
public async Task<(IStorageHistory, IStorageItem)> CreateAsync(IStorageItem source, IProgress<FileSystemStatusCode> errorCode, CancellationToken cancellationToken)
{
IStorageItem item = null;
try
{
switch (source)
{
case IStorageFile:
{
var newEntryInfo = await RegistryHelper.GetNewContextMenuEntryForType(Path.GetExtension(source.Path));
if (newEntryInfo == null)
{
StorageFolder folder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(source.Path));
item = await folder.CreateFileAsync(Path.GetFileName(source.Path));
}
else
{
item = (await newEntryInfo.Create(source.Path, associatedInstance)).Result;
}
break;
}
case IStorageFolder:
{
StorageFolder folder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(source.Path));
item = await folder.CreateFolderAsync(Path.GetFileName(source.Path));
break;
}
default:
Debugger.Break();
break;
}
errorCode?.Report(FileSystemStatusCode.Success);
return (new StorageHistory(FileOperationType.CreateNew, source.CreateEnumerable(), null), item);
}
catch (Exception e)
{
errorCode?.Report(FilesystemTasks.GetErrorCode(e));
return (null, null);
}
}
public async Task<IStorageHistory> CopyAsync(IStorageItem source,
string destination,
NameCollisionOption collision,
IProgress<float> progress,
IProgress<FileSystemStatusCode> errorCode,
CancellationToken cancellationToken)
{
if (destination.StartsWith(App.AppSettings.RecycleBinPath))
{
errorCode?.Report(FileSystemStatusCode.Unauthorized);
progress?.Report(100.0f);
// Do not paste files and folders inside the recycle bin
await DialogDisplayHelper.ShowDialogAsync(
"ErrorDialogThisActionCannotBeDone".GetLocalized(),
"ErrorDialogUnsupportedOperation".GetLocalized());
return null;
}
IStorageItem copiedItem = null;
//long itemSize = await FilesystemHelpers.GetItemSize(await source.ToStorageItem(associatedInstance));
if (source is IStorageFolder)
{
if (!string.IsNullOrWhiteSpace(source.Path) &&
Path.GetDirectoryName(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();
ContentDialog dialog = new ContentDialog()
{
Title = "ErrorDialogThisActionCannotBeDone".GetLocalized(),
Content = $"{"ErrorDialogTheDestinationFolder".GetLocalized()} ({destinationName}) {"ErrorDialogIsASubfolder".GetLocalized()} (sourceName)",
//PrimaryButtonText = "ErrorDialogSkip".GetLocalized(),
CloseButtonText = "ErrorDialogCancel".GetLocalized()
};
ContentDialogResult result = await dialog.ShowAsync();
if (result == ContentDialogResult.Primary)
{
progress?.Report(100.0f);
errorCode?.Report(FileSystemStatusCode.InProgress | FileSystemStatusCode.Success);
}
else
{
progress?.Report(100.0f);
errorCode?.Report(FileSystemStatusCode.InProgress | FileSystemStatusCode.Generic);
}
return null;
}
else
{
// CopyFileFromApp only works on file not directories
var fsSourceFolder = await source.ToStorageItemResult(associatedInstance);
var fsDestinationFolder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(destination));
var fsResult = (FilesystemResult)(fsSourceFolder.ErrorCode | fsDestinationFolder.ErrorCode);
if (fsResult)
{
var fsCopyResult = await FilesystemTasks.Wrap(() => CloneDirectoryAsync((StorageFolder)fsSourceFolder, (StorageFolder)fsDestinationFolder, fsSourceFolder.Result.Name, collision.Convert()));
if (fsCopyResult == FileSystemStatusCode.AlreadyExists)
{
errorCode?.Report(FileSystemStatusCode.AlreadyExists);
progress?.Report(100.0f);
return null;
}
if (fsCopyResult)
{
if (FolderHelpers.CheckFolderForHiddenAttribute(source.Path))
{
// The source folder was hidden, apply hidden attribute to destination
NativeFileOperationsHelper.SetFileAttribute(fsCopyResult.Result.Path, FileAttributes.Hidden);
}
copiedItem = (StorageFolder)fsCopyResult;
}
fsResult = fsCopyResult;
}
if (fsResult == FileSystemStatusCode.Unauthorized)
{
fsResult = await PerformAdminOperation(new ValueSet()
{
{ "Arguments", "FileOperation" },
{ "fileop", "CopyItem" },
{ "operationID", Guid.NewGuid().ToString() },
{ "filepath", source.Path },
{ "destpath", destination },
{ "overwrite", collision == NameCollisionOption.ReplaceExisting }
});
}
errorCode?.Report(fsResult.ErrorCode);
if (!fsResult)
{
return null;
}
}
}
else if (source is IStorageFile)
{
var fsResult = (FilesystemResult)await Task.Run(() => NativeFileOperationsHelper.CopyFileFromApp(source.Path, destination, true));
if (!fsResult)
{
Debug.WriteLine(System.Runtime.InteropServices.Marshal.GetLastWin32Error());
FilesystemResult<StorageFolder> destinationResult = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(destination));
var sourceResult = await source.ToStorageItemResult(associatedInstance);
fsResult = sourceResult.ErrorCode | destinationResult.ErrorCode;
if (fsResult)
{
var file = (StorageFile)sourceResult;
var fsResultCopy = await FilesystemTasks.Wrap(() => file.CopyAsync(destinationResult.Result, Path.GetFileName(file.Name), collision).AsTask());
if (fsResultCopy == FileSystemStatusCode.AlreadyExists)
{
errorCode?.Report(FileSystemStatusCode.AlreadyExists);
progress?.Report(100.0f);
return null;
}
if (fsResultCopy)
{
copiedItem = fsResultCopy.Result;
}
fsResult = fsResultCopy;
}
if (fsResult == FileSystemStatusCode.Unauthorized)
{
fsResult = await PerformAdminOperation(new ValueSet()
{
{ "Arguments", "FileOperation" },
{ "fileop", "CopyItem" },
{ "operationID", Guid.NewGuid().ToString() },
{ "filepath", source.Path },
{ "destpath", destination },
{ "overwrite", collision == NameCollisionOption.ReplaceExisting }
});
}
}
errorCode?.Report(fsResult.ErrorCode);
if (!fsResult)
{
return null;
}
}
if (Path.GetDirectoryName(destination) == associatedInstance.FilesystemViewModel.WorkingDirectory.TrimPath())
{
await Windows.ApplicationModel.Core.CoreApplication.MainView.DispatcherQueue.EnqueueAsync(async () =>
{
await Task.Delay(50); // Small delay for the item to appear in the file list
List<ListedItem> copiedListedItems = associatedInstance.FilesystemViewModel.FilesAndFolders
.Where(listedItem => destination.Contains(listedItem.ItemPath)).ToList();
if (copiedListedItems.Count > 0)
{
itemManipulationModel.AddSelectedItems(copiedListedItems);
itemManipulationModel.FocusSelectedItems();
}
}, Windows.System.DispatcherQueuePriority.Low);
}
progress?.Report(100.0f);
if (collision == NameCollisionOption.ReplaceExisting)
{
errorCode?.Report(FileSystemStatusCode.Success);
return null; // Cannot undo overwrite operation
}
return new StorageHistory(FileOperationType.Copy, source, copiedItem);
}
public async Task<IStorageHistory> MoveAsync(IStorageItem source,
string destination,
NameCollisionOption collision,
IProgress<float> progress,
IProgress<FileSystemStatusCode> errorCode,
CancellationToken cancellationToken)
{
if (source.Path == destination)
{
progress?.Report(100.0f);
errorCode?.Report(FileSystemStatusCode.Success);
return null;
}
if (string.IsNullOrWhiteSpace(source.Path))
{
// Can't move (only copy) files from MTP devices because:
// StorageItems returned in DataPackageView are read-only
// The item.Path property will be empty and there's no way of retrieving a new StorageItem with R/W access
return await CopyAsync(source, destination, collision, progress, errorCode, cancellationToken);
}
if (destination.StartsWith(App.AppSettings.RecycleBinPath))
{
errorCode?.Report(FileSystemStatusCode.Unauthorized);
progress?.Report(100.0f);
// Do not paste files and folders inside the recycle bin
await DialogDisplayHelper.ShowDialogAsync(
"ErrorDialogThisActionCannotBeDone".GetLocalized(),
"ErrorDialogUnsupportedOperation".GetLocalized());
return null;
}
IStorageItem movedItem = null;
//long itemSize = await FilesystemHelpers.GetItemSize(await source.ToStorageItem(associatedInstance));
if (source is IStorageFolder)
{
if (!string.IsNullOrWhiteSpace(source.Path) &&
Path.GetDirectoryName(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();
ContentDialog dialog = new ContentDialog()
{
Title = "ErrorDialogThisActionCannotBeDone".GetLocalized(),
Content = "ErrorDialogTheDestinationFolder".GetLocalized() + " (" + destinationName + ") " + "ErrorDialogIsASubfolder".GetLocalized() + " (" + sourceName + ")",
//PrimaryButtonText = "ErrorDialogSkip".GetLocalized(),
CloseButtonText = "ErrorDialogCancel".GetLocalized()
};
ContentDialogResult result = await dialog.ShowAsync();
if (result == ContentDialogResult.Primary)
{
progress?.Report(100.0f);
errorCode?.Report(FileSystemStatusCode.InProgress | FileSystemStatusCode.Success);
}
else
{
progress?.Report(100.0f);
errorCode?.Report(FileSystemStatusCode.InProgress | FileSystemStatusCode.Generic);
}
return null;
}
else
{
var fsResult = (FilesystemResult)await Task.Run(() => NativeFileOperationsHelper.MoveFileFromApp(source.Path, destination));
if (!fsResult)
{
Debug.WriteLine(System.Runtime.InteropServices.Marshal.GetLastWin32Error());
var fsSourceFolder = await source.ToStorageItemResult(associatedInstance);
var fsDestinationFolder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(destination));
fsResult = fsSourceFolder.ErrorCode | fsDestinationFolder.ErrorCode;
if (fsResult)
{
var fsResultMove = await FilesystemTasks.Wrap(() => MoveDirectoryAsync((StorageFolder)fsSourceFolder, (StorageFolder)fsDestinationFolder, fsSourceFolder.Result.Name, collision.Convert(), true));
if (fsResultMove == FileSystemStatusCode.AlreadyExists)
{
progress?.Report(100.0f);
errorCode?.Report(FileSystemStatusCode.AlreadyExists);
return null;
}
if (fsResultMove)
{
if (FolderHelpers.CheckFolderForHiddenAttribute(source.Path))
{
// The source folder was hidden, apply hidden attribute to destination
NativeFileOperationsHelper.SetFileAttribute(fsResultMove.Result.Path, FileAttributes.Hidden);
}
movedItem = (StorageFolder)fsResultMove;
}
fsResult = fsResultMove;
}
if (fsResult == FileSystemStatusCode.Unauthorized || fsResult == FileSystemStatusCode.ReadOnly)
{
fsResult = await PerformAdminOperation(new ValueSet()
{
{ "Arguments", "FileOperation" },
{ "fileop", "MoveItem" },
{ "operationID", Guid.NewGuid().ToString() },
{ "filepath", source.Path },
{ "destpath", destination },
{ "overwrite", collision == NameCollisionOption.ReplaceExisting }
});
}
}
errorCode?.Report(fsResult.ErrorCode);
}
}
else if (source is IStorageFile)
{
var fsResult = (FilesystemResult)await Task.Run(() => NativeFileOperationsHelper.MoveFileFromApp(source.Path, destination));
if (!fsResult)
{
Debug.WriteLine(System.Runtime.InteropServices.Marshal.GetLastWin32Error());
FilesystemResult<StorageFolder> destinationResult = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(destination));
var sourceResult = await source.ToStorageItemResult(associatedInstance);
fsResult = sourceResult.ErrorCode | destinationResult.ErrorCode;
if (fsResult)
{
var file = (StorageFile)sourceResult;
var fsResultMove = await FilesystemTasks.Wrap(() => file.MoveAsync(destinationResult.Result, Path.GetFileName(file.Name), collision).AsTask());
if (fsResultMove == FileSystemStatusCode.AlreadyExists)
{
progress?.Report(100.0f);
errorCode?.Report(FileSystemStatusCode.AlreadyExists);
return null;
}
if (fsResultMove)
{
movedItem = file;
}
fsResult = fsResultMove;
}
if (fsResult == FileSystemStatusCode.Unauthorized || fsResult == FileSystemStatusCode.ReadOnly)
{
fsResult = await PerformAdminOperation(new ValueSet()
{
{ "Arguments", "FileOperation" },
{ "fileop", "MoveItem" },
{ "operationID", Guid.NewGuid().ToString() },
{ "filepath", source.Path },
{ "destpath", destination },
{ "overwrite", collision == NameCollisionOption.ReplaceExisting }
});
}
}
errorCode?.Report(fsResult.ErrorCode);
}
if (Path.GetDirectoryName(destination) == associatedInstance.FilesystemViewModel.WorkingDirectory.TrimPath())
{
await Windows.ApplicationModel.Core.CoreApplication.MainView.DispatcherQueue.EnqueueAsync(async () =>
{
await Task.Delay(50); // Small delay for the item to appear in the file list
List<ListedItem> movedListedItems = associatedInstance.FilesystemViewModel.FilesAndFolders
.Where(listedItem => destination.Contains(listedItem.ItemPath)).ToList();
if (movedListedItems.Count > 0)
{
itemManipulationModel.AddSelectedItems(movedListedItems);
itemManipulationModel.FocusSelectedItems();
}
}, Windows.System.DispatcherQueuePriority.Low);
}
progress?.Report(100.0f);
if (collision == NameCollisionOption.ReplaceExisting)
{
return null; // Cannot undo overwrite operation
}
return new StorageHistory(FileOperationType.Move, source, movedItem);
}
public async Task<IStorageHistory> DeleteAsync(IStorageItem source,
IProgress<float> progress,
IProgress<FileSystemStatusCode> errorCode,
bool permanently,
CancellationToken cancellationToken)
{
bool deleteFromRecycleBin = recycleBinHelpers.IsPathUnderRecycleBin(source.Path);
FilesystemResult fsResult = FileSystemStatusCode.InProgress;
errorCode?.Report(fsResult);
progress?.Report(0.0f);
if (permanently)
{
fsResult = (FilesystemResult)NativeFileOperationsHelper.DeleteFileFromApp(source.Path);
}
if (!fsResult)
{
if (source is IStorageFile)
{
fsResult = await associatedInstance.FilesystemViewModel.GetFileFromPathAsync(source.Path)
.OnSuccess((t) => t.DeleteAsync(permanently ? StorageDeleteOption.PermanentDelete : StorageDeleteOption.Default).AsTask());
}
else if (source is IStorageFolder)
{
fsResult = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(source.Path)
.OnSuccess((t) => t.DeleteAsync(permanently ? StorageDeleteOption.PermanentDelete : StorageDeleteOption.Default).AsTask());
}
}
errorCode?.Report(fsResult);
if (fsResult == FileSystemStatusCode.Unauthorized)
{
// Try again with fulltrust process (non admin: for shortcuts and hidden files)
var connection = await AppServiceConnectionHelper.Instance;
if (connection != null)
{
var (status, response) = await connection.SendMessageForResponseAsync(new ValueSet()
{
{ "Arguments", "FileOperation" },
{ "fileop", "DeleteItem" },
{ "operationID", Guid.NewGuid().ToString() },
{ "filepath", source.Path },
{ "permanently", permanently }
});
fsResult = (FilesystemResult)(status == AppServiceResponseStatus.Success
&& response.Get("Success", false));
}
if (!fsResult)
{
fsResult = await PerformAdminOperation(new ValueSet()
{
{ "Arguments", "FileOperation" },
{ "fileop", "DeleteItem" },
{ "operationID", Guid.NewGuid().ToString() },
{ "filepath", source.Path },
{ "permanently", permanently }
});
}
}
else if (fsResult == FileSystemStatusCode.InUse)
{
// TODO: retry or show dialog
await DialogDisplayHelper.ShowDialogAsync("FileInUseDeleteDialog/Title".GetLocalized(), "FileInUseDeleteDialog/Text".GetLocalized());
}
if (deleteFromRecycleBin)
{
// Recycle bin also stores a file starting with $I for each item
string iFilePath = Path.Combine(Path.GetDirectoryName(source.Path), Path.GetFileName(source.Path).Replace("$R", "$I"));
await associatedInstance.FilesystemViewModel.GetFileFromPathAsync(iFilePath)
.OnSuccess(iFile => iFile.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask());
}
errorCode?.Report(fsResult);
progress?.Report(100.0f);
if (fsResult)
{
await associatedInstance.FilesystemViewModel.RemoveFileOrFolderAsync(source.Path);
if (!permanently)
{
// Enumerate Recycle Bin
List<ShellFileItem> nameMatchItems, items = await recycleBinHelpers.EnumerateRecycleBin();
// Get name matching files
if (Path.GetExtension(source.Path) == ".lnk" || Path.GetExtension(source.Path) == ".url") // We need to check if it is a shortcut file
{
nameMatchItems = items.Where((item) => item.FilePath == Path.Combine(Path.GetDirectoryName(source.Path), Path.GetFileNameWithoutExtension(source.Path))).ToList();
}
else
{
nameMatchItems = items.Where((item) => item.FilePath == source.Path).ToList();
}
// Get newest file
ShellFileItem item = nameMatchItems.Where((item) => item.RecycleDate != null).OrderBy((item) => item.RecycleDate).FirstOrDefault();
return new StorageHistory(FileOperationType.Recycle, source, StorageItemHelpers.FromPathAndType(item?.RecyclePath, source.ItemType));
}
return new StorageHistory(FileOperationType.Delete, source, null);
}
else
{
// Stop at first error
return null;
}
}
public async Task<IStorageHistory> RenameAsync(IStorageItem source,
string newName,
NameCollisionOption collision,
IProgress<FileSystemStatusCode> errorCode,
CancellationToken cancellationToken)
{
if (Path.GetFileName(source.Path) == newName && collision == NameCollisionOption.FailIfExists)
{
errorCode?.Report(FileSystemStatusCode.AlreadyExists);
return null;
}
if (!string.IsNullOrWhiteSpace(newName)
&& !FilesystemHelpers.ContainsRestrictedCharacters(newName)
&& !FilesystemHelpers.ContainsRestrictedFileName(newName))
{
var renamed = await source.ToStorageItemResult(associatedInstance)
.OnSuccess(async (t) =>
{
if (t.Name.Equals(newName, StringComparison.CurrentCultureIgnoreCase))
{
await t.RenameAsync(newName, NameCollisionOption.ReplaceExisting);
}
else
{
await t.RenameAsync(newName, collision);
}
return t;
});
if (renamed)
{
errorCode?.Report(FileSystemStatusCode.Success);
return new StorageHistory(FileOperationType.Rename, source.CreateEnumerable(), renamed.Result.FromStorageItem());
}
else if (renamed == FileSystemStatusCode.Unauthorized)
{
// Try again with MoveFileFromApp
var destination = Path.Combine(Path.GetDirectoryName(source.Path), newName);
if (NativeFileOperationsHelper.MoveFileFromApp(source.Path, destination))
{
errorCode?.Report(FileSystemStatusCode.Success);
return new StorageHistory(FileOperationType.Rename, source, StorageItemHelpers.FromPathAndType(destination, source.ItemType));
}
else
{
var fsResult = await PerformAdminOperation(new ValueSet()
{
{ "Arguments", "FileOperation" },
{ "fileop", "RenameItem" },
{ "operationID", Guid.NewGuid().ToString() },
{ "filepath", source.Path },
{ "newName", newName },
{ "overwrite", collision == NameCollisionOption.ReplaceExisting }
});
if (fsResult)
{
errorCode?.Report(FileSystemStatusCode.Success);
return new StorageHistory(FileOperationType.Rename, source, StorageItemHelpers.FromPathAndType(destination, source.ItemType));
}
}
}
else if (renamed == FileSystemStatusCode.NotAFile || renamed == FileSystemStatusCode.NotAFolder)
{
await DialogDisplayHelper.ShowDialogAsync("RenameError/NameInvalid/Title".GetLocalized(), "RenameError/NameInvalid/Text".GetLocalized());
}
else if (renamed == FileSystemStatusCode.NameTooLong)
{
await DialogDisplayHelper.ShowDialogAsync("RenameError/TooLong/Title".GetLocalized(), "RenameError/TooLong/Text".GetLocalized());
}
else if (renamed == FileSystemStatusCode.InUse)
{
// TODO: proper dialog, retry
await DialogDisplayHelper.ShowDialogAsync("FileInUseDeleteDialog/Title".GetLocalized(), "");
}
else if (renamed == FileSystemStatusCode.NotFound)
{
await DialogDisplayHelper.ShowDialogAsync("RenameError/ItemDeleted/Title".GetLocalized(), "RenameError/ItemDeleted/Text".GetLocalized());
}
else if (renamed == FileSystemStatusCode.AlreadyExists)
{
var ItemAlreadyExistsDialog = new ContentDialog()
{
Title = "ItemAlreadyExistsDialogTitle".GetLocalized(),
Content = "ItemAlreadyExistsDialogContent".GetLocalized(),
PrimaryButtonText = "ItemAlreadyExistsDialogPrimaryButtonText".GetLocalized(),
SecondaryButtonText = "ItemAlreadyExistsDialogSecondaryButtonText".GetLocalized(),
CloseButtonText = "ItemAlreadyExistsDialogCloseButtonText".GetLocalized()
};
if (UIHelpers.IsAnyContentDialogOpen())
{
// Only a single ContentDialog can be open at any time.
return null;
}
ContentDialogResult result = await ItemAlreadyExistsDialog.ShowAsync();
if (result == ContentDialogResult.Primary)
{
return await RenameAsync(source, newName, NameCollisionOption.GenerateUniqueName, errorCode, cancellationToken);
}
else if (result == ContentDialogResult.Secondary)
{
return await RenameAsync(source, newName, NameCollisionOption.ReplaceExisting, errorCode, cancellationToken);
}
}
errorCode?.Report(renamed);
}
return null;
}
public async Task<IStorageHistory> RestoreFromTrashAsync(IStorageItem source,
string destination,
IProgress<float> progress,
IProgress<FileSystemStatusCode> errorCode,
CancellationToken cancellationToken)
{
FilesystemResult fsResult = FileSystemStatusCode.InProgress;
errorCode?.Report(fsResult);
fsResult = (FilesystemResult)await Task.Run(() => NativeFileOperationsHelper.MoveFileFromApp(source.Path, destination));
if (!fsResult)
{
if (source is IStorageFolder)
{
FilesystemResult<StorageFolder> sourceFolder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(source.Path);
FilesystemResult<StorageFolder> destinationFolder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(destination));
fsResult = sourceFolder.ErrorCode | destinationFolder.ErrorCode;
errorCode?.Report(fsResult);
if (fsResult)
{
fsResult = await FilesystemTasks.Wrap(() => MoveDirectoryAsync(sourceFolder.Result, destinationFolder.Result, Path.GetFileName(destination),
CreationCollisionOption.FailIfExists, true));
// TODO: we could use here FilesystemHelpers with registerHistory false?
}
errorCode?.Report(fsResult);
}
else
{
FilesystemResult<StorageFile> sourceFile = await associatedInstance.FilesystemViewModel.GetFileFromPathAsync(source.Path);
FilesystemResult<StorageFolder> destinationFolder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(destination));
fsResult = sourceFile.ErrorCode | destinationFolder.ErrorCode;
errorCode?.Report(fsResult);
if (fsResult)
{
fsResult = await FilesystemTasks.Wrap(() => sourceFile.Result.MoveAsync(destinationFolder.Result, Path.GetFileName(destination), NameCollisionOption.GenerateUniqueName).AsTask());
}
errorCode?.Report(fsResult);
}
if (fsResult == FileSystemStatusCode.Unauthorized || fsResult == FileSystemStatusCode.ReadOnly)
{
fsResult = await PerformAdminOperation(new ValueSet()
{
{ "Arguments", "FileOperation" },
{ "fileop", "MoveItem" },
{ "operationID", Guid.NewGuid().ToString() },
{ "filepath", source.Path },
{ "destpath", destination },
{ "overwrite", false }
});
}
}
if (fsResult)
{
// Recycle bin also stores a file starting with $I for each item
string iFilePath = Path.Combine(Path.GetDirectoryName(source.Path), Path.GetFileName(source.Path).Replace("$R", "$I"));
await associatedInstance.FilesystemViewModel.GetFileFromPathAsync(iFilePath)
.OnSuccess(iFile => iFile.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask());
}
errorCode?.Report(fsResult);
if (fsResult != FileSystemStatusCode.Success)
{
if (((FileSystemStatusCode)fsResult).HasFlag(FileSystemStatusCode.Unauthorized))
{
await DialogDisplayHelper.ShowDialogAsync("AccessDeniedDeleteDialog/Title".GetLocalized(), "AccessDeniedDeleteDialog/Text".GetLocalized());
}
else if (((FileSystemStatusCode)fsResult).HasFlag(FileSystemStatusCode.Unauthorized))
{
await DialogDisplayHelper.ShowDialogAsync("FileNotFoundDialog/Title".GetLocalized(), "FileNotFoundDialog/Text".GetLocalized());
}
else if (((FileSystemStatusCode)fsResult).HasFlag(FileSystemStatusCode.AlreadyExists))
{
await DialogDisplayHelper.ShowDialogAsync("ItemAlreadyExistsDialogTitle".GetLocalized(), "ItemAlreadyExistsDialogContent".GetLocalized());
}
}
return new StorageHistory(FileOperationType.Restore, source, StorageItemHelpers.FromPathAndType(destination, source.ItemType));
}
#endregion IFilesystemOperations
#region Helpers
private async static Task<StorageFolder> CloneDirectoryAsync(IStorageFolder sourceFolder, IStorageFolder destinationFolder, string sourceRootName, CreationCollisionOption collision = CreationCollisionOption.FailIfExists)
{
StorageFolder createdRoot = await destinationFolder.CreateFolderAsync(sourceRootName, collision);
destinationFolder = createdRoot;
foreach (IStorageFile fileInSourceDir in await sourceFolder.GetFilesAsync())
{
await fileInSourceDir.CopyAsync(destinationFolder, fileInSourceDir.Name, NameCollisionOption.GenerateUniqueName);
}
foreach (IStorageFolder folderinSourceDir in await sourceFolder.GetFoldersAsync())
{
await CloneDirectoryAsync(folderinSourceDir, destinationFolder, folderinSourceDir.Name);
}
return createdRoot;
}
private static async Task<StorageFolder> MoveDirectoryAsync(IStorageFolder sourceFolder, IStorageFolder destinationDirectory, string sourceRootName, CreationCollisionOption collision = CreationCollisionOption.FailIfExists, bool deleteSource = false)
{
StorageFolder createdRoot = await destinationDirectory.CreateFolderAsync(sourceRootName, collision);
destinationDirectory = createdRoot;
foreach (StorageFile fileInSourceDir in await sourceFolder.GetFilesAsync())
{
await fileInSourceDir.MoveAsync(destinationDirectory, fileInSourceDir.Name, NameCollisionOption.GenerateUniqueName);
}
foreach (StorageFolder folderinSourceDir in await sourceFolder.GetFoldersAsync())
{
await MoveDirectoryAsync(folderinSourceDir, destinationDirectory, folderinSourceDir.Name, collision, false);
}
if (deleteSource)
{
await sourceFolder.DeleteAsync(StorageDeleteOption.Default);
}
App.JumpList.RemoveFolder(sourceFolder.Path);
return createdRoot;
}
private async Task<FilesystemResult> PerformAdminOperation(ValueSet operation)
{
var elevateConfirmDialog = new Files.Dialogs.ElevateConfirmDialog();
var elevateConfirmResult = await elevateConfirmDialog.ShowAsync();
if (elevateConfirmResult == ContentDialogResult.Primary)
{
var connection = await AppServiceConnectionHelper.Instance;
if (connection != null && await connection.Elevate())
{
// Try again with fulltrust process (admin)
connection = await AppServiceConnectionHelper.Instance;
if (connection != null)
{
var (status, response) = await connection.SendMessageForResponseAsync(operation);
return (FilesystemResult)(status == AppServiceResponseStatus.Success
&& response.Get("Success", false));
}
}
}
return (FilesystemResult)false;
}
#endregion Helpers
#region IDisposable
public void Dispose()
{
recycleBinHelpers = null;
associatedInstance = null;
}
#endregion IDisposable
public async Task<IStorageHistory> CopyItemsAsync(IEnumerable<IStorageItem> source, IEnumerable<string> destination, IEnumerable<FileNameConflictResolveOptionType> collisions, IProgress<float> progress, IProgress<FileSystemStatusCode> errorCode, CancellationToken cancellationToken)
{
return await CopyItemsAsync(source.Select((item) => item.FromStorageItem()).ToList(), destination, collisions, progress, errorCode, cancellationToken);
}
public async Task<IStorageHistory> CopyItemsAsync(IEnumerable<IStorageItemWithPath> source, IEnumerable<string> destination, IEnumerable<FileNameConflictResolveOptionType> collisions, IProgress<float> progress, IProgress<FileSystemStatusCode> errorCode, CancellationToken token)
{
var rawStorageHistory = new List<IStorageHistory>();
for (int i = 0; i < source.Count(); i++)
{
if (token.IsCancellationRequested)
{
break;
}
if (collisions.ElementAt(i) != FileNameConflictResolveOptionType.Skip)
{
rawStorageHistory.Add(await CopyAsync(
source.ElementAt(i),
destination.ElementAt(i),
collisions.ElementAt(i).Convert(),
null,
errorCode,
token));
}
progress?.Report(i / (float)source.Count() * 100.0f);
}
if (rawStorageHistory.Any() && rawStorageHistory.TrueForAll((item) => item != null))
{
return new StorageHistory(
rawStorageHistory[0].OperationType,
rawStorageHistory.SelectMany((item) => item.Source).ToList(),
rawStorageHistory.SelectMany((item) => item.Destination).ToList());
}
return null;
}
public async Task<IStorageHistory> MoveItemsAsync(IEnumerable<IStorageItem> source, IEnumerable<string> destination, IEnumerable<FileNameConflictResolveOptionType> collisions, IProgress<float> progress, IProgress<FileSystemStatusCode> errorCode, CancellationToken token)
{
var rawStorageHistory = new List<IStorageHistory>();
for (int i = 0; i < source.Count(); i++)
{
if (token.IsCancellationRequested)
{
break;
}
if (collisions.ElementAt(i) != FileNameConflictResolveOptionType.Skip)
{
rawStorageHistory.Add(await MoveAsync(
source.ElementAt(i),
destination.ElementAt(i),
collisions.ElementAt(i).Convert(),
null,
errorCode,
token));
}
progress?.Report(i / (float)source.Count() * 100.0f);
}
if (rawStorageHistory.Any() && rawStorageHistory.TrueForAll((item) => item != null))
{
return new StorageHistory(
rawStorageHistory[0].OperationType,
rawStorageHistory.SelectMany((item) => item.Source).ToList(),
rawStorageHistory.SelectMany((item) => item.Destination).ToList());
}
return null;
}
public async Task<IStorageHistory> DeleteItemsAsync(IEnumerable<IStorageItem> source, IProgress<float> progress, IProgress<FileSystemStatusCode> errorCode, bool permanently, CancellationToken token)
{
bool originalPermanently = permanently;
var rawStorageHistory = new List<IStorageHistory>();
for (int i = 0; i < source.Count(); i++)
{
if (token.IsCancellationRequested)
{
break;
}
if (recycleBinHelpers.IsPathUnderRecycleBin(source.ElementAt(i).Path))
{
permanently = true;
}
else
{
permanently = originalPermanently;
}
rawStorageHistory.Add(await DeleteAsync(source.ElementAt(i), null, errorCode, permanently, token));
progress?.Report((float)i / source.Count() * 100.0f);
}
if (rawStorageHistory.Any() && rawStorageHistory.TrueForAll((item) => item != null))
{
return new StorageHistory(
rawStorageHistory[0].OperationType,
rawStorageHistory.SelectMany((item) => item.Source).ToList(),
rawStorageHistory.SelectMany((item) => item.Destination).ToList());
}
return null;
}
}
}