-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathItem.swift
More file actions
399 lines (355 loc) · 14 KB
/
Item.swift
File metadata and controls
399 lines (355 loc) · 14 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
/*
* 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 UniformTypeIdentifiers
import OSLog
public class Item: NSObject, NSFileProviderItem {
public enum FileProviderItemTransferError: Error {
case downloadError
case uploadError
}
public let dbManager: FilesDatabaseManager
public let metadata: SendableItemMetadata
public let parentItemIdentifier: NSFileProviderItemIdentifier
public let account: Account
public let remoteInterface: RemoteInterface
public var itemIdentifier: NSFileProviderItemIdentifier {
NSFileProviderItemIdentifier(metadata.ocId)
}
public var capabilities: NSFileProviderItemCapabilities {
guard !metadata.directory else {
var directoryCapabilities: NSFileProviderItemCapabilities = [
.allowsAddingSubItems,
.allowsContentEnumerating,
.allowsReading,
.allowsDeleting,
.allowsReparenting,
.allowsRenaming
]
#if os(macOS)
if #available(macOS 11.3, *) {
directoryCapabilities.insert(.allowsExcludingFromSync)
}
#endif
// .allowsEvicting deprecated on macOS 13.0+, use contentPolicy instead
if #unavailable(macOS 13.0) {
directoryCapabilities.insert(.allowsEvicting)
}
if remoteInterface.currentCapabilitiesSync(account: account)?.files?.undelete == true {
directoryCapabilities.insert(.allowsTrashing)
}
return directoryCapabilities
}
guard !metadata.lock else {
return [.allowsReading]
}
var itemCapabilities: NSFileProviderItemCapabilities = [
.allowsWriting,
.allowsReading,
.allowsDeleting,
.allowsRenaming,
.allowsReparenting,
.allowsEvicting,
]
if remoteInterface.currentCapabilitiesSync(account: account)?.files?.undelete == true,
!isLockFileName(filename)
{
itemCapabilities.insert(.allowsTrashing)
}
return itemCapabilities
}
public var itemVersion: NSFileProviderItemVersion {
NSFileProviderItemVersion(
contentVersion: metadata.etag.data(using: .utf8)!,
metadataVersion: metadata.etag.data(using: .utf8)!)
}
public var filename: String {
metadata.isTrashed && !metadata.trashbinFileName.isEmpty ?
metadata.trashbinFileName : !metadata.fileName.isEmpty ?
metadata.fileName : "unnamed file"
}
public var contentType: UTType {
if itemIdentifier == .rootContainer || (metadata.contentType.isEmpty && metadata.directory)
{
return .folder
} else if metadata.contentType == "httpd/unix-directory", metadata.directory {
let filenameComponents = filename.components(separatedBy: ".")
if filenameComponents.count > 1, let ext = filenameComponents.last {
return UTType(filenameExtension: ext, conformingTo: .directory) ?? .folder
}
return .folder
} else if !metadata.contentType.isEmpty, let type = UTType(metadata.contentType) {
return type
}
let filenameExtension = filename.components(separatedBy: ".").last ?? ""
return UTType(filenameExtension: filenameExtension) ?? .content
}
public var documentSize: NSNumber? {
NSNumber(value: metadata.size)
}
public var creationDate: Date? {
metadata.creationDate as Date
}
public var lastUsedDate: Date? {
metadata.date as Date
}
public var contentModificationDate: Date? {
metadata.date as Date
}
public var isDownloaded: Bool {
metadata.directory || metadata.downloaded
}
public var isDownloading: Bool {
metadata.isDownload
}
public var downloadingError: Error? {
if metadata.status == Status.downloadError.rawValue {
return FileProviderItemTransferError.downloadError
}
return nil
}
public var isUploaded: Bool {
metadata.uploaded
}
public var isUploading: Bool {
metadata.isUpload
}
public var uploadingError: Error? {
if metadata.status == Status.uploadError.rawValue {
FileProviderItemTransferError.uploadError
} else {
nil
}
}
public var isShared: Bool {
!metadata.shareType.isEmpty
}
public var isSharedByCurrentUser: Bool {
isShared && metadata.ownerId == account.id
}
public var ownerNameComponents: PersonNameComponents? {
guard isShared, !isSharedByCurrentUser else { return nil }
let formatter = PersonNameComponentsFormatter()
return formatter.personNameComponents(from: metadata.ownerDisplayName)
}
public var childItemCount: NSNumber? {
if metadata.directory {
NSNumber(integerLiteral: dbManager.childItemCount(directoryMetadata: metadata))
} else {
nil
}
}
public var fileSystemFlags: NSFileProviderFileSystemFlags {
if metadata.lock,
(metadata.lockOwnerType != 0 || metadata.lockOwner != account.username),
metadata.lockTimeOut ?? Date() > Date()
{
return [.userReadable]
}
return [.userReadable, .userWritable]
}
public var userInfo: [AnyHashable : Any]? {
var userInfoDict = [AnyHashable : Any]()
if metadata.lock {
// Can be used to display lock/unlock context menu entries for FPUIActions
// Note that only files, not folders, should be lockable/unlockable
userInfoDict["locked"] = metadata.lock
}
// I suspect this is already exposed by Apple but the documentation is so vague I don't know
userInfoDict["downloaded"] = metadata.downloaded
return userInfoDict
}
@available(macOS 13.0, iOS 16.0, visionOS 1.0, *)
public var contentPolicy: NSFileProviderContentPolicy {
if metadata.keepOffline {
return .downloadEagerlyAndKeepDownloaded
}
return .inherited
}
public var keepOffline: Bool {
guard #available(macOS 13.0, iOS 16.0, visionOS 1.0, *) else { return false }
return metadata.keepOffline
}
public static func rootContainer(
account: Account,
remoteInterface: RemoteInterface,
dbManager: FilesDatabaseManager
) -> Item {
let metadata = SendableItemMetadata(
ocId: NSFileProviderItemIdentifier.rootContainer.rawValue,
account: account.ncKitAccount,
classFile: NKCommon.TypeClassFile.directory.rawValue,
contentType: "", // Placeholder as not set in original code
creationDate: Date(), // Default as not set in original code
directory: true,
e2eEncrypted: false, // Default as not set in original code
etag: "", // Placeholder as not set in original code
fileId: "", // Placeholder as not set in original code
fileName: "/",
fileNameView: "/",
hasPreview: false, // Default as not set in original code
iconName: "", // Placeholder as not set in original code
mountType: "", // Placeholder as not set in original code
ownerId: "", // Placeholder as not set in original code
ownerDisplayName: "", // Placeholder as not set in original code
path: "", // Placeholder as not set in original code
serverUrl: account.davFilesUrl,
size: 0, // Default as not set in original code
uploaded: true,
urlBase: "", // Placeholder as not set in original code
user: "", // Placeholder as not set in original code
userId: "" // Placeholder as not set in original code
)
return Item(
metadata: metadata,
parentItemIdentifier: .rootContainer,
account: account,
remoteInterface: remoteInterface,
dbManager: dbManager
)
}
public static func trashContainer(
remoteInterface: RemoteInterface,
account: Account,
dbManager: FilesDatabaseManager
) -> Item {
let metadata = SendableItemMetadata(
ocId: NSFileProviderItemIdentifier.trashContainer.rawValue,
account: account.ncKitAccount,
classFile: NKCommon.TypeClassFile.directory.rawValue,
contentType: "", // Placeholder as not set in original code
creationDate: Date(), // Default as not set in original code
directory: true,
e2eEncrypted: false, // Default as not set in original code
etag: "", // Placeholder as not set in original code
fileId: "", // Placeholder as not set in original code
fileName: "Trash",
fileNameView: "Trash",
hasPreview: false, // Default as not set in original code
iconName: "", // Placeholder as not set in original code
mountType: "", // Placeholder as not set in original code
ownerId: "", // Placeholder as not set in original code
ownerDisplayName: "", // Placeholder as not set in original code
path: "", // Placeholder as not set in original code
serverUrl: account.trashUrl,
size: 0, // Default as not set in original code
uploaded: true,
urlBase: "", // Placeholder as not set in original code
user: "", // Placeholder as not set in original code
userId: "" // Placeholder as not set in original code
)
return Item(
metadata: metadata,
parentItemIdentifier: .trashContainer,
account: account,
remoteInterface: remoteInterface,
dbManager: dbManager
)
}
static let logger = Logger(subsystem: Logger.subsystem, category: "item")
public required init(
metadata: SendableItemMetadata,
parentItemIdentifier: NSFileProviderItemIdentifier,
account: Account,
remoteInterface: RemoteInterface,
dbManager: FilesDatabaseManager
) {
self.metadata = metadata
self.parentItemIdentifier = parentItemIdentifier
self.account = account
self.remoteInterface = remoteInterface
self.dbManager = dbManager
super.init()
}
public static func storedItem(
identifier: NSFileProviderItemIdentifier,
account: Account,
remoteInterface: RemoteInterface,
dbManager: FilesDatabaseManager
) -> Item? {
// resolve the given identifier to a record in the model
guard identifier != .rootContainer else {
return Item.rootContainer(
account: account, remoteInterface: remoteInterface, dbManager: dbManager
)
}
guard identifier != .trashContainer else {
return Item.trashContainer(
remoteInterface: remoteInterface, account: account, dbManager: dbManager
)
}
guard let metadata = dbManager.itemMetadataFromFileProviderItemIdentifier(identifier) else {
return nil
}
var parentItemIdentifier: NSFileProviderItemIdentifier?
if metadata.isTrashed {
parentItemIdentifier = .trashContainer
} else {
parentItemIdentifier = dbManager.parentItemIdentifierFromMetadata(metadata)
}
guard let parentItemIdentifier else { return nil }
return Item(
metadata: metadata,
parentItemIdentifier: parentItemIdentifier,
account: account,
remoteInterface: remoteInterface,
dbManager: dbManager
)
}
public func localUrlForContents(domain: NSFileProviderDomain) async -> URL? {
guard isDownloaded else {
Self.logger.error(
"""
Unable to get local URL for item contents.
filename: \(self.filename, privacy: .public)
Item is not materialised.
"""
)
return nil
}
guard let manager = NSFileProviderManager(for: domain),
let fileUrl = try? await manager.getUserVisibleURL(for: itemIdentifier)
else {
Self.logger.error(
"""
Unable to get manager or user visible url for item.
filename: \(self.filename, privacy: .public)
Cannot provide local URL for contents.
"""
)
return nil
}
let fm = FileManager.default
let tempLocation = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString)
let coordinator = NSFileCoordinator()
var readData: Data?
coordinator.coordinate(readingItemAt: fileUrl, options: [], error: nil) { readURL in
readData = try? Data(contentsOf: readURL)
}
guard let readData else { return nil }
do {
try readData.write(to: tempLocation)
} catch let error {
Self.logger.error(
"""
Unable to write file item contents \(self.filename, privacy: .public) to temp url.
error: \(error.localizedDescription, privacy: .public)
Cannot provide local URL for contents.
"""
)
}
return tempLocation
}
}