-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNextcloudKit+RemoteInterface.swift
More file actions
438 lines (415 loc) · 16.7 KB
/
NextcloudKit+RemoteInterface.swift
File metadata and controls
438 lines (415 loc) · 16.7 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
//
// NextcloudKit+RemoteInterface.swift
//
//
// Created by Claudio Cambra on 16/4/24.
//
import Alamofire
import FileProvider
import Foundation
import NextcloudCapabilitiesKit
import NextcloudKit
import OSLog
extension NextcloudKit: RemoteInterface {
public func setDelegate(_ delegate: any NextcloudKitDelegate) {
setup(delegate: delegate)
}
public func createFolder(
remotePath: String,
account: Account,
options: NKRequestOptions = .init(),
taskHandler: @escaping (URLSessionTask) -> Void = { _ in }
) async -> (account: String, ocId: String?, date: NSDate?, error: NKError) {
return await withCheckedContinuation { continuation in
createFolder(
serverUrlFileName: remotePath,
account: account.ncKitAccount,
options: options,
taskHandler: taskHandler
) { account, ocId, date, _, error in
continuation.resume(returning: (account, ocId, date as NSDate?, error))
}
}
}
public func upload(
remotePath: String,
localPath: String,
creationDate: Date? = nil,
modificationDate: Date? = nil,
account: Account,
options: NKRequestOptions = .init(),
requestHandler: @escaping (UploadRequest) -> Void = { _ in },
taskHandler: @escaping (URLSessionTask) -> Void = { _ in },
progressHandler: @escaping (Progress) -> Void = { _ in }
) async -> (
account: String,
ocId: String?,
etag: String?,
date: NSDate?,
size: Int64,
response: HTTPURLResponse?,
afError: AFError?,
remoteError: NKError
) {
return await withCheckedContinuation { continuation in
upload(
serverUrlFileName: remotePath,
fileNameLocalPath: localPath,
dateCreationFile: creationDate,
dateModificationFile: modificationDate,
account: account.ncKitAccount,
options: options,
requestHandler: requestHandler,
taskHandler: taskHandler,
progressHandler: progressHandler
) { account, ocId, etag, date, size, response, afError, nkError in
continuation.resume(returning: (
account,
ocId,
etag,
date as NSDate?,
size,
response?.response,
afError,
nkError
))
}
}
}
public func chunkedUpload(
localPath: String,
remotePath: String,
remoteChunkStoreFolderName: String = UUID().uuidString,
chunkSize: Int,
remainingChunks: [RemoteFileChunk],
creationDate: Date? = nil,
modificationDate: Date? = nil,
account: Account,
options: NKRequestOptions = .init(),
currentNumChunksUpdateHandler: @escaping (_ num: Int) -> Void = { _ in },
chunkCounter: @escaping (_ counter: Int) -> Void = { _ in },
chunkUploadStartHandler: @escaping (_ filesChunk: [RemoteFileChunk]) -> Void = { _ in },
requestHandler: @escaping (_ request: UploadRequest) -> Void = { _ in },
taskHandler: @escaping (_ task: URLSessionTask) -> Void = { _ in },
progressHandler: @escaping (Progress) -> Void = { _ in },
chunkUploadCompleteHandler: @escaping (_ fileChunk: RemoteFileChunk) -> Void = { _ in }
) async -> (
account: String,
fileChunks: [RemoteFileChunk]?,
file: NKFile?,
afError: AFError?,
remoteError: NKError
) {
guard let remoteUrl = URL(string: remotePath) else {
uploadLogger.error("NCKit ext: Could not get url from \(remotePath, privacy: .public)")
return ("", nil, nil, nil, .urlError)
}
let localUrl = URL(fileURLWithPath: localPath)
let fm = FileManager.default
let chunksOutputDirectoryUrl =
fm.temporaryDirectory.appendingPathComponent(remoteChunkStoreFolderName)
do {
try fm.createDirectory(at: chunksOutputDirectoryUrl, withIntermediateDirectories: true)
} catch let error {
uploadLogger.error(
"""
Could not create temporary directory for chunked files: \(error, privacy: .public)
"""
)
return ("", nil, nil, nil, .urlError)
}
var directory = localUrl.deletingLastPathComponent().path
if directory.last == "/" {
directory.removeLast()
}
let fileChunksOutputDirectory = chunksOutputDirectoryUrl.path
let fileName = localUrl.lastPathComponent
let destinationFileName = remoteUrl.lastPathComponent
guard let serverUrl = remoteUrl
.deletingLastPathComponent()
.absoluteString
.removingPercentEncoding
else {
uploadLogger.error(
"NCKit ext: Could not get server url from \(remotePath, privacy: .public)"
)
return ("", nil, nil, nil, .urlError)
}
let fileChunks = remainingChunks.toNcKitChunks()
uploadLogger.info(
"""
Beginning chunked upload of: \(localPath, privacy: .public)
directory: \(directory, privacy: .public)
fileChunksOutputDirectory: \(fileChunksOutputDirectory, privacy: .public)
fileName: \(fileName, privacy: .public)
destinationFileName: \(destinationFileName, privacy: .public)
date: \(modificationDate?.debugDescription ?? "", privacy: .public)
creationDate: \(creationDate?.debugDescription ?? "", privacy: .public)
serverUrl: \(serverUrl, privacy: .public)
chunkFolder: \(remoteChunkStoreFolderName, privacy: .public)
filesChunk: \(fileChunks, privacy: .public)
chunkSize: \(chunkSize, privacy: .public)
"""
)
return await withCheckedContinuation { continuation in
uploadChunk(
directory: directory,
fileChunksOutputDirectory: fileChunksOutputDirectory,
fileName: fileName,
destinationFileName: destinationFileName,
date: modificationDate,
creationDate: creationDate,
serverUrl: serverUrl,
chunkFolder: remoteChunkStoreFolderName,
filesChunk: fileChunks,
chunkSize: chunkSize,
account: account.ncKitAccount,
options: options,
numChunks: currentNumChunksUpdateHandler,
counterChunk: chunkCounter,
start: { processedChunks in
let chunks = RemoteFileChunk.fromNcKitChunks(
processedChunks, remoteChunkStoreFolderName: remoteChunkStoreFolderName
)
chunkUploadStartHandler(chunks)
},
requestHandler: requestHandler,
taskHandler: taskHandler,
progressHandler: { totalBytesExpected, totalBytes, fractionCompleted in
let currentProgress = Progress(totalUnitCount: totalBytesExpected)
currentProgress.completedUnitCount = totalBytes
progressHandler(currentProgress)
},
uploaded: { uploadedChunk in
let chunk = RemoteFileChunk(
ncKitChunk: uploadedChunk,
remoteChunkStoreFolderName: remoteChunkStoreFolderName
)
chunkUploadCompleteHandler(chunk)
}
) { account, receivedChunks, file, afError, error in
let chunks = RemoteFileChunk.fromNcKitChunks(
receivedChunks ?? [], remoteChunkStoreFolderName: remoteChunkStoreFolderName
)
continuation.resume(returning: (account, chunks, file, afError, error))
}
}
}
public func move(
remotePathSource: String,
remotePathDestination: String,
overwrite: Bool,
account: Account,
options: NKRequestOptions,
taskHandler: @escaping (URLSessionTask) -> Void
) async -> (account: String, data: Data?, error: NKError) {
return await withCheckedContinuation { continuation in
moveFileOrFolder(
serverUrlFileNameSource: remotePathSource,
serverUrlFileNameDestination: remotePathDestination,
overwrite: overwrite,
account: account.ncKitAccount,
options: options,
taskHandler: taskHandler
) { account, data, error in
continuation.resume(returning: (account, data?.data, error))
}
}
}
public func download(
remotePath: String,
localPath: String,
account: Account,
options: NKRequestOptions = .init(),
requestHandler: @escaping (DownloadRequest) -> Void = { _ in },
taskHandler: @escaping (URLSessionTask) -> Void = { _ in },
progressHandler: @escaping (Progress) -> Void = { _ in }
) async -> (
account: String,
etag: String?,
date: NSDate?,
length: Int64,
response: HTTPURLResponse?,
afError: AFError?,
remoteError: NKError
) {
return await withCheckedContinuation { continuation in
download(
serverUrlFileName: remotePath,
fileNameLocalPath: localPath,
account: account.ncKitAccount,
options: options,
requestHandler: requestHandler,
taskHandler: taskHandler,
progressHandler: progressHandler
) { account, etag, date, length, data, afError, remoteError in
continuation.resume(returning: (
account,
etag,
date as NSDate?,
length,
data?.response,
afError,
remoteError
))
}
}
}
public func enumerate(
remotePath: String,
depth: EnumerateDepth,
showHiddenFiles: Bool = false,
includeHiddenFiles: [String] = [],
requestBody: Data? = nil,
account: Account,
options: NKRequestOptions = .init(),
taskHandler: @escaping (URLSessionTask) -> Void = { _ in }
) async -> (
account: String, files: [NKFile], data: Data?, error: NKError
) {
return await withCheckedContinuation { continuation in
readFileOrFolder(
serverUrlFileName: remotePath,
depth: depth.rawValue,
showHiddenFiles: showHiddenFiles,
includeHiddenFiles: includeHiddenFiles,
requestBody: requestBody,
account: account.ncKitAccount,
options: options,
taskHandler: taskHandler
) { account, files, data, error in
continuation.resume(returning: (account, files ?? [], data?.data, error))
}
}
}
public func delete(
remotePath: String,
account: Account,
options: NKRequestOptions = .init(),
taskHandler: @escaping (URLSessionTask) -> Void = { _ in }
) async -> (account: String, response: HTTPURLResponse?, error: NKError) {
return await withCheckedContinuation { continuation in
deleteFileOrFolder(
serverUrlFileName: remotePath, account: account.ncKitAccount
) { account, response, error in
continuation.resume(returning: (account, response?.response, error))
}
}
}
public func setLockStateForFile(
remotePath: String,
lock: Bool,
account: Account,
options: NKRequestOptions,
taskHandler: @escaping (_ task: URLSessionTask) -> Void
) async -> (account: String, response: HTTPURLResponse?, error: NKError) {
return await withCheckedContinuation { continuation in
lockUnlockFile(
serverUrlFileName: remotePath, shouldLock: lock, account: account.ncKitAccount
) { account, response, error in
continuation.resume(returning: (account, response?.response, error))
}
}
}
public func trashedItems(
account: Account,
options: NKRequestOptions = .init(),
taskHandler: @escaping (URLSessionTask) -> Void
) async -> (account: String, trashedItems: [NKTrash], data: Data?, error: NKError) {
return await withCheckedContinuation { continuation in
listingTrash(
showHiddenFiles: true, account: account.ncKitAccount
) { account, items, data, error in
continuation.resume(returning: (account, items ?? [], data?.data, error))
}
}
}
public func restoreFromTrash(
filename: String,
account: Account,
options: NKRequestOptions,
taskHandler: @escaping (_ task: URLSessionTask) -> Void
) async -> (account: String, data: Data?, error: NKError) {
let trashFileUrl = account.trashUrl + "/" + filename
let recoverFileUrl = account.trashRestoreUrl + "/" + filename
return await move(
remotePathSource: trashFileUrl,
remotePathDestination: recoverFileUrl,
overwrite: true,
account: account,
options: options,
taskHandler: taskHandler
)
}
public func downloadThumbnail(
url: URL,
account: Account,
options: NKRequestOptions,
taskHandler: @escaping (URLSessionTask) -> Void
) async -> (account: String, data: Data?, error: NKError) {
await withCheckedContinuation { continuation in
downloadPreview(
url: url, account: account.ncKitAccount, options: options, taskHandler: taskHandler
) { account, data, error in
continuation.resume(returning: (account, data?.data, error))
}
}
}
public func fetchCapabilities(
account: Account,
options: NKRequestOptions = .init(),
taskHandler: @escaping (_ task: URLSessionTask) -> Void = { _ in }
) async -> (account: String, capabilities: Capabilities?, data: Data?, error: NKError) {
let ncKitAccount = account.ncKitAccount
await RetrievedCapabilitiesActor.shared.setOngoingFetch(
forAccount: ncKitAccount, ongoing: true
)
let result = await withCheckedContinuation { continuation in
getCapabilities(account: account.ncKitAccount, options: options, taskHandler: taskHandler) { account, data, error in
let capabilities: Capabilities? = {
guard let realData = data?.data else { return nil }
return Capabilities(data: realData)
}()
continuation.resume(returning: (account, capabilities, data?.data, error))
}
}
await RetrievedCapabilitiesActor.shared.setOngoingFetch(
forAccount: ncKitAccount, ongoing: false
)
if let capabilities = result.1 {
await RetrievedCapabilitiesActor.shared.setCapabilities(
forAccount: account.ncKitAccount, capabilities: capabilities
)
}
return result
}
public func fetchUserProfile(
account: Account,
options: NKRequestOptions = .init(),
taskHandler: @escaping (_ task: URLSessionTask) -> Void = { _ in }
) async -> (account: String, userProfile: NKUserProfile?, data: Data?, error: NKError) {
return await withCheckedContinuation { continuation in
getUserProfile(
account: account.ncKitAccount, options: options, taskHandler: taskHandler
) { account, userProfile, data, error in
continuation.resume(returning: (account, userProfile, data?.data, error))
}
}
}
public func tryAuthenticationAttempt(
account: Account,
options: NKRequestOptions = .init(),
taskHandler: @escaping (_ task: URLSessionTask) -> Void = { _ in }
) async -> AuthenticationAttemptResultState {
// Test by trying to fetch user profile
let (_, _, _, error) =
await enumerate(remotePath: account.davFilesUrl + "/", depth: .target, account: account)
if error == .success {
return .success
} else if error.isCouldntConnectError {
return .connectionError
} else {
return .authenticationError
}
}
}