forked from files-community/Files
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathZipStorageFile.cs
536 lines (484 loc) · 18.3 KB
/
ZipStorageFile.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
// Copyright (c) Files Community
// Licensed under the MIT License.
using Files.Shared.Helpers;
using SevenZip;
using System.IO;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Storage;
using Windows.Storage.FileProperties;
using Windows.Storage.Streams;
using Windows.Win32;
using IO = System.IO;
namespace Files.App.Utils.Storage
{
public sealed class ZipStorageFile : BaseStorageFile, IPasswordProtectedItem
{
private readonly string containerPath;
private readonly BaseStorageFile backingFile;
public override string Path { get; }
public override string Name { get; }
public override string DisplayName => Name;
public override string ContentType => "application/octet-stream";
public override string FileType => IO.Path.GetExtension(Name);
public override string FolderRelativeId => $"0\\{Name}";
public override string DisplayType
{
get
{
var itemType = "File".GetLocalizedResource();
if (Name.Contains('.', StringComparison.Ordinal))
{
itemType = FileType.Trim('.') + " " + itemType;
}
return itemType;
}
}
public override DateTimeOffset DateCreated { get; }
public override Windows.Storage.FileAttributes Attributes => Windows.Storage.FileAttributes.Normal | Windows.Storage.FileAttributes.ReadOnly;
private IStorageItemExtraProperties properties;
public override IStorageItemExtraProperties Properties => properties ??= new BaseBasicStorageItemExtraProperties(this);
public StorageCredential Credentials { get; set; } = new();
public Func<IPasswordProtectedItem, Task<StorageCredential>> PasswordRequestedCallback { get; set; }
public ZipStorageFile(string path, string containerPath)
{
Name = IO.Path.GetFileName(path.TrimEnd('\\', '/'));
Path = path;
this.containerPath = containerPath;
}
public ZipStorageFile(string path, string containerPath, BaseStorageFile backingFile) : this(path, containerPath)
=> this.backingFile = backingFile;
public ZipStorageFile(string path, string containerPath, ArchiveFileInfo entry) : this(path, containerPath)
=> DateCreated = entry.CreationTime == DateTime.MinValue ? DateTimeOffset.MinValue : entry.CreationTime;
public ZipStorageFile(string path, string containerPath, ArchiveFileInfo entry, BaseStorageFile backingFile) : this(path, containerPath, entry)
=> this.backingFile = backingFile;
public override IAsyncOperation<StorageFile> ToStorageFileAsync()
=> StorageFile.CreateStreamedFileAsync(Name, ZipDataStreamingHandler(Path), null);
public static IAsyncOperation<BaseStorageFile> FromPathAsync(string path)
{
if (!FileExtensionHelpers.IsBrowsableZipFile(path, out var ext))
{
return Task.FromResult<BaseStorageFile>(null).AsAsyncOperation();
}
var marker = path.IndexOf(ext, StringComparison.OrdinalIgnoreCase);
if (marker is not -1)
{
var containerPath = path.Substring(0, marker + ext.Length);
if (path == containerPath)
{
return Task.FromResult<BaseStorageFile>(null).AsAsyncOperation(); // Root
}
if (CheckAccess(containerPath))
{
return Task.FromResult<BaseStorageFile>(new ZipStorageFile(path, containerPath)).AsAsyncOperation();
}
}
return Task.FromResult<BaseStorageFile>(null).AsAsyncOperation();
}
public override bool IsEqual(IStorageItem item) => item?.Path == Path;
public override bool IsOfType(StorageItemTypes type) => type is StorageItemTypes.File;
public override IAsyncOperation<BaseStorageFolder> GetParentAsync() => throw new NotSupportedException();
public override IAsyncOperation<BaseBasicProperties> GetBasicPropertiesAsync() => GetBasicProperties().AsAsyncOperation();
public override IAsyncOperation<IRandomAccessStream> OpenAsync(FileAccessMode accessMode)
{
return AsyncInfo.Run((cancellationToken) => SafetyExtensions.Wrap<IRandomAccessStream>(async () =>
{
bool rw = accessMode is FileAccessMode.ReadWrite;
if (Path == containerPath)
{
if (backingFile is not null)
{
return await backingFile.OpenAsync(accessMode);
}
var file = Win32Helper.OpenFileForRead(containerPath, rw);
return file.IsInvalid ? null : new FileStream(file, rw ? FileAccess.ReadWrite : FileAccess.Read).AsRandomAccessStream();
}
if (!rw)
{
SevenZipExtractor zipFile = await OpenZipFileAsync();
if (zipFile is null || zipFile.ArchiveFileData is null)
{
return null;
}
//zipFile.IsStreamOwner = true;
var entry = zipFile.ArchiveFileData.FirstOrDefault(x => System.IO.Path.Combine(containerPath, x.FileName) == Path);
if (entry.FileName is not null)
{
var ms = new MemoryStream();
await zipFile.ExtractFileAsync(entry.Index, ms);
ms.Position = 0;
return new NonSeekableRandomAccessStreamForRead(ms, entry.Size)
{
DisposeCallback = () => zipFile.Dispose()
};
}
return null;
}
throw new NotSupportedException("Can't open zip file as RW");
}, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync));
}
public override IAsyncOperation<IRandomAccessStream> OpenAsync(FileAccessMode accessMode, StorageOpenOptions options)
=> OpenAsync(accessMode);
public override IAsyncOperation<IRandomAccessStreamWithContentType> OpenReadAsync()
{
return AsyncInfo.Run((cancellationToken) => SafetyExtensions.Wrap<IRandomAccessStreamWithContentType>(async () =>
{
if (Path == containerPath)
{
if (backingFile is not null)
{
return await backingFile.OpenReadAsync();
}
var hFile = Win32Helper.OpenFileForRead(containerPath);
return hFile.IsInvalid ? null : new StreamWithContentType(new FileStream(hFile, FileAccess.Read).AsRandomAccessStream());
}
SevenZipExtractor zipFile = await OpenZipFileAsync();
if (zipFile is null || zipFile.ArchiveFileData is null)
{
return null;
}
//zipFile.IsStreamOwner = true;
var entry = zipFile.ArchiveFileData.FirstOrDefault(x => System.IO.Path.Combine(containerPath, x.FileName) == Path);
if (entry.FileName is null)
{
return null;
}
var ms = new MemoryStream();
await zipFile.ExtractFileAsync(entry.Index, ms);
ms.Position = 0;
var nsStream = new NonSeekableRandomAccessStreamForRead(ms, entry.Size)
{
DisposeCallback = () => zipFile.Dispose()
};
return new StreamWithContentType(nsStream);
}, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync));
}
public override IAsyncOperation<IInputStream> OpenSequentialReadAsync()
{
return AsyncInfo.Run((cancellationToken) => SafetyExtensions.Wrap<IInputStream>(async () =>
{
if (Path == containerPath)
{
if (backingFile is not null)
{
return await backingFile.OpenSequentialReadAsync();
}
var hFile = Win32Helper.OpenFileForRead(containerPath);
return hFile.IsInvalid ? null : new FileStream(hFile, FileAccess.Read).AsInputStream();
}
SevenZipExtractor zipFile = await OpenZipFileAsync();
if (zipFile is null || zipFile.ArchiveFileData is null)
{
return null;
}
//zipFile.IsStreamOwner = true;
var entry = zipFile.ArchiveFileData.FirstOrDefault(x => System.IO.Path.Combine(containerPath, x.FileName) == Path);
if (entry.FileName is null)
{
return null;
}
var ms = new MemoryStream();
await zipFile.ExtractFileAsync(entry.Index, ms);
ms.Position = 0;
return new NonSeekableRandomAccessStreamForRead(ms, entry.Size)
{
DisposeCallback = () => zipFile.Dispose()
};
}, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync));
}
public override IAsyncOperation<StorageStreamTransaction> OpenTransactedWriteAsync()
=> throw new NotSupportedException();
public override IAsyncOperation<StorageStreamTransaction> OpenTransactedWriteAsync(StorageOpenOptions options)
=> throw new NotSupportedException();
public override IAsyncOperation<BaseStorageFile> CopyAsync(IStorageFolder destinationFolder)
=> CopyAsync(destinationFolder, Name, NameCollisionOption.FailIfExists);
public override IAsyncOperation<BaseStorageFile> CopyAsync(IStorageFolder destinationFolder, string desiredNewName)
=> CopyAsync(destinationFolder, desiredNewName, NameCollisionOption.FailIfExists);
public override IAsyncOperation<BaseStorageFile> CopyAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option)
{
return AsyncInfo.Run((cancellationToken) => SafetyExtensions.Wrap<BaseStorageFile>(async () =>
{
using SevenZipExtractor zipFile = await OpenZipFileAsync();
if (zipFile is null || zipFile.ArchiveFileData is null)
{
return null;
}
//zipFile.IsStreamOwner = true;
var entry = zipFile.ArchiveFileData.FirstOrDefault(x => System.IO.Path.Combine(containerPath, x.FileName) == Path);
if (entry.FileName is null)
{
return null;
}
var destFolder = destinationFolder.AsBaseStorageFolder();
if (destFolder is ICreateFileWithStream cwsf)
{
var ms = new MemoryStream();
await zipFile.ExtractFileAsync(entry.Index, ms);
ms.Position = 0;
using var inStream = new NonSeekableRandomAccessStreamForRead(ms, entry.Size);
return await cwsf.CreateFileAsync(inStream.AsStreamForRead(), desiredNewName, option.Convert());
}
else
{
var destFile = await destFolder.CreateFileAsync(desiredNewName, option.Convert());
await using var outStream = await destFile.OpenStreamForWriteAsync();
await SafetyExtensions.WrapAsync(() => zipFile.ExtractFileAsync(entry.Index, outStream), async (_, exception) =>
{
await destFile.DeleteAsync();
throw exception;
});
return destFile;
}
}, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync));
}
public override IAsyncAction CopyAndReplaceAsync(IStorageFile fileToReplace)
{
return AsyncInfo.Run((cancellationToken) => SafetyExtensions.WrapAsync(async () =>
{
using SevenZipExtractor zipFile = await OpenZipFileAsync();
if (zipFile is null || zipFile.ArchiveFileData is null)
{
return;
}
//zipFile.IsStreamOwner = true;
var entry = zipFile.ArchiveFileData.FirstOrDefault(x => System.IO.Path.Combine(containerPath, x.FileName) == Path);
if (entry.FileName is null)
{
return;
}
using var hDestFile = fileToReplace.CreateSafeFileHandle(FileAccess.ReadWrite);
await using (var outStream = new FileStream(hDestFile, FileAccess.Write))
{
await zipFile.ExtractFileAsync(entry.Index, outStream);
}
}, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync));
}
public override IAsyncAction MoveAsync(IStorageFolder destinationFolder)
=> throw new NotSupportedException();
public override IAsyncAction MoveAsync(IStorageFolder destinationFolder, string desiredNewName)
=> throw new NotSupportedException();
public override IAsyncAction MoveAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option)
=> throw new NotSupportedException();
public override IAsyncAction MoveAndReplaceAsync(IStorageFile fileToReplace)
=> throw new NotSupportedException();
public override IAsyncAction RenameAsync(string desiredName) => RenameAsync(desiredName, NameCollisionOption.FailIfExists);
public override IAsyncAction RenameAsync(string desiredName, NameCollisionOption option)
{
return AsyncInfo.Run((cancellationToken) => SafetyExtensions.WrapAsync(async () =>
{
if (Path == containerPath)
{
if (backingFile is not null)
{
await backingFile.RenameAsync(desiredName, option);
}
else
{
var fileName = IO.Path.Combine(IO.Path.GetDirectoryName(Path), desiredName);
PInvoke.MoveFileFromApp(Path, fileName);
}
}
else
{
var index = await FetchZipIndex();
if (index < 0)
{
return;
}
using (var ms = new MemoryStream())
{
await using (var archiveStream = await OpenZipFileAsync(FileAccessMode.Read))
{
SevenZipCompressor compressor = new SevenZipCompressor() { CompressionMode = CompressionMode.Append };
compressor.SetFormatFromExistingArchive(archiveStream);
var fileName = IO.Path.GetRelativePath(containerPath, IO.Path.Combine(IO.Path.GetDirectoryName(Path), desiredName));
await compressor.ModifyArchiveAsync(archiveStream, new Dictionary<int, string>() { { index, fileName } }, Credentials.Password, ms);
}
await using (var archiveStream = await OpenZipFileAsync(FileAccessMode.ReadWrite))
{
ms.Position = 0;
await ms.CopyToAsync(archiveStream);
await ms.FlushAsync();
archiveStream.SetLength(archiveStream.Position);
}
}
}
}, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync));
}
public override IAsyncAction DeleteAsync() => DeleteAsync(StorageDeleteOption.Default);
public override IAsyncAction DeleteAsync(StorageDeleteOption option)
{
return AsyncInfo.Run((cancellationToken) => SafetyExtensions.WrapAsync(async () =>
{
if (Path == containerPath)
{
if (backingFile is not null)
{
await backingFile.DeleteAsync();
}
else if (option == StorageDeleteOption.PermanentDelete)
{
PInvoke.DeleteFileFromApp(Path);
}
else
{
throw new NotSupportedException("Moving to recycle bin is not supported.");
}
}
else
{
var index = await FetchZipIndex();
if (index < 0)
{
return;
}
using (var ms = new MemoryStream())
{
await using (var archiveStream = await OpenZipFileAsync(FileAccessMode.Read))
{
SevenZipCompressor compressor = new SevenZipCompressor() { CompressionMode = CompressionMode.Append };
compressor.SetFormatFromExistingArchive(archiveStream);
await compressor.ModifyArchiveAsync(archiveStream, new Dictionary<int, string>() { { index, null } }, Credentials.Password, ms);
}
await using (var archiveStream = await OpenZipFileAsync(FileAccessMode.ReadWrite))
{
ms.Position = 0;
await ms.CopyToAsync(archiveStream);
await ms.FlushAsync();
archiveStream.SetLength(archiveStream.Position);
}
}
}
}, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync));
}
public override IAsyncOperation<StorageItemThumbnail> GetThumbnailAsync(ThumbnailMode mode)
=> Task.FromResult<StorageItemThumbnail>(null).AsAsyncOperation();
public override IAsyncOperation<StorageItemThumbnail> GetThumbnailAsync(ThumbnailMode mode, uint requestedSize)
=> Task.FromResult<StorageItemThumbnail>(null).AsAsyncOperation();
public override IAsyncOperation<StorageItemThumbnail> GetThumbnailAsync(ThumbnailMode mode, uint requestedSize, ThumbnailOptions options)
=> Task.FromResult<StorageItemThumbnail>(null).AsAsyncOperation();
private static bool CheckAccess(string path)
{
try
{
var hFile = Win32Helper.OpenFileForRead(path);
if (hFile.IsInvalid)
{
return false;
}
using (SevenZipExtractor zipFile = new SevenZipExtractor(new FileStream(hFile, FileAccess.Read)))
{
//zipFile.IsStreamOwner = true;
return zipFile.ArchiveFileData is not null;
}
}
catch (SevenZipOpenFailedException ex)
{
return ex.Result == OperationResult.WrongPassword;
}
catch
{
return false;
}
}
private async Task<int> FetchZipIndex()
{
using (SevenZipExtractor zipFile = await OpenZipFileAsync())
{
if (zipFile is null || zipFile.ArchiveFileData is null)
{
return -1;
}
//zipFile.IsStreamOwner = true;
var entry = zipFile.ArchiveFileData.FirstOrDefault(x => System.IO.Path.Combine(containerPath, x.FileName) == Path);
if (entry.FileName is not null)
{
return entry.Index;
}
return -1;
}
}
private async Task<BaseBasicProperties> GetBasicProperties()
{
using SevenZipExtractor zipFile = await OpenZipFileAsync();
if (zipFile is null || zipFile.ArchiveFileData is null)
{
return null;
}
//zipFile.IsStreamOwner = true;
var entry = zipFile.ArchiveFileData.FirstOrDefault(x => System.IO.Path.Combine(containerPath, x.FileName) == Path);
return entry.FileName is null
? new BaseBasicProperties()
: new ZipFileBasicProperties(entry);
}
private IAsyncOperation<SevenZipExtractor> OpenZipFileAsync()
{
return AsyncInfo.Run<SevenZipExtractor>(async (cancellationToken) =>
{
var zipFile = await OpenZipFileAsync(FileAccessMode.Read);
return zipFile is not null ? new SevenZipExtractor(zipFile, Credentials.Password) : null;
});
}
private IAsyncOperation<Stream> OpenZipFileAsync(FileAccessMode accessMode)
{
return AsyncInfo.Run<Stream>(async (cancellationToken) =>
{
bool readWrite = accessMode == FileAccessMode.ReadWrite;
if (backingFile is not null)
{
return (await backingFile.OpenAsync(accessMode)).AsStream();
}
else
{
var hFile = Win32Helper.OpenFileForRead(containerPath, readWrite);
if (hFile.IsInvalid)
{
return null;
}
return new FileStream(hFile, readWrite ? FileAccess.ReadWrite : FileAccess.Read);
}
});
}
private StreamedFileDataRequestedHandler ZipDataStreamingHandler(string name)
{
return async request =>
{
try
{
using SevenZipExtractor zipFile = await OpenZipFileAsync();
if (zipFile is null || zipFile.ArchiveFileData is null)
{
request.FailAndClose(StreamedFileFailureMode.CurrentlyUnavailable);
return;
}
//zipFile.IsStreamOwner = true;
var entry = zipFile.ArchiveFileData.FirstOrDefault(x => System.IO.Path.Combine(containerPath, x.FileName) == name);
if (entry.FileName is null)
{
request.FailAndClose(StreamedFileFailureMode.CurrentlyUnavailable);
}
else
{
await using (var outStream = request.AsStreamForWrite())
{
await zipFile.ExtractFileAsync(entry.Index, outStream);
}
request.Dispose();
}
}
catch
{
request.FailAndClose(StreamedFileFailureMode.Failed);
}
};
}
private sealed class ZipFileBasicProperties : BaseBasicProperties
{
private ArchiveFileInfo entry;
public ZipFileBasicProperties(ArchiveFileInfo entry) => this.entry = entry;
public override DateTimeOffset DateModified => entry.LastWriteTime == DateTime.MinValue ? DateTimeOffset.MinValue : entry.LastWriteTime;
public override DateTimeOffset DateCreated => entry.CreationTime == DateTime.MinValue ? DateTimeOffset.MinValue : entry.CreationTime;
public override ulong Size => entry.Size;
}
}
}