-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathEnumerator.swift
More file actions
810 lines (738 loc) · 33.3 KB
/
Enumerator.swift
File metadata and controls
810 lines (738 loc) · 33.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
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
/*
* Copyright (C) 2022 by Claudio Cambra <claudio.cambra@nextcloud.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*/
import FileProvider
import NextcloudKit
import OSLog
public class Enumerator: NSObject, NSFileProviderEnumerator {
let enumeratedItemIdentifier: NSFileProviderItemIdentifier
private var enumeratedItemMetadata: SendableItemMetadata?
private var enumeratingSystemIdentifier: Bool {
Self.isSystemIdentifier(enumeratedItemIdentifier)
}
let domain: NSFileProviderDomain?
let dbManager: FilesDatabaseManager
// TODO: actually use this in NCKit and server requests
private let anchor = NSFileProviderSyncAnchor(Date().description.data(using: .utf8)!)
private static let maxItemsPerFileProviderPage = 100
static let logger = Logger(subsystem: Logger.subsystem, category: "enumerator")
let account: Account
let remoteInterface: RemoteInterface
let fastEnumeration: Bool
var serverUrl: String = ""
var isInvalidated = false
weak var listener: EnumerationListener?
private static func isSystemIdentifier(_ identifier: NSFileProviderItemIdentifier) -> Bool {
identifier == .rootContainer || identifier == .trashContainer || identifier == .workingSet
}
public init(
enumeratedItemIdentifier: NSFileProviderItemIdentifier,
account: Account,
remoteInterface: RemoteInterface,
dbManager: FilesDatabaseManager,
domain: NSFileProviderDomain? = nil,
fastEnumeration: Bool = true,
listener: EnumerationListener? = nil
) {
self.enumeratedItemIdentifier = enumeratedItemIdentifier
self.remoteInterface = remoteInterface
self.account = account
self.dbManager = dbManager
self.domain = domain
self.fastEnumeration = fastEnumeration
self.listener = listener
if Self.isSystemIdentifier(enumeratedItemIdentifier) {
Self.logger.debug(
"""
Providing enumerator for a system defined container:
\(enumeratedItemIdentifier.rawValue, privacy: .public)
"""
)
serverUrl = account.davFilesUrl
} else {
Self.logger.debug(
"""
Providing enumerator for item with identifier:
\(enumeratedItemIdentifier.rawValue, privacy: .public)
"""
)
enumeratedItemMetadata = dbManager.itemMetadataFromFileProviderItemIdentifier(
enumeratedItemIdentifier)
if let enumeratedItemMetadata {
serverUrl =
enumeratedItemMetadata.serverUrl + "/" + enumeratedItemMetadata.fileName
} else {
Self.logger.error(
"""
Could not find itemMetadata for file with identifier:
\(enumeratedItemIdentifier.rawValue, privacy: .public)
"""
)
}
}
Self.logger.info(
"""
Set up enumerator for user: \(self.account.ncKitAccount, privacy: .public)
with serverUrl: \(self.serverUrl, privacy: .public)
"""
)
super.init()
}
public func invalidate() {
Self.logger.debug(
"""
Enumerator is being invalidated for item with identifier:
\(self.enumeratedItemIdentifier.rawValue, privacy: .public)
"""
)
isInvalidated = true
}
// MARK: - Protocol methods
public func enumerateItems(
for observer: NSFileProviderEnumerationObserver, startingAt page: NSFileProviderPage
) {
let actionId = UUID()
listener?.enumerationActionStarted(actionId: actionId)
Self.logger.debug(
"""
Received enumerate items request for enumerator with user:
\(self.account.ncKitAccount, privacy: .public)
with serverUrl: \(self.serverUrl, privacy: .public)
"""
)
/*
- inspect the page to determine whether this is an initial or a follow-up request (TODO)
If this is an enumerator for a directory, the root container or all directories:
- perform a server request to fetch directory contents
If this is an enumerator for the working set:
- perform a server request to update your local database
- fetch the working set from your local database
- inform the observer about the items returned by the server (possibly multiple times)
- inform the observer that you are finished with this page
*/
if enumeratedItemIdentifier == .trashContainer {
Self.logger.debug(
"""
Enumerating trash set for user: \(self.account.ncKitAccount, privacy: .public)
with serverUrl: \(self.serverUrl, privacy: .public)
"""
)
Task {
let (_, capabilities, _, error) = await remoteInterface.currentCapabilities(
account: account, options: .init(), taskHandler: { _ in }
)
guard let capabilities, error == .success else {
Self.logger.error(
"""
Could not acquire capabilities, cannot check trash.
Error: \(error.errorDescription, privacy: .public)
""")
observer.finishEnumeratingWithError(NSFileProviderError(.serverUnreachable))
return
}
guard capabilities.files?.undelete == true else {
Self.logger.error("Trash is unsupported on server, cannot enumerate items.")
observer.finishEnumeratingWithError(
NSError(domain: NSCocoaErrorDomain, code: NSFeatureUnsupportedError)
)
return
}
let (_, trashedItems, _, trashReadError) = await remoteInterface.trashedItems(
account: account,
options: .init(),
taskHandler: { task in
if let domain = self.domain {
NSFileProviderManager(for: domain)?.register(
task,
forItemWithIdentifier: self.enumeratedItemIdentifier,
completionHandler: { _ in }
)
}
}
)
guard trashReadError == .success else {
let error = trashReadError.fileProviderError(
handlingNoSuchItemErrorUsingItemIdentifier: self.enumeratedItemIdentifier
) ?? NSFileProviderError(.cannotSynchronize)
listener?.enumerationActionFailed(actionId: actionId, error: error)
observer.finishEnumeratingWithError(error)
return
}
Self.completeEnumerationObserver(
observer,
account: account,
remoteInterface: remoteInterface,
dbManager: dbManager,
numPage: 1,
trashItems: trashedItems
)
listener?.enumerationActionFinished(actionId: actionId)
}
return
}
// Handle the working set as if it were the root container
// If we do a full server scan per the recommendations of the File Provider documentation,
// we will be stuck for a huge period of time without being able to access files as the
// entire server gets scanned. Instead, treat the working set as the root container here.
// Then, when we enumerate changes, we'll go through everything -- while we can still
// navigate a little bit in Finder, file picker, etc
guard serverUrl != "" else {
Self.logger.error(
"""
Enumerator has empty serverUrl -- can't enumerate that!
For identifier: \(self.enumeratedItemIdentifier.rawValue, privacy: .public)
"""
)
let error = NSError.fileProviderErrorForNonExistentItem(
withIdentifier: self.enumeratedItemIdentifier
)
listener?.enumerationActionFailed(actionId: actionId, error: error)
observer.finishEnumeratingWithError(error)
return
}
// TODO: Make better use of pagination and handle paging properly
if page == NSFileProviderPage.initialPageSortedByDate as NSFileProviderPage
|| page == NSFileProviderPage.initialPageSortedByName as NSFileProviderPage
{
Self.logger.debug(
"""
Enumerating initial page for user: \(self.account.ncKitAccount, privacy: .public)
with serverUrl: \(self.serverUrl, privacy: .public)
"""
)
Task {
let (metadatas, _, _, _, readError) = await Self.readServerUrl(
serverUrl,
account: account,
remoteInterface: remoteInterface,
dbManager: dbManager
)
guard readError == nil else {
Self.logger.error(
"""
"Finishing enumeration for: \(self.account.ncKitAccount, privacy: .public)
with serverUrl: \(self.serverUrl, privacy: .public)
with error \(readError!.errorDescription, privacy: .public)
"""
)
// TODO: Refactor for conciseness
let error = readError?.fileProviderError(
handlingNoSuchItemErrorUsingItemIdentifier: self.enumeratedItemIdentifier
) ?? NSFileProviderError(.cannotSynchronize)
listener?.enumerationActionFailed(actionId: actionId, error: error)
observer.finishEnumeratingWithError(error)
return
}
guard let metadatas else {
Self.logger.error(
"""
Finishing enumeration for: \(self.account.ncKitAccount, privacy: .public)
with serverUrl: \(self.serverUrl, privacy: .public)
with invalid metadatas.
"""
)
listener?.enumerationActionFailed(
actionId: actionId, error: NSFileProviderError(.cannotSynchronize)
)
observer.finishEnumeratingWithError(NSFileProviderError(.cannotSynchronize))
return
}
Self.logger.info(
"""
Finished reading serverUrl: \(self.serverUrl, privacy: .public)
for user: \(self.account.ncKitAccount, privacy: .public).
Processed \(metadatas.count) metadatas
"""
)
Self.completeEnumerationObserver(
observer,
account: account,
remoteInterface: remoteInterface,
dbManager: dbManager,
numPage: 1,
itemMetadatas: metadatas
)
listener?.enumerationActionFinished(actionId: actionId)
}
return
}
let numPage = Int(String(data: page.rawValue, encoding: .utf8)!)!
Self.logger.debug(
"""
Enumerating page \(numPage, privacy: .public)
for user: \(self.account.ncKitAccount, privacy: .public)
with serverUrl: \(self.serverUrl, privacy: .public)
"""
)
// TODO: Handle paging properly
// Self.completeObserver(observer, ncKit: ncKit, numPage: numPage, itemMetadatas: nil)
listener?.enumerationActionFinished(actionId: actionId)
observer.finishEnumerating(upTo: nil)
}
public func enumerateChanges(
for observer: NSFileProviderChangeObserver, from anchor: NSFileProviderSyncAnchor
) {
let actionId = UUID()
listener?.enumerationActionStarted(actionId: actionId)
Self.logger.debug(
"""
Received enumerate changes request for enumerator for user:
\(self.account.ncKitAccount, privacy: .public)
with serverUrl: \(self.serverUrl, privacy: .public)
"""
)
/*
- query the server for updates since the passed-in sync anchor (TODO)
If this is an enumerator for the working set:
- note the changes in your local database
- inform the observer about item deletions and updates (modifications + insertions)
- inform the observer when you have finished enumerating up to a subsequent sync anchor
*/
if enumeratedItemIdentifier == .workingSet {
Self.logger.debug(
"Enumerating changes in working set for: \(self.account.ncKitAccount, privacy: .public)"
)
// Unlike when enumerating items we can't progressively enumerate items as we need to
// wait to see which items are truly deleted and which have just been moved elsewhere.
Task {
let (
_, newMetadatas, updatedMetadatas, deletedMetadatas, error
) = await fullRecursiveScan(
account: account,
remoteInterface: remoteInterface,
dbManager: dbManager,
scanChangesOnly: true
)
if self.isInvalidated {
Self.logger.info(
"""
Enumerator invalidated during working set change scan.
For user: \(self.account.ncKitAccount, privacy: .public)
"""
)
listener?.enumerationActionFailed(
actionId: actionId, error: NSFileProviderError(.cannotSynchronize)
)
observer.finishEnumeratingWithError(NSFileProviderError(.cannotSynchronize))
return
}
guard error == nil else {
Self.logger.info(
"""
Finished recursive change enumeration of working set for user:
\(self.account.ncKitAccount, privacy: .public)
with error: \(error!.errorDescription, privacy: .public)
"""
)
// TODO: Refactor for conciseness
let fpError = error?.fileProviderError(
handlingNoSuchItemErrorUsingItemIdentifier: self.enumeratedItemIdentifier
) ?? NSFileProviderError(.cannotSynchronize)
listener?.enumerationActionFailed(actionId: actionId, error: fpError)
observer.finishEnumeratingWithError(fpError)
return
}
Self.logger.info(
"""
Finished recursive change enumeration of working set for user:
\(self.account.ncKitAccount, privacy: .public). Enumerating items.
"""
)
Self.completeChangesObserver(
observer,
anchor: anchor,
enumeratedItemIdentifier: self.enumeratedItemIdentifier,
account: account,
remoteInterface: remoteInterface,
dbManager: dbManager,
newMetadatas: newMetadatas,
updatedMetadatas: updatedMetadatas,
deletedMetadatas: deletedMetadatas
)
listener?.enumerationActionFinished(actionId: actionId)
}
return
} else if enumeratedItemIdentifier == .trashContainer {
Self.logger.debug(
"Enumerating changes in trash set for: \(self.account.ncKitAccount, privacy: .public)"
)
Task {
let (_, capabilities, _, error) = await remoteInterface.currentCapabilities(
account: account, options: .init(), taskHandler: { _ in }
)
guard let capabilities, error == .success else {
Self.logger.error(
"""
Could not acquire capabilities, cannot check trash.
Error: \(error.errorDescription, privacy: .public)
""")
observer.finishEnumeratingWithError(NSFileProviderError(.serverUnreachable))
return
}
guard capabilities.files?.undelete == true else {
Self.logger.error("Trash is unsupported on server, cannot enumerate changes.")
observer.finishEnumeratingWithError(
NSError(domain: NSCocoaErrorDomain, code: NSFeatureUnsupportedError)
)
return
}
let (_, trashedItems, _, trashReadError) = await remoteInterface.trashedItems(
account: account,
options: .init(),
taskHandler: { task in
if let domain = self.domain {
NSFileProviderManager(for: domain)?.register(
task,
forItemWithIdentifier: self.enumeratedItemIdentifier,
completionHandler: { _ in }
)
}
}
)
guard trashReadError == .success else {
let error = trashReadError.fileProviderError(
handlingNoSuchItemErrorUsingItemIdentifier: self.enumeratedItemIdentifier
) ?? NSFileProviderError(.cannotSynchronize)
listener?.enumerationActionFailed(actionId: actionId, error: error)
observer.finishEnumeratingWithError(error)
return
}
await Self.completeChangesObserver(
observer,
anchor: anchor,
account: account,
remoteInterface: remoteInterface,
dbManager: dbManager,
trashItems: trashedItems
)
listener?.enumerationActionFinished(actionId: actionId)
}
return
}
Self.logger.info(
"""
Enumerating changes for user: \(self.account.ncKitAccount, privacy: .public)
with serverUrl: \(self.serverUrl, privacy: .public)
"""
)
// No matter what happens here we finish enumeration in some way, either from the error
// handling below or from the completeChangesObserver
// TODO: Move to the sync engine extension
Task {
let (
_, newMetadatas, updatedMetadatas, deletedMetadatas, readError
) = await Self.readServerUrl(
serverUrl,
account: account,
remoteInterface: remoteInterface,
dbManager: dbManager,
stopAtMatchingEtags: true
)
// If we get a 404 we might add more deleted metadatas
var currentDeletedMetadatas: [SendableItemMetadata] = []
if let notNilDeletedMetadatas = deletedMetadatas {
currentDeletedMetadatas = notNilDeletedMetadatas
}
guard readError == nil else {
Self.logger.error(
"""
Finishing enumeration of changes for: \(self.account.ncKitAccount, privacy: .public)
with serverUrl: \(self.serverUrl, privacy: .public)
with error: \(readError!.errorDescription, privacy: .public)
"""
)
let error = readError?.fileProviderError(
handlingNoSuchItemErrorUsingItemIdentifier: self.enumeratedItemIdentifier
) ?? NSFileProviderError(.cannotSynchronize)
if readError!.isNotFoundError {
Self.logger.info(
"""
404 error means item no longer exists.
Deleting metadata and reporting \(self.serverUrl, privacy: .public)
as deletion without error
"""
)
guard let itemMetadata = self.enumeratedItemMetadata else {
Self.logger.error(
"""
Invalid enumeratedItemMetadata.
Could not delete metadata nor report deletion.
"""
)
listener?.enumerationActionFailed(actionId: actionId, error: error)
observer.finishEnumeratingWithError(error)
return
}
if itemMetadata.directory {
if let deletedDirectoryMetadatas =
dbManager.deleteDirectoryAndSubdirectoriesMetadata(
ocId: itemMetadata.ocId)
{
currentDeletedMetadatas += deletedDirectoryMetadatas
} else {
Self.logger.error(
"""
Something went wrong when recursively deleting directory.
It's metadata was not found. Cannot report it as deleted.
"""
)
}
} else {
dbManager.deleteItemMetadata(ocId: itemMetadata.ocId)
}
Self.completeChangesObserver(
observer,
anchor: anchor,
enumeratedItemIdentifier: self.enumeratedItemIdentifier,
account: account,
remoteInterface: remoteInterface,
dbManager: dbManager,
newMetadatas: nil,
updatedMetadatas: nil,
deletedMetadatas: [itemMetadata]
)
listener?.enumerationActionFinished(actionId: actionId)
return
} else if readError!.isNoChangesError { // All is well, just no changed etags
Self.logger.info(
"""
Error was to say no changed files -- not bad error.
Finishing change enumeration.
"""
)
listener?.enumerationActionFinished(actionId: actionId)
observer.finishEnumeratingChanges(upTo: anchor, moreComing: false)
return
}
listener?.enumerationActionFailed(actionId: actionId, error: error)
observer.finishEnumeratingWithError(error)
return
}
Self.logger.info(
"""
Finished reading serverUrl: \(self.serverUrl, privacy: .public)
for user: \(self.account.ncKitAccount, privacy: .public)
"""
)
Self.completeChangesObserver(
observer,
anchor: anchor,
enumeratedItemIdentifier: self.enumeratedItemIdentifier,
account: account,
remoteInterface: remoteInterface,
dbManager: dbManager,
newMetadatas: newMetadatas,
updatedMetadatas: updatedMetadatas,
deletedMetadatas: deletedMetadatas
)
listener?.enumerationActionFinished(actionId: actionId)
}
}
public func currentSyncAnchor(completionHandler: @escaping (NSFileProviderSyncAnchor?) -> Void) {
completionHandler(anchor)
}
// MARK: - Helper methods
static func fileProviderPageforNumPage(_ numPage: Int) -> NSFileProviderPage? {
return nil
// TODO: Handle paging properly
// NSFileProviderPage("\(numPage)".data(using: .utf8)!)
}
private static func completeEnumerationObserver(
_ observer: NSFileProviderEnumerationObserver,
account: Account,
remoteInterface: RemoteInterface,
dbManager: FilesDatabaseManager,
numPage: Int,
itemMetadatas: [SendableItemMetadata],
handleInvalidParent: Bool = true
) {
Task {
do {
let items = try await itemMetadatas.toFileProviderItems(
account: account, remoteInterface: remoteInterface, dbManager: dbManager
)
Task { @MainActor in
observer.didEnumerate(items)
Self.logger.info("Did enumerate \(items.count) items")
// TODO: Handle paging properly
/*
if items.count == maxItemsPerFileProviderPage {
let nextPage = numPage + 1
let providerPage = NSFileProviderPage("\(nextPage)".data(using: .utf8)!)
observer.finishEnumerating(upTo: providerPage)
} else {
observer.finishEnumerating(upTo: nil)
}
*/
observer.finishEnumerating(upTo: fileProviderPageforNumPage(numPage))
}
} catch let error as NSError { // This error can only mean a missing parent item identifier
guard handleInvalidParent else {
Self.logger.info("Not handling invalid parent in enumeration")
observer.finishEnumeratingWithError(error)
return
}
do {
let metadata = try await Self.attemptInvalidParentRecovery(
error: error,
account: account,
remoteInterface: remoteInterface,
dbManager: dbManager
)
Self.completeEnumerationObserver(
observer,
account: account,
remoteInterface: remoteInterface,
dbManager: dbManager,
numPage: numPage,
itemMetadatas: [metadata] + itemMetadatas,
handleInvalidParent: false
)
} catch let error {
observer.finishEnumeratingWithError(error)
}
}
}
}
private static func completeChangesObserver(
_ observer: NSFileProviderChangeObserver,
anchor: NSFileProviderSyncAnchor,
enumeratedItemIdentifier: NSFileProviderItemIdentifier,
account: Account,
remoteInterface: RemoteInterface,
dbManager: FilesDatabaseManager,
newMetadatas: [SendableItemMetadata]?,
updatedMetadatas: [SendableItemMetadata]?,
deletedMetadatas: [SendableItemMetadata]?,
handleInvalidParent: Bool = true
) {
guard newMetadatas != nil || updatedMetadatas != nil || deletedMetadatas != nil else {
Self.logger.error(
"""
Received invalid newMetadatas, updatedMetadatas or deletedMetadatas.
Finished enumeration of changes with error.
"""
)
observer.finishEnumeratingWithError(
NSError.fileProviderErrorForNonExistentItem(
withIdentifier: enumeratedItemIdentifier
)
)
return
}
// Observer does not care about new vs updated, so join
var allUpdatedMetadatas: [SendableItemMetadata] = []
var allDeletedMetadatas: [SendableItemMetadata] = []
if let newMetadatas {
allUpdatedMetadatas += newMetadatas
}
if let updatedMetadatas {
allUpdatedMetadatas += updatedMetadatas
}
if let deletedMetadatas {
allDeletedMetadatas = deletedMetadatas
}
let allFpItemDeletionsIdentifiers = Array(
allDeletedMetadatas.map { NSFileProviderItemIdentifier($0.ocId) })
if !allFpItemDeletionsIdentifiers.isEmpty {
observer.didDeleteItems(withIdentifiers: allFpItemDeletionsIdentifiers)
}
Task { [allUpdatedMetadatas, allDeletedMetadatas] in
do {
let updatedItems = try await allUpdatedMetadatas.toFileProviderItems(
account: account, remoteInterface: remoteInterface, dbManager: dbManager
)
Task { @MainActor in
if !updatedItems.isEmpty {
observer.didUpdate(updatedItems)
}
Self.logger.info(
"""
Processed \(updatedItems.count) new or updated metadatas.
\(allDeletedMetadatas.count) deleted metadatas.
"""
)
observer.finishEnumeratingChanges(upTo: anchor, moreComing: false)
}
} catch let error as NSError { // This error can only mean a missing parent item identifier
guard handleInvalidParent else {
Self.logger.info("Not handling invalid parent in change enumeration")
observer.finishEnumeratingWithError(error)
return
}
do {
let metadata = try await Self.attemptInvalidParentRecovery(
error: error,
account: account,
remoteInterface: remoteInterface,
dbManager: dbManager
)
var modifiedNewMetadatas = newMetadatas
modifiedNewMetadatas?.append(metadata)
Self.completeChangesObserver(
observer,
anchor: anchor,
enumeratedItemIdentifier: enumeratedItemIdentifier,
account: account,
remoteInterface: remoteInterface,
dbManager: dbManager,
newMetadatas: modifiedNewMetadatas,
updatedMetadatas: updatedMetadatas,
deletedMetadatas: deletedMetadatas,
handleInvalidParent: false
)
} catch let error {
observer.finishEnumeratingWithError(error)
}
}
}
}
private static func attemptInvalidParentRecovery(
error: NSError,
account: Account,
remoteInterface: RemoteInterface,
dbManager: FilesDatabaseManager
) async throws -> SendableItemMetadata {
Self.logger.info("Attempting recovery from invalid parent identifier.")
// Try to recover from errors involving missing metadata for a parent
let userInfoKey =
FilesDatabaseManager.ErrorUserInfoKey.missingParentServerUrlAndFileName.rawValue
guard let urlToEnumerate = (error as NSError).userInfo[userInfoKey] as? String else {
Self.logger.fault("No missing parent server url and filename in error user info.")
assert(false)
throw NSError()
}
Self.logger.info(
"Recovering from invalid parent identifier at \(urlToEnumerate, privacy: .public)"
)
let (metadatas, _, _, _, error) = await Enumerator.readServerUrl(
urlToEnumerate,
account: account,
remoteInterface: remoteInterface,
dbManager: dbManager,
depth: .target
)
guard error == nil || error == .success, let metadata = metadatas?.first else {
Self.logger.error(
"""
Problem retrieving parent for metadata.
Error: \(error?.errorDescription ?? "NONE", privacy: .public)
Metadatas: \(metadatas?.count ?? -1, privacy: .public)
"""
)
throw error?.fileProviderError ?? NSFileProviderError(.cannotSynchronize)
}
// Provide it to the caller method so it can ingest it into the database and fix future errs
return metadata
}
}