-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathItem+Create.swift
More file actions
659 lines (601 loc) · 25.9 KB
/
Item+Create.swift
File metadata and controls
659 lines (601 loc) · 25.9 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
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
// SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
// SPDX-License-Identifier: LGPL-3.0-or-later
@preconcurrency import FileProvider
import Foundation
import NextcloudCapabilitiesKit
import NextcloudKit
public extension Item {
///
/// Create a new folder on the server.
///
private static func createNewFolder(
itemTemplate: NSFileProviderItem?,
remotePath: String,
parentItemIdentifier: NSFileProviderItemIdentifier,
domain: NSFileProviderDomain? = nil,
account: Account,
remoteInterface: RemoteInterface,
progress _: Progress,
dbManager: FilesDatabaseManager,
log: any FileProviderLogging
) async -> (Item?, Error?) {
let logger = FileProviderLogger(category: "Item", log: log)
let (_, _, _, createError) = await remoteInterface.createFolder(
remotePath: remotePath, account: account, options: .init(), taskHandler: { task in
if let domain, let itemTemplate {
NSFileProviderManager(for: domain)?.register(
task,
forItemWithIdentifier: itemTemplate.itemIdentifier,
completionHandler: { _ in }
)
}
}
)
guard createError == .success else {
logger.error(
"""
Could not create new folder at: \(remotePath),
received error: \(createError.errorCode)
\(createError.errorDescription)
"""
)
return await (nil, createError.fileProviderError(
handlingCollisionAgainstItemInRemotePath: remotePath,
dbManager: dbManager,
remoteInterface: remoteInterface,
log: log
))
}
// Read contents after creation
let (_, files, _, readError) = await remoteInterface.enumerate(
remotePath: remotePath,
depth: .target,
showHiddenFiles: true,
includeHiddenFiles: [],
requestBody: nil,
account: account,
options: .init(),
taskHandler: { task in
if let domain, let itemTemplate {
NSFileProviderManager(for: domain)?.register(
task,
forItemWithIdentifier: itemTemplate.itemIdentifier,
completionHandler: { _ in }
)
}
}
)
guard readError == .success else {
logger.error(
"""
Could not read new folder at: \(remotePath),
received error: \(readError.errorCode)
\(readError.errorDescription)
"""
)
return await (nil, readError.fileProviderError(
handlingCollisionAgainstItemInRemotePath: remotePath,
dbManager: dbManager,
remoteInterface: remoteInterface,
log: log
))
}
guard var (directory, _, _) = await files.toSendableDirectoryMetadata(account: account, directoryToRead: remotePath) else {
logger.error("Failed to resolve directory metadata on item conversion!")
return (nil, NSFileProviderError(.cannotSynchronize))
}
directory.downloaded = true
dbManager.addItemMetadata(directory)
let fpItem = await Item(
metadata: directory,
parentItemIdentifier: parentItemIdentifier,
account: account,
remoteInterface: remoteInterface,
dbManager: dbManager,
remoteSupportsTrash: remoteInterface.supportsTrash(account: account),
log: log
)
return (fpItem, nil)
}
private static func createNewFile(
remotePath: String,
localPath: String,
itemTemplate: NSFileProviderItem,
parentItemRemotePath: String,
domain: NSFileProviderDomain? = nil,
account: Account,
remoteInterface: RemoteInterface,
forcedChunkSize: Int?,
progress: Progress,
dbManager: FilesDatabaseManager,
log: any FileProviderLogging
) async -> (Item?, Error?) {
let logger = FileProviderLogger(category: "Item", log: log)
let chunkUploadId =
itemTemplate.itemIdentifier.rawValue.replacingOccurrences(of: "/", with: "")
let (ocId, _, etag, date, size, error) = await upload(
fileLocatedAt: localPath,
toRemotePath: remotePath,
usingRemoteInterface: remoteInterface,
withAccount: account,
inChunksSized: forcedChunkSize,
usingChunkUploadId: chunkUploadId,
dbManager: dbManager,
creationDate: itemTemplate.creationDate as? Date,
modificationDate: itemTemplate.contentModificationDate as? Date,
log: log,
requestHandler: { progress.setHandlersFromAfRequest($0) },
taskHandler: { task in
if let domain {
NSFileProviderManager(for: domain)?.register(
task,
forItemWithIdentifier: itemTemplate.itemIdentifier,
completionHandler: { _ in }
)
}
},
progressHandler: { $0.copyCurrentStateToProgress(progress) }
)
guard error == .success, let ocId else {
logger.error(
"""
Could not upload item with filename: \(itemTemplate.filename),
received error: \(error.errorCode)
\(error.errorDescription)
received ocId: \(ocId ?? "empty")
"""
)
return await (nil, error.fileProviderError(
handlingCollisionAgainstItemInRemotePath: remotePath,
dbManager: dbManager,
remoteInterface: remoteInterface,
log: log
))
}
logger.info(
"""
Successfully uploaded item with identifier: \(ocId)
filename: \(itemTemplate.filename)
ocId: \(ocId)
etag: \(etag ?? "")
date: \(date ?? Date())
size: \(Int(size ?? -1)),
account: \(account.ncKitAccount)
"""
)
if let expectedSize = itemTemplate.documentSize??.int64Value, size != expectedSize {
logger.info(
"""
Created item upload reported as successful, but there are differences between
the received file size (\(Int(size ?? -1)))
and the original file size (\(itemTemplate.documentSize??.int64Value ?? 0))
"""
)
}
let newMetadata = SendableItemMetadata(
ocId: ocId,
account: account.ncKitAccount,
classFile: "", // Placeholder as not set in original code
contentType: itemTemplate.contentType?.preferredMIMEType ?? "",
creationDate: Date(), // Default as not set in original code
date: date ?? Date(),
directory: false,
e2eEncrypted: false, // Default as not set in original code
etag: etag ?? "",
fileId: "", // Placeholder as not set in original code
fileName: itemTemplate.filename,
fileNameView: itemTemplate.filename,
hasPreview: false, // Default as not set in original code
iconName: "", // Placeholder as not set in original code
mountType: "", // Placeholder as not set in original code
ownerId: "", // Placeholder as not set in original code
ownerDisplayName: "", // Placeholder as not set in original code
path: "", // Placeholder as not set in original code
serverUrl: parentItemRemotePath,
size: size ?? 0,
status: Status.normal.rawValue,
downloaded: true,
uploaded: true,
urlBase: account.serverUrl,
user: account.username,
userId: account.id,
wasTrashedLocally: false
)
dbManager.addItemMetadata(newMetadata)
let fpItem = await Item(
metadata: newMetadata,
parentItemIdentifier: itemTemplate.parentItemIdentifier,
account: account,
remoteInterface: remoteInterface,
dbManager: dbManager,
remoteSupportsTrash: remoteInterface.supportsTrash(account: account),
log: log
)
return (fpItem, nil)
}
@discardableResult private static func createBundleOrPackageInternals(
rootItem: Item,
contents: URL,
remotePath: String,
domain: NSFileProviderDomain? = nil,
account: Account,
remoteInterface: RemoteInterface,
forcedChunkSize: Int?,
progress: Progress,
dbManager: FilesDatabaseManager,
log: any FileProviderLogging
) async throws -> Item? {
let logger = FileProviderLogger(category: "Item", log: log)
logger.debug(
"""
Handling new bundle/package/internal directory at: \(contents.path)
"""
)
let attributesToFetch: Set<URLResourceKey> = [
.isDirectoryKey, .fileSizeKey, .creationDateKey, .contentModificationDateKey
]
let fm = FileManager.default
guard let enumerator = fm.enumerator(
at: contents, includingPropertiesForKeys: Array(attributesToFetch)
) else {
logger.error(
"""
Could not create enumerator for contents of bundle or package
at: \(contents.path)
"""
)
throw NSError(domain: NSURLErrorDomain, code: NSURLErrorResourceUnavailable)
}
guard let enumeratorArray = enumerator.allObjects as? [URL] else {
logger.error(
"""
Could not create enumerator array for contents of bundle or package
at: \(contents.path)
"""
)
throw NSError(domain: NSURLErrorDomain, code: NSURLErrorResourceUnavailable)
}
func remoteErrorToThrow(_ error: NKError) -> Error {
error.fileProviderError ?? NSFileProviderError(.cannotSynchronize)
}
let contentsPath = contents.path
let privatePrefix = "/private"
let privateContentsPath = contentsPath.hasPrefix(privatePrefix)
var remoteDirectoriesPaths = [remotePath]
// Add one more total unit count to signify final reconciliation of bundle creation process
progress.totalUnitCount = Int64(enumeratorArray.count) + 1
for childUrl in enumeratorArray {
var childUrlPath = childUrl.path
if childUrlPath.hasPrefix(privatePrefix), !privateContentsPath {
childUrlPath.removeFirst(privatePrefix.count)
}
let childRelativePath = childUrlPath.replacingOccurrences(of: contents.path, with: "")
let childRemoteUrl = remotePath + childRelativePath
let childUrlAttributes = try childUrl.resourceValues(forKeys: attributesToFetch)
if childUrlAttributes.isDirectory ?? false {
logger.debug(
"""
Handling child bundle or package directory at: \(childUrlPath)
"""
)
let (_, _, _, createError) = await remoteInterface.createFolder(
remotePath: childRemoteUrl,
account: account,
options: .init(), taskHandler: { task in
if let domain {
NSFileProviderManager(for: domain)?.register(
task,
forItemWithIdentifier: rootItem.itemIdentifier,
completionHandler: { _ in }
)
}
}
)
// As with the creating of the bundle's root folder, we do not want to abort on fail
// as we might have faced an error creating some other internal content and we want
// to retry all of its contents
guard createError == .success || createError.matchesCollisionError else {
logger.error(
"""
Could not create new bpi folder at: \(remotePath),
received error: \(createError.errorCode)
\(createError.errorDescription)
"""
)
throw remoteErrorToThrow(createError)
}
remoteDirectoriesPaths.append(childRemoteUrl)
} else {
logger.debug(
"""
Handling child bundle or package file at: \(childUrlPath)
"""
)
let (_, _, _, _, _, error) = await upload(
fileLocatedAt: childUrlPath,
toRemotePath: childRemoteUrl,
usingRemoteInterface: remoteInterface,
withAccount: account,
inChunksSized: forcedChunkSize,
dbManager: dbManager,
creationDate: childUrlAttributes.creationDate,
modificationDate: childUrlAttributes.contentModificationDate,
log: log,
requestHandler: { progress.setHandlersFromAfRequest($0) },
taskHandler: { task in
if let domain {
NSFileProviderManager(for: domain)?.register(
task,
forItemWithIdentifier: rootItem.itemIdentifier,
completionHandler: { _ in }
)
}
},
progressHandler: { _ in }
)
// Do not fail on existing item, just keep going
guard error == .success || error.matchesCollisionError else {
logger.error(
"""
Could not upload bpi file at: \(childUrlPath),
received error: \(error.errorCode)
\(error.errorDescription)
"""
)
throw remoteErrorToThrow(error)
}
}
progress.completedUnitCount += 1
}
for remoteDirectoryPath in remoteDirectoriesPaths {
// After everything, check into what the final state is of each folder now
logger.debug("Reading bpi folder at: \(remoteDirectoryPath)")
let (_, _, _, _, _, readError) = await Enumerator.readServerUrl(
remoteDirectoryPath,
account: account,
remoteInterface: remoteInterface,
dbManager: dbManager,
log: log
)
if let readError, readError != .success {
logger.error(
"""
Could not read bpi folder at: \(remotePath),
received error: \(readError.errorDescription)
"""
)
throw remoteErrorToThrow(readError)
}
}
guard let bundleRootMetadata = dbManager.itemMetadata(
account: account.ncKitAccount, locatedAtRemoteUrl: remotePath
) else {
logger.error(
"""
Could not find directory metadata for bundle or package at:
\(remotePath)
of account:
\(account.ncKitAccount)
with contents located at:
\(contentsPath)
"""
)
// Yes, it's weird to throw a "non-existent item" error during an item's creation.
// No, it's not the wrong solution. Thanks to the peculiar way we have to handle bundles
// things can happen as we are populating the bundle remotely and then checking it.
throw NSError.fileProviderErrorForNonExistentItem(
withIdentifier: rootItem.itemIdentifier
)
}
progress.completedUnitCount += 1
return await Item(
metadata: bundleRootMetadata,
parentItemIdentifier: rootItem.parentItemIdentifier,
account: account,
remoteInterface: remoteInterface,
dbManager: dbManager,
remoteSupportsTrash: remoteInterface.supportsTrash(account: account),
log: log
)
}
static func create(
basedOn itemTemplate: NSFileProviderItem,
fields _: NSFileProviderItemFields = NSFileProviderItemFields(),
contents url: URL?,
options: NSFileProviderCreateItemOptions = [],
request _: NSFileProviderRequest = NSFileProviderRequest(),
domain: NSFileProviderDomain? = nil,
account: Account,
remoteInterface: RemoteInterface,
ignoredFiles: IgnoredFilesMatcher? = nil,
forcedChunkSize: Int? = nil,
progress: Progress,
dbManager: FilesDatabaseManager,
log: any FileProviderLogging
) async -> (Item?, Error?) {
let logger = FileProviderLogger(category: "Item", log: log)
let tempId = itemTemplate.itemIdentifier.rawValue
guard itemTemplate.contentType != .symbolicLink else {
logger.error(
"Cannot create item \(tempId), symbolic links not supported."
)
return (nil, NSError(domain: NSCocoaErrorDomain, code: NSFeatureUnsupportedError))
}
if options.contains(.mayAlreadyExist) {
// TODO: This needs to be properly handled with a check in the db
logger.info(
"""
Not creating item: \(itemTemplate.itemIdentifier.rawValue)
as it may already exist
"""
)
return (nil, NSFileProviderError(.cannotSynchronize))
}
let parentItemIdentifier = itemTemplate.parentItemIdentifier
var parentItemRemotePath: String
var parentItemRelativePath: String
// TODO: Deduplicate
if parentItemIdentifier == .rootContainer {
parentItemRemotePath = account.davFilesUrl
parentItemRelativePath = "/"
} else {
guard let parentItemMetadata = dbManager.directoryMetadata(
ocId: parentItemIdentifier.rawValue
) else {
logger.error(
"""
Not creating item: \(itemTemplate.itemIdentifier.rawValue),
could not find metadata for parentItemIdentifier:
\(parentItemIdentifier.rawValue)
"""
)
return (nil, NSFileProviderError(.cannotSynchronize))
}
parentItemRemotePath = parentItemMetadata.remotePath()
parentItemRelativePath = parentItemRemotePath.replacingOccurrences(
of: account.davFilesUrl, with: ""
)
assert(parentItemRelativePath.starts(with: "/"))
}
let itemTemplateIsFolder = itemTemplate.contentType?.conforms(to: .directory) ?? false
guard !isLockFileName(itemTemplate.filename) || itemTemplateIsFolder else {
return await Item.createLockFile(
basedOn: itemTemplate,
parentItemIdentifier: parentItemIdentifier,
parentItemRemotePath: parentItemRemotePath,
progress: progress,
domain: domain,
account: account,
remoteInterface: remoteInterface,
dbManager: dbManager,
log: log
)
}
let relativePath = parentItemRelativePath + "/" + itemTemplate.filename
guard ignoredFiles == nil || ignoredFiles?.isExcluded(relativePath) == false else {
return await Item.createIgnored(
basedOn: itemTemplate,
parentItemRemotePath: parentItemRemotePath,
contents: url,
account: account,
remoteInterface: remoteInterface,
progress: progress,
dbManager: dbManager,
log: log
)
}
let fileNameLocalPath = url?.path ?? ""
let newServerUrlFileName = parentItemRemotePath + "/" + itemTemplate.filename
logger.debug(
"""
About to upload item with identifier: \(tempId)
of type: \(itemTemplate.contentType?.identifier ?? "UNKNOWN")
(is folder: \(itemTemplateIsFolder ? "yes" : "no")
and filename: \(itemTemplate.filename)
to server url: \(newServerUrlFileName)
with contents located at: \(fileNameLocalPath)
"""
)
guard !itemTemplateIsFolder else {
let isBundleOrPackage =
itemTemplate.contentType?.conforms(to: .bundle) == true ||
itemTemplate.contentType?.conforms(to: .package) == true
var (item, error) = await Self.createNewFolder(
itemTemplate: itemTemplate,
remotePath: newServerUrlFileName,
parentItemIdentifier: parentItemIdentifier,
domain: domain,
account: account,
remoteInterface: remoteInterface,
progress: isBundleOrPackage ? Progress() : progress,
dbManager: dbManager,
log: log
)
guard isBundleOrPackage else {
return (item, error)
}
// Ignore collision errors as we might have faced an error creating one of the bundle's
// internal files or folders and we want to retry all of its contents
let fpErrorCode = (error as? NSFileProviderError)?.code
guard error == nil || fpErrorCode == .filenameCollision else {
logger.error("Could not create item.", [.item: item?.itemIdentifier, .error: error])
return (item, error)
}
if item == nil {
logger.debug("Item is a bundle or package whose root folder already exists, ignoring errors. Fetching remote information, proceeding with creation of internal contents.")
let (metadatas, _, _, _, _, readError) = await Enumerator.readServerUrl(
newServerUrlFileName,
account: account,
remoteInterface: remoteInterface,
dbManager: dbManager,
domain: domain,
depth: .target,
log: log
)
if let readError, readError != .success {
logger.error("Could not read existing bundle or package folder.", [.error: readError, .url: newServerUrlFileName])
return (nil, readError.fileProviderError)
}
guard let itemMetadata = metadatas?.first else {
logger.error("Could not create item for remotely-existing bundle or package. This should not happen.", [.item: tempId])
return (
nil,
NSError.fileProviderErrorForNonExistentItem(
withIdentifier: itemTemplate.itemIdentifier
)
)
}
item = await Item(
metadata: itemMetadata,
parentItemIdentifier: parentItemIdentifier,
account: account,
remoteInterface: remoteInterface,
dbManager: dbManager,
remoteSupportsTrash: remoteInterface.supportsTrash(account: account),
log: log
)
}
guard let item else {
logger.error("Could not create item for remotely-existing bundle or package as item is null. This should not happen!", [.item: tempId])
return (nil, NSFileProviderError(.cannotSynchronize))
}
guard let url else {
logger.error("Could not create item as it is a bundle or package and no contents were provided.", [.item: tempId])
return (nil, NSError(domain: NSURLErrorDomain, code: NSURLErrorBadURL))
}
// Bundles and packages are given to us as if they were files -- i.e. we don't get
// notified about internal changes. So we need to manually handle their internal
// contents
logger.debug("Handling bundle or package contents for item.", [.item: tempId])
do {
return try await (Self.createBundleOrPackageInternals(
rootItem: item,
contents: url,
remotePath: newServerUrlFileName,
domain: domain,
account: account,
remoteInterface: remoteInterface,
forcedChunkSize: forcedChunkSize,
progress: progress,
dbManager: dbManager,
log: log
), nil)
} catch {
return (nil, error)
}
}
return await Self.createNewFile(
remotePath: newServerUrlFileName,
localPath: fileNameLocalPath,
itemTemplate: itemTemplate,
parentItemRemotePath: parentItemRemotePath,
domain: domain,
account: account,
remoteInterface: remoteInterface,
forcedChunkSize: forcedChunkSize,
progress: progress,
dbManager: dbManager,
log: log
)
}
}