-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathItem+LockFile.swift
More file actions
303 lines (289 loc) · 11.2 KB
/
Copy pathItem+LockFile.swift
File metadata and controls
303 lines (289 loc) · 11.2 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
//
// Item+CreateLockFile.swift
// NextcloudFileProviderKit
//
// Created by Claudio Cambra on 17/4/25.
//
import FileProvider
import NextcloudCapabilitiesKit
extension Item {
static func createLockFile(
basedOn itemTemplate: NSFileProviderItem,
parentItemIdentifier: NSFileProviderItemIdentifier,
parentItemRemotePath: String,
progress: Progress,
domain: NSFileProviderDomain? = nil,
account: Account,
remoteInterface: RemoteInterface,
dbManager: FilesDatabaseManager
) async -> (Item?, Error?) {
progress.totalUnitCount = 1
// Lock but don't upload, do not error
let (_, capabilities, _, capabilitiesError) = await remoteInterface.currentCapabilities(
account: account,
options: .init(),
taskHandler: { task in
if let domain {
NSFileProviderManager(for: domain)?.register(
task,
forItemWithIdentifier: itemTemplate.itemIdentifier,
completionHandler: { _ in }
)
}
}
)
guard capabilitiesError == .success,
let capabilities,
capabilities.files?.locking != nil
else {
uploadLogger.info(
"""
Received nil capabilities data.
Received error: \(capabilitiesError.errorDescription, privacy: .public)
Capabilities nil: \(capabilities == nil ? "YES" : "NO", privacy: .public)
(if capabilities are not nil the server may just not have files_lock enabled).
Will not proceed with locking for \(itemTemplate.filename, privacy: .public)
"""
)
return (nil, nil)
}
Self.logger.info(
"""
Item to create:
\(itemTemplate.filename, privacy: .public)
is a lock file. Will handle by remotely locking the target file.
"""
)
guard let targetFileName = originalFileName(
fromLockFileName: itemTemplate.filename
) else {
Self.logger.error(
"""
Could not get original filename from lock file filename
\(itemTemplate.filename, privacy: .public)
so will not lock target file.
"""
)
return (nil, nil)
}
let targetFileRemotePath = parentItemRemotePath + "/" + targetFileName
let (_, _, error) = await remoteInterface.setLockStateForFile( // TODO: NOT WORKING
remotePath: targetFileRemotePath,
lock: true,
account: account,
options: .init(),
taskHandler: { task in
if let domain {
NSFileProviderManager(for: domain)?.register(
task,
forItemWithIdentifier: itemTemplate.itemIdentifier,
completionHandler: { _ in }
)
}
}
)
if error != .success {
Self.logger.error(
"""
Failed to lock target file \(targetFileName, privacy: .public)
for lock file: \(itemTemplate.filename, privacy: .public)
received error: \(error.errorDescription)
"""
)
} else {
Self.logger.info("Locked file at: \(targetFileRemotePath, privacy: .public)")
}
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
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)
progress.completedUnitCount = 1
var returnError = error.fileProviderError // No need to handle problem cases, no upload here
if #available(macOS 13.0, *), error == .success {
returnError = NSFileProviderError(.excludedFromSync)
}
return (
Item(
metadata: metadata,
parentItemIdentifier: parentItemIdentifier,
account: account,
remoteInterface: remoteInterface,
dbManager: dbManager,
remoteSupportsTrash: await remoteInterface.supportsTrash(account: account)
),
returnError
)
}
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?) {
Self.logger.info(
"""
System requested modification of lockfile \(self.filename, privacy: .public)
Marking as complete without syncing to server.
"""
)
assert(isLockFileName(filename), "Should not handle non-lock files here.")
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 {
Self.logger.info(
"Cannot modify lock file: \(self.filename) as received a nil modified item"
)
return (nil, NSFileProviderError(.cannotSynchronize))
}
if !isLockFileName(modifiedItem.filename) {
Self.logger.info(
"""
After modification, lock file: \(self.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
)
}
var returnError: Error? = nil
if #available(macOS 13.0, *) {
returnError = NSFileProviderError(.excludedFromSync)
}
return (modifiedItem, returnError)
}
func deleteLockFile(
domain: NSFileProviderDomain? = nil, dbManager: FilesDatabaseManager
) async -> Error? {
let (_, capabilities, _, capabilitiesError) = await remoteInterface.currentCapabilities(
account: account,
options: .init(),
taskHandler: { task in
if let domain {
NSFileProviderManager(for: domain)?.register(
task,
forItemWithIdentifier: self.itemIdentifier,
completionHandler: { _ in }
)
}
}
)
guard capabilitiesError == .success,
let capabilities,
capabilities.files?.locking != nil
else {
uploadLogger.info(
"""
Received nil capabilities data.
Received error: \(capabilitiesError.errorDescription, privacy: .public)
Capabilities nil: \(capabilities == nil ? "YES" : "NO", privacy: .public)
(if capabilities are not nil the server may just not have files_lock enabled).
Will not proceed with unlocking for \(self.filename, privacy: .public)
"""
)
return nil
}
dbManager.deleteItemMetadata(ocId: metadata.ocId)
guard let originalFileName = originalFileName(
fromLockFileName: metadata.fileName
) else {
Self.logger.error(
"""
Could not get original filename from lock file filename
\(self.metadata.fileName, privacy: .public)
so will not unlock target file.
"""
)
return nil
}
let originalFileServerFileNameUrl = metadata.serverUrl + "/" + originalFileName
let (_, _, error) = await remoteInterface.setLockStateForFile( // TODO: NOT WORKING
remotePath: originalFileServerFileNameUrl,
lock: false,
account: account,
options: .init(),
taskHandler: { task in
if let domain {
NSFileProviderManager(for: domain)?.register(
task,
forItemWithIdentifier: self.itemIdentifier,
completionHandler: { _ in }
)
}
}
)
guard error == .success else {
Self.logger.error(
"""
Could not unlock item for \(self.filename, privacy: .public)...
at \(originalFileServerFileNameUrl, privacy: .public)...
received error: \(error.errorCode, privacy: .public)
\(error.errorDescription, privacy: .public)
"""
)
return error.fileProviderError(
handlingNoSuchItemErrorUsingItemIdentifier: itemIdentifier
)
}
Self.logger.info(
"""
Successfully unlocked item for: \(self.filename, privacy: .public)...
at: \(originalFileServerFileNameUrl, privacy: .public)
"""
)
return nil
}
}