-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathItem+Trash.swift
More file actions
321 lines (295 loc) · 12.8 KB
/
Item+Trash.swift
File metadata and controls
321 lines (295 loc) · 12.8 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
//
// Item+Trash.swift
// NextcloudFileProviderKit
//
// Created by Claudio Cambra on 9/5/25.
//
import FileProvider
import NextcloudKit
extension Item {
// Note: When handling trashing, the server handles filename conflicts for us
static func trash(
_ modifiedItem: Item,
account: Account,
dbManager: FilesDatabaseManager,
domain: NSFileProviderDomain?
) async -> (Item, Error?) {
let deleteError =
await modifiedItem.delete(trashing: true, domain: domain, dbManager: dbManager)
guard deleteError == nil else {
Self.logger.error(
"""
Error attempting to move item into trash:
\(modifiedItem.filename, privacy: .public)
\(deleteError?.localizedDescription ?? "", privacy: .public)
"""
)
return (modifiedItem, deleteError)
}
let ocId = modifiedItem.itemIdentifier.rawValue
guard let dirtyMetadata = dbManager.itemMetadata(ocId: ocId) else {
Self.logger.error(
"""
Could not correctly process trashing results, dirty metadata not found.
\(modifiedItem.filename, privacy: .public) \(ocId, privacy: .public)
"""
)
return (modifiedItem, NSFileProviderError(.cannotSynchronize))
}
let dirtyChildren = dbManager.childItems(directoryMetadata: dirtyMetadata)
let dirtyItem = Item(
metadata: dirtyMetadata,
parentItemIdentifier: .trashContainer,
account: account,
remoteInterface: modifiedItem.remoteInterface,
dbManager: dbManager,
remoteSupportsTrash: await modifiedItem.remoteInterface.supportsTrash(account: account)
)
// The server may have renamed the trashed file so we need to scan the entire trash
let (_, files, _, error) = await modifiedItem.remoteInterface.trashedItems(
account: account,
options: .init(),
taskHandler: { task in
if let domain {
NSFileProviderManager(for: domain)?.register(
task,
forItemWithIdentifier: modifiedItem.itemIdentifier,
completionHandler: { _ in }
)
}
}
)
guard error == .success else {
Self.logger.error(
"""
Received bad error from post-trashing remote scan:
\(error.errorDescription, privacy: .public) \(files, privacy: .public)
"""
)
return (dirtyItem, error.fileProviderError)
}
guard let targetItemNKTrash = files.first(
// It seems the server likes to return a fileId as the ocId for trash files, so let's
// check for the fileId too
where: { $0.ocId == modifiedItem.metadata.ocId ||
$0.fileId == modifiedItem.metadata.fileId })
else {
Self.logger.error(
"""
Did not find trashed item:
\(modifiedItem.filename, privacy: .public)
\(modifiedItem.itemIdentifier.rawValue, privacy: .public)
in trash. Asking for a rescan. Found trashed files were:
\(files.map {
($0.ocId, $0.fileId, $0.fileName, $0.trashbinFileName)
}, privacy: .public)
"""
)
if #available(macOS 11.3, *) {
return (dirtyItem, NSFileProviderError(.unsyncedEdits))
} else {
return (dirtyItem, NSFileProviderError(.syncAnchorExpired))
}
}
var postDeleteMetadata = targetItemNKTrash.toItemMetadata(account: account)
postDeleteMetadata.ocId = modifiedItem.itemIdentifier.rawValue
dbManager.addItemMetadata(postDeleteMetadata)
let postDeleteItem = Item(
metadata: postDeleteMetadata,
parentItemIdentifier: .trashContainer,
account: account,
remoteInterface: modifiedItem.remoteInterface,
dbManager: dbManager,
remoteSupportsTrash: await modifiedItem.remoteInterface.supportsTrash(account: account)
)
// Now we can directly update info on the child items
var (_, childFiles, _, childError) = await modifiedItem.remoteInterface.enumerate(
remotePath: postDeleteMetadata.serverUrl + "/" + postDeleteMetadata.fileName,
depth: EnumerateDepth.targetAndAllChildren, // Just do it in one go
showHiddenFiles: true,
includeHiddenFiles: [],
requestBody: nil,
account: account,
options: .init(),
taskHandler: { task in
if let domain {
NSFileProviderManager(for: domain)?.register(
task,
forItemWithIdentifier: modifiedItem.itemIdentifier,
completionHandler: { _ in }
)
}
}
)
guard error == .success else {
Self.logger.error(
"""
Received bad error or files from post-trashing child items remote scan:
\(error.errorDescription, privacy: .public) \(files, privacy: .public)
"""
)
return (postDeleteItem, childError.fileProviderError)
}
// Update state of child files
childFiles.removeFirst() // This is the target path, already scanned
for file in childFiles {
var metadata = file.toItemMetadata()
guard let original = dirtyChildren
.filter({ $0.ocId == metadata.ocId || $0.fileId == metadata.fileId })
.first
else {
Self.logger.info(
"""
Skipping post-trash child item metadata: \(metadata.fileName, privacy: .public)
Could not find matching existing item in database, cannot do ocId correction
"""
)
continue
}
metadata.ocId = original.ocId // Give original id back
dbManager.addItemMetadata(metadata)
Self.logger.info("Note: that was a post-trash child item metadata")
}
return (postDeleteItem, nil)
}
// Note: When restoring from the trash, the server handles filename conflicts for us
static func restoreFromTrash(
_ modifiedItem: Item,
account: Account,
remoteInterface: RemoteInterface,
dbManager: FilesDatabaseManager,
domain: NSFileProviderDomain?
) async -> (Item, Error?) {
func finaliseRestore(target: NKFile) async -> (Item, Error?) {
let restoredItemMetadata = target.toItemMetadata()
guard let parentItemIdentifier = await dbManager.parentItemIdentifierWithRemoteFallback(
fromMetadata: restoredItemMetadata,
remoteInterface: remoteInterface,
account: account
) else {
Self.logger.error("Could not find parent item identifier for \(originalLocation)")
return (modifiedItem, NSFileProviderError(.cannotSynchronize))
}
if restoredItemMetadata.directory {
_ = dbManager.renameDirectoryAndPropagateToChildren(
ocId: restoredItemMetadata.ocId,
newServerUrl: restoredItemMetadata.serverUrl,
newFileName: restoredItemMetadata.fileName
)
}
dbManager.addItemMetadata(restoredItemMetadata)
return (Item(
metadata: restoredItemMetadata,
parentItemIdentifier: parentItemIdentifier,
account: account,
remoteInterface: modifiedItem.remoteInterface,
dbManager: dbManager,
remoteSupportsTrash: await modifiedItem.remoteInterface.supportsTrash(account: account)
), nil)
}
let (_, _, restoreError) = await modifiedItem.remoteInterface.restoreFromTrash(
filename: modifiedItem.metadata.fileName,
account: account,
options: .init(),
taskHandler: { _ in }
)
guard restoreError == .success else {
Self.logger.error(
"""
Could not restore item \(modifiedItem.filename, privacy: .public) from trash
Received error: \(restoreError.errorDescription, privacy: .public)
"""
)
return (modifiedItem, restoreError.fileProviderError)
}
guard modifiedItem.metadata.trashbinOriginalLocation != "" else {
Self.logger.error(
"""
Could not scan restored item \(modifiedItem.filename, privacy: .public).
The trashed file's original location is invalid.
"""
)
if #available(macOS 11.3, *) {
return (modifiedItem, NSFileProviderError(.unsyncedEdits))
}
return (modifiedItem, NSFileProviderError(.cannotSynchronize))
}
let originalLocation =
account.davFilesUrl + "/" + modifiedItem.metadata.trashbinOriginalLocation
let (_, files, _, enumerateError) = await modifiedItem.remoteInterface.enumerate(
remotePath: originalLocation,
depth: .target,
showHiddenFiles: true,
includeHiddenFiles: [],
requestBody: nil,
account: account,
options: .init(),
taskHandler: { _ in }
)
guard enumerateError == .success, !files.isEmpty, let target = files.first else {
Self.logger.error(
"""
Could not scan restored state of file \(originalLocation, privacy: .public)
Received error: \(enumerateError.errorDescription, privacy: .public)
Files: \(files.count, privacy: .public)
"""
)
if #available(macOS 11.3, *) {
return (modifiedItem, NSFileProviderError(.unsyncedEdits))
}
return (modifiedItem, enumerateError.fileProviderError)
}
guard target.ocId == modifiedItem.itemIdentifier.rawValue else {
Self.logger.warning(
"""
Restored item \(originalLocation, privacy: .public)
does not match \(modifiedItem.filename, privacy: .public)
(it is likely that when restoring from the trash, there was another identical item).
"""
)
guard let finalSlashIndex = originalLocation.lastIndex(of: "/") else {
return (modifiedItem, NSFileProviderError(.cannotSynchronize))
}
var parentDirectoryRemotePath = originalLocation
parentDirectoryRemotePath.removeSubrange(finalSlashIndex..<originalLocation.endIndex)
Self.logger.info(
"""
Scanning parent folder at \(parentDirectoryRemotePath, privacy: .public) for current
state of item restored from trash.
"""
)
let (_, files, _, folderScanError) = await modifiedItem.remoteInterface.enumerate(
remotePath: parentDirectoryRemotePath,
depth: .targetAndDirectChildren,
showHiddenFiles: true,
includeHiddenFiles: [],
requestBody: nil,
account: account,
options: .init(),
taskHandler: { _ in }
)
guard folderScanError == .success else {
Self.logger.error(
"""
Scanning parent folder at \(parentDirectoryRemotePath, privacy: .public)
returned error: \(folderScanError.errorDescription)
"""
)
return (modifiedItem, NSFileProviderError(.cannotSynchronize))
}
guard let actualTarget = files.first(
where: { $0.ocId == modifiedItem.itemIdentifier.rawValue }
) else {
Self.logger.error(
"""
Scanning parent folder at \(parentDirectoryRemotePath, privacy: .public)
finished successfully but the target item restored from trash not found.
"""
)
return (modifiedItem, NSFileProviderError(.cannotSynchronize))
}
return await finaliseRestore(target: actualTarget)
}
return await finaliseRestore(target: target)
}
}