-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathItem+LockFile.swift
More file actions
315 lines (277 loc) · 13.6 KB
/
Item+LockFile.swift
File metadata and controls
315 lines (277 loc) · 13.6 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
// SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors
// SPDX-License-Identifier: GPL-2.0-or-later
import FileProvider
import NextcloudCapabilitiesKit
import NextcloudKit
extension Item {
///
/// Shared capability assertion before dispatching (un)lock requests to the server.
///
private static func assertRequiredCapabilities(domain: NSFileProviderDomain?, itemIdentifier: NSFileProviderItemIdentifier, account: Account, remoteInterface: RemoteInterface, logger: FileProviderLogger) async -> Bool {
let (_, capabilities, _, capabilitiesError) = await remoteInterface.currentCapabilities(
account: account,
options: .init(),
taskHandler: { task in
if let domain {
NSFileProviderManager(for: domain)?.register(
task,
forItemWithIdentifier: itemIdentifier,
completionHandler: { _ in }
)
}
}
)
guard capabilitiesError == .success else {
logger.error("Request for capability assertion failed!")
return false
}
guard let capabilities else {
logger.error("Capabilities to assert are nil!")
return false
}
guard capabilities.files?.locking != nil else {
logger.error("Capability assertion failed because file locks are not supported!")
return false
}
return true
}
///
/// Create a lock file in the local file provider extension database which is not synchronized to the server, if the server supports file locking.
/// The lock file itself is not uploaded and no error is reported intentionally.
///
/// - Parameters:
/// - basedOn: Passed through as received from the file provider framework.
/// - parentItemIdentifier: Passed through as received from the file provider framework.
/// - parentItemRemotePath: Passed through as received from the file provider framework.
/// - progress: Passed through as received from the file provider framework.
/// - domain: File provider domain with which the background network task should be associated with.
/// - account: The Nextcloud account to use for interaction with the server.
/// - remoteInterface: The server API abstraction to use for calls.
/// - dbManager: The database manager to use for managing metadata.
///
/// - Returns: Either the created `item` or an `error` but not both. In either case the other value is `nil`. To be passed to the completion handler provided by the file provider framework.
///
static func createLockFile(
basedOn itemTemplate: NSFileProviderItem,
parentItemIdentifier: NSFileProviderItemIdentifier,
parentItemRemotePath: String,
progress: Progress,
domain: NSFileProviderDomain? = nil,
account: Account,
remoteInterface: RemoteInterface,
dbManager: FilesDatabaseManager,
log: any FileProviderLogging
) async -> (Item?, Error?) {
let logger = FileProviderLogger(category: "Item", log: log)
progress.totalUnitCount = 1
guard await assertRequiredCapabilities(domain: domain, itemIdentifier: itemTemplate.itemIdentifier, account: account, remoteInterface: remoteInterface, logger: logger) else {
logger.debug("Excluding lock file from synchronizing due to lack of server-side locking capability.", [.item: itemTemplate, .name: itemTemplate.filename])
let error = if #available(macOS 13.0, *) {
NSFileProviderError(.excludedFromSync)
} else {
NSFileProviderError(.cannotSynchronize)
}
return (nil, error)
}
logger.info("Item to create is a lock file. Will attempt to lock the associated file on the server.", [.name: itemTemplate.filename])
guard let targetFileName = originalFileName(fromLockFileName: itemTemplate.filename, dbManager: dbManager) else {
logger.error("Will not lock the target file because it could not be determined based on the lock file name.", [.name: itemTemplate.filename])
if #available(macOS 13.0, *) {
return (nil, NSFileProviderError(.excludedFromSync))
} else {
return (nil, NSFileProviderError(.cannotSynchronize))
}
}
logger.debug("Derived target file name for lock file.", [.name: targetFileName])
let targetFileRemotePath = parentItemRemotePath + "/" + targetFileName
let metadata = SendableItemMetadata(
ocId: itemTemplate.itemIdentifier.rawValue,
account: account.ncKitAccount,
classFile: "lock", // Indicates this metadata is for a locked file
contentType: itemTemplate.contentType?.preferredMIMEType ?? "",
creationDate: itemTemplate.creationDate as? Date ?? Date(),
date: Date(),
directory: false,
e2eEncrypted: false,
etag: "",
fileId: itemTemplate.itemIdentifier.rawValue,
fileName: itemTemplate.filename,
fileNameView: itemTemplate.filename,
hasPreview: false,
iconName: "lockIcon", // Custom icon for locked items
isLockfileOfLocalOrigin: true,
mountType: "",
ownerId: account.id,
ownerDisplayName: "",
path: parentItemRemotePath + "/" + targetFileName,
serverUrl: parentItemRemotePath,
size: 0,
status: Status.normal.rawValue,
downloaded: true,
uploaded: false,
urlBase: account.serverUrl,
user: account.username,
userId: account.id
)
dbManager.addItemMetadata(metadata)
var errorToReturn: Error?
do {
let lock = try await remoteInterface.lockUnlockFile(serverUrlFileName: targetFileRemotePath, type: .token, shouldLock: true, account: account, options: .init(), taskHandler: { task in
if let domain {
NSFileProviderManager(for: domain)?.register(
task,
forItemWithIdentifier: itemTemplate.itemIdentifier,
completionHandler: { _ in }
)
}
})
if let lock {
logger.info("Locked file and received lock, will update target item.", [.name: targetFileName, .lock: lock])
if let targetMetadata = dbManager.itemMetadatas.where({ $0.fileName.equals(targetFileName) }).where({ $0.serverUrl.equals(parentItemRemotePath) }).first {
try dbManager.ncDatabase().write {
targetMetadata.lock = true
targetMetadata.lockOwner = lock.owner
targetMetadata.lockOwnerDisplayName = lock.ownerDisplayName
targetMetadata.lockOwnerEditor = lock.ownerEditor
targetMetadata.lockOwnerType = lock.ownerType.rawValue
targetMetadata.lockTime = lock.time
targetMetadata.lockTimeOut = lock.timeOut
targetMetadata.lockToken = lock.token
}
} else {
logger.error("Failed to find target item for acquired lock.", [.lock: lock])
}
} else {
logger.info("Locked file but did not receive lock information.", [.name: targetFileName])
}
} catch {
logger.error("Failed to lock file \"\(targetFileName)\" which has lock file \"\(itemTemplate.filename)\".", [.error: error])
if let nkError = error as? NKError {
// Attempt to map a possible NKError to an NSFileProviderError.
errorToReturn = nkError.fileProviderError
} else {
// Return the error as it is.
errorToReturn = error
}
}
progress.completedUnitCount = 1
return await (
Item(
metadata: metadata,
parentItemIdentifier: parentItemIdentifier,
account: account,
remoteInterface: remoteInterface,
dbManager: dbManager,
remoteSupportsTrash: remoteInterface.supportsTrash(account: account),
log: log
),
errorToReturn
)
}
func modifyLockFile(
itemTarget: NSFileProviderItem,
baseVersion: NSFileProviderItemVersion = NSFileProviderItemVersion(),
changedFields: NSFileProviderItemFields,
contents newContents: URL?,
options: NSFileProviderModifyItemOptions = [],
request: NSFileProviderRequest = NSFileProviderRequest(),
ignoredFiles: IgnoredFilesMatcher? = nil,
domain: NSFileProviderDomain? = nil,
forcedChunkSize: Int? = nil,
progress: Progress = .init(),
dbManager: FilesDatabaseManager
) async -> (Item?, Error?) {
logger.info("System requested modification of lock file. Marking as complete without syncing to server.", [.name: filename])
if isLockFileName(filename) == false {
logger.fault("Should not handle non-lock files here.", [.name: filename])
}
guard let modifiedItem = await modifyUnuploaded(
itemTarget: itemTarget,
baseVersion: baseVersion,
changedFields: changedFields,
contents: newContents,
options: options,
request: request,
ignoredFiles: ignoredFiles,
domain: domain,
forcedChunkSize: forcedChunkSize,
progress: progress,
dbManager: dbManager
) else {
logger.info("Cannot modify lock file because received a nil modified item.", [.name: filename])
return (nil, NSFileProviderError(.cannotSynchronize))
}
if !isLockFileName(modifiedItem.filename) {
logger.info("After modification, lock file: \(filename) is no longer a lock file (it is now named: \(modifiedItem.filename)) Will proceed with creating item on server (if possible).")
return await modifiedItem.createUnuploaded(
itemTarget: itemTarget,
baseVersion: baseVersion,
changedFields: changedFields,
contents: newContents,
options: options,
request: request,
ignoredFiles: ignoredFiles,
domain: domain,
forcedChunkSize: forcedChunkSize,
progress: progress,
dbManager: dbManager
)
}
return (modifiedItem, nil)
}
func deleteLockFile(domain: NSFileProviderDomain? = nil, dbManager: FilesDatabaseManager) async -> Error? {
guard await Self.assertRequiredCapabilities(domain: domain, itemIdentifier: itemIdentifier, account: account, remoteInterface: remoteInterface, logger: logger) else {
return nil
}
dbManager.deleteItemMetadata(ocId: metadata.ocId)
guard let originalFileName = originalFileName(fromLockFileName: metadata.fileName, dbManager: dbManager) else {
logger.error("Could not get original filename from lock file filename so will not unlock target file.", [.name: metadata.fileName])
return nil
}
let originalFileServerFileNameUrl = metadata.serverUrl + "/" + originalFileName
do {
let lock = try await remoteInterface.lockUnlockFile(
serverUrlFileName: originalFileServerFileNameUrl,
type: .token,
shouldLock: false,
account: account,
options: .init(),
taskHandler: { task in
if let domain {
NSFileProviderManager(for: domain)?.register(
task,
forItemWithIdentifier: self.itemIdentifier,
completionHandler: { _ in }
)
}
}
)
if let lock {
logger.info("Unlocked file and received lock.", [.name: originalFileName, .lock: lock])
} else {
logger.info("Unlocked file but did not receive lock information.", [.name: originalFileName])
}
logger.info("Removing lock from locally stored target item.", [.name: originalFileName])
if let targetMetadata = dbManager.itemMetadatas.where({ $0.fileName.equals(originalFileName) }).where({ $0.serverUrl.equals(metadata.serverUrl) }).first {
try dbManager.ncDatabase().write {
targetMetadata.lock = false
targetMetadata.lockOwner = nil
targetMetadata.lockOwnerDisplayName = nil
targetMetadata.lockOwnerEditor = nil
targetMetadata.lockOwnerType = nil
targetMetadata.lockTime = nil
targetMetadata.lockTimeOut = nil
targetMetadata.lockToken = nil
}
} else {
logger.error("Failed to find target item for released lock.", [.lock: lock])
}
} catch {
logger.error("Could not unlock item.", [.name: filename, .error: error])
if let error = error as? NKError {
return error.fileProviderError(handlingNoSuchItemErrorUsingItemIdentifier: itemIdentifier)
}
}
return nil
}
}