-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Expand file tree
/
Copy pathIOSStorageItem.cs
More file actions
351 lines (299 loc) · 11.3 KB
/
IOSStorageItem.cs
File metadata and controls
351 lines (299 loc) · 11.3 KB
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Avalonia.Logging;
using Avalonia.Platform.Storage;
using Avalonia.Platform.Storage.FileIO;
using Avalonia.Reactive;
using Foundation;
using UIKit;
namespace Avalonia.iOS.Storage;
internal abstract class IOSStorageItem : IStorageBookmarkItem
{
private readonly string _filePath;
protected IOSStorageItem(NSUrl url, NSUrl? securityScopedAncestorUrl = null)
{
Url = url ?? throw new ArgumentNullException(nameof(url));
SecurityScopedAncestorUrl = securityScopedAncestorUrl ?? url;
using (var doc = new UIDocument(url))
{
_filePath = doc.FileUrl?.Path ?? url.FilePathUrl?.Path ?? string.Empty;
Name = doc.LocalizedName
?? System.IO.Path.GetFileName(_filePath)
?? url.FilePathUrl?.LastPathComponent
?? string.Empty;
}
}
public static IStorageItem CreateItem(NSUrl url, NSUrl? securityScopedAncestorUrl = null)
{
return url.HasDirectoryPath ?
new IOSStorageFolder(url, securityScopedAncestorUrl) :
new IOSStorageFile(url, securityScopedAncestorUrl);
}
internal NSUrl Url { get; }
// Calling StartAccessingSecurityScopedResource on items retrieved from, or created in a folder
// fails, because only folders directly opened via StorageProvider.OpenFolderPickerAsync have
// security-scoped NSUrls. This property stores and exposes that ancestor's Url, so we can have
// recursive access to an opened folder.
internal NSUrl SecurityScopedAncestorUrl { get; }
internal string FilePath => _filePath;
public bool CanBookmark => true;
public string Name { get; }
public Uri Path => Url!;
public Task<StorageItemProperties> GetBasicPropertiesAsync()
{
var attributes = NSFileManager.DefaultManager.GetAttributes(_filePath, out var error);
if (error is not null)
{
Logger.TryGet(LogEventLevel.Error, LogArea.IOSPlatform)?.
Log(this, "GetBasicPropertiesAsync returned an error: {ErrorCode} {ErrorMessage}", error.Code, error.LocalizedFailureReason);
}
var properties = attributes is null ?
new StorageItemProperties() :
new StorageItemProperties(
attributes.Size,
attributes.CreationDate is { } creationDate ? (DateTime)creationDate : null,
attributes.ModificationDate is { } modificationDate ? (DateTime)modificationDate : null);
return Task.FromResult(properties);
}
public Task<IStorageFolder?> GetParentAsync()
{
return Task.FromResult<IStorageFolder?>(new IOSStorageFolder(Url.RemoveLastPathComponent(), SecurityScopedAncestorUrl));
}
public Task DeleteAsync()
{
try
{
SecurityScopedAncestorUrl.StartAccessingSecurityScopedResource();
return NSFileManager.DefaultManager.Remove(Url, out var error)
? Task.CompletedTask
: Task.FromException(new NSErrorException(error));
}
finally
{
SecurityScopedAncestorUrl.StopAccessingSecurityScopedResource();
}
}
public Task<IStorageItem?> MoveAsync(IStorageFolder destination)
{
if (destination is not IOSStorageFolder folder)
{
throw new InvalidOperationException("Destination folder must be initialized the StorageProvider API.");
}
try
{
SecurityScopedAncestorUrl.StartAccessingSecurityScopedResource();
folder.SecurityScopedAncestorUrl.StartAccessingSecurityScopedResource();
var isDir = this is IStorageFolder;
var newPath = new NSUrl(System.IO.Path.Combine(folder.FilePath, Name), isDir);
if (NSFileManager.DefaultManager.Move(Url, newPath, out var error))
{
return Task.FromResult<IStorageItem?>(isDir
? new IOSStorageFolder(newPath)
: new IOSStorageFile(newPath));
}
if (error is not null)
{
throw new NSErrorException(error);
}
return Task.FromResult<IStorageItem?>(null);
}
finally
{
SecurityScopedAncestorUrl.StopAccessingSecurityScopedResource();
folder.SecurityScopedAncestorUrl.StopAccessingSecurityScopedResource();
}
}
public Task ReleaseBookmarkAsync()
{
// no-op
return Task.CompletedTask;
}
public unsafe Task<string?> SaveBookmarkAsync()
{
try
{
if (!SecurityScopedAncestorUrl.StartAccessingSecurityScopedResource())
{
return Task.FromResult<string?>(null);
}
using var newBookmark = Url.CreateBookmarkData(NSUrlBookmarkCreationOptions.SuitableForBookmarkFile, [], null, out var bookmarkError);
if (bookmarkError is not null)
{
Logger.TryGet(LogEventLevel.Error, LogArea.IOSPlatform)?.
Log(this, "SaveBookmark returned an error: {ErrorCode} {ErrorMessage}", bookmarkError.Code, bookmarkError.LocalizedFailureReason);
return Task.FromResult<string?>(null);
}
var bytes = new Span<byte>((void*)newBookmark.Bytes, (int)newBookmark.Length);
return Task.FromResult<string?>(
StorageBookmarkHelper.EncodeBookmark(IOSStorageProvider.PlatformKey, bytes));
}
finally
{
SecurityScopedAncestorUrl.StopAccessingSecurityScopedResource();
}
}
public void Dispose()
{
}
}
internal sealed class IOSStorageFile : IOSStorageItem, IStorageBookmarkFile
{
public IOSStorageFile(NSUrl url, NSUrl? securityScopedAncestorUrl = null) : base(url, securityScopedAncestorUrl)
{
}
public Task<Stream> OpenReadAsync()
{
return Task.FromResult(CreateStream(FileMode.Open, FileAccess.Read));
}
public Task<Stream> OpenWriteAsync()
{
return Task.FromResult(CreateStream(FileMode.Create, FileAccess.Write));
}
private Stream CreateStream(FileMode fileMode, FileAccess fileAccess)
{
using var document = new UIDocument(Url);
var path = document.FileUrl.Path!;
var scopeCreated = SecurityScopedAncestorUrl.StartAccessingSecurityScopedResource();
FileStream stream;
try
{
stream = new FileStream(path, fileMode, fileAccess);
}
catch
{
if (scopeCreated)
SecurityScopedAncestorUrl.StopAccessingSecurityScopedResource();
throw;
}
return scopeCreated ?
new SecurityScopedStream(stream, Disposable.Create(() =>
{
SecurityScopedAncestorUrl.StopAccessingSecurityScopedResource();
})) :
stream;
}
}
internal sealed class IOSStorageFolder : IOSStorageItem, IStorageBookmarkFolder
{
public IOSStorageFolder(NSUrl url, NSUrl? securityScopedAncestorUrl = null) : base(url, securityScopedAncestorUrl)
{
}
public IOSStorageFolder(NSUrl url, WellKnownFolder wellKnownFolder) : base(url, null)
{
WellKnownFolder = wellKnownFolder;
}
public WellKnownFolder? WellKnownFolder { get; }
public async IAsyncEnumerable<IStorageItem> GetItemsAsync()
{
try
{
SecurityScopedAncestorUrl.StartAccessingSecurityScopedResource();
// TODO: find out if it can be lazily enumerated.
var tcs = new TaskCompletionSource<IReadOnlyList<IStorageItem>>();
new NSFileCoordinator().CoordinateRead(Url,
NSFileCoordinatorReadingOptions.WithoutChanges,
out var error,
uri =>
{
var content = NSFileManager.DefaultManager.GetDirectoryContent(uri, null, NSDirectoryEnumerationOptions.None, out var error);
if (error is not null)
{
tcs.TrySetException(new NSErrorException(error));
}
else
{
var items = content
.Select(u => CreateItem(u, SecurityScopedAncestorUrl))
.ToArray();
tcs.TrySetResult(items);
}
});
if (error is not null)
{
throw new NSErrorException(error);
}
var items = await tcs.Task;
foreach (var item in items)
{
yield return item;
}
}
finally
{
SecurityScopedAncestorUrl.StopAccessingSecurityScopedResource();
}
}
public Task<IStorageFile?> CreateFileAsync(string name)
{
try
{
if (!SecurityScopedAncestorUrl.StartAccessingSecurityScopedResource())
{
return Task.FromResult<IStorageFile?>(null);
}
var path = System.IO.Path.Combine(FilePath, name);
NSFileAttributes? attributes = null;
if (NSFileManager.DefaultManager.CreateFile(path, new NSData(), attributes))
{
return Task.FromResult<IStorageFile?>(new IOSStorageFile(new NSUrl(path, false), SecurityScopedAncestorUrl));
}
return Task.FromResult<IStorageFile?>(null);
}
finally
{
SecurityScopedAncestorUrl.StopAccessingSecurityScopedResource();
}
}
public Task<IStorageFolder?> CreateFolderAsync(string name)
{
try
{
SecurityScopedAncestorUrl.StartAccessingSecurityScopedResource();
var path = System.IO.Path.Combine(FilePath, name);
NSFileAttributes? attributes = null;
if (NSFileManager.DefaultManager.CreateDirectory(path, true, attributes, out var error))
{
return Task.FromResult<IStorageFolder?>(new IOSStorageFolder(new NSUrl(path, true), SecurityScopedAncestorUrl));
}
if (error is not null)
{
throw new NSErrorException(error);
}
return Task.FromResult<IStorageFolder?>(null);
}
finally
{
SecurityScopedAncestorUrl.StopAccessingSecurityScopedResource();
}
}
private NSUrl? GetItem(string name, bool isDirectory)
{
try
{
SecurityScopedAncestorUrl.StartAccessingSecurityScopedResource();
var path = System.IO.Path.Combine(FilePath, name);
if (NSFileManager.DefaultManager.FileExists(path, ref isDirectory))
{
return new NSUrl(path, isDirectory);
}
return null;
}
finally
{
SecurityScopedAncestorUrl.StopAccessingSecurityScopedResource();
}
}
public Task<IStorageFolder?> GetFolderAsync(string name)
{
var url = GetItem(name, true);
return Task.FromResult<IStorageFolder?>(url is null ? null : new IOSStorageFolder(url));
}
public Task<IStorageFile?> GetFileAsync(string name)
{
var url = GetItem(name, false);
return Task.FromResult<IStorageFile?>(url is null ? null : new IOSStorageFile(url));
}
}