Skip to content
Navigation Menu
{{ message }}
forked from glushchenko/fsnotes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCloudDriveManager.swift
More file actions
416 lines (316 loc) · 14.4 KB
/
Copy pathCloudDriveManager.swift
File metadata and controls
416 lines (316 loc) · 14.4 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
//
// CloudDriveManager.swift
// FSNotes iOS
//
// Created by Oleksandr Glushchenko on 6/13/18.
// Copyright © 2018 Oleksandr Glushchenko. All rights reserved.
//
import Foundation
import UIKit
class CloudDriveManager {
private var cloudDriveResults = [URL]()
private var delegate: ViewController
private var storage: Storage
public let metadataQuery = NSMetadataQuery()
private var resultsDict = NSMutableDictionary()
private let workerQueue: OperationQueue = {
let workerQueue = OperationQueue()
workerQueue.name = "co.fluder.fsnotes.manager.browserdatasource.workerQueue"
workerQueue.maxConcurrentOperationCount = 1
workerQueue.qualityOfService = .background
return workerQueue
}()
private var shouldLoadTags: Bool = false
private var notesInsertionQueue = [Note]()
private var notesDeletionQueue = [Note]()
private var notesModificationQueue = [Note]()
private var projectsInsertionQueue = [Project]()
private var projectsDeletionQueue = [Project]()
init(delegate: ViewController, storage: Storage) {
metadataQuery.operationQueue = workerQueue
metadataQuery.searchScopes = [
NSMetadataQueryUbiquitousDocumentsScope
]
metadataQuery.notificationBatchingInterval = 1
metadataQuery.predicate = NSPredicate(format: "%K LIKE '*'", NSMetadataItemFSNameKey)
metadataQuery.sortDescriptors = [NSSortDescriptor(key: NSMetadataItemFSContentChangeDateKey, ascending: false)]
self.delegate = delegate
self.storage = storage
}
@objc func queryDidFinishGathering(notification: NSNotification) {
let query = notification.object as? NSMetadataQuery
if let results = query?.results as? [NSMetadataItem] {
saveCloudDriveResultsCache(results: results)
startInitialLoading(results: results)
}
metadataQuery.enableUpdates()
}
@objc func handleMetadataQueryUpdates(notification: NSNotification) {
guard let metadataQuery = notification.object as? NSMetadataQuery else { return }
metadataQuery.disableUpdates()
let changed = change(notification: notification)
let added = self.added(notification: notification)
let removed = remove(notification: notification)
doVisualChanges()
if added > 0 || removed > 0 || changed > 0,
let results = metadataQuery.results as? [NSMetadataItem] {
saveCloudDriveResultsCache(results: results)
}
metadataQuery.enableUpdates()
}
private func saveCloudDriveResultsCache(results: [NSMetadataItem]) {
let point = Date()
for result in results {
if let url = result.value(forAttribute: NSMetadataItemURLKey) as? URL {
resultsDict[metadataQuery.index(ofResult: result)] = url.standardized
}
}
print("N. iCloud Drive resources: \"\(results.count)\", caching finished in \(point.timeIntervalSinceNow * -1) seconds.")
}
private func startInitialLoading(results: [NSMetadataItem]) {
for metadataItem in results {
let url = metadataItem.value(forAttribute: NSMetadataItemURLKey) as? URL
let status = metadataItem.value(forAttribute: NSMetadataUbiquitousItemDownloadingStatusKey) as? String
if status == NSMetadataUbiquitousItemDownloadingStatusNotDownloaded,
let url = url,
FileManager.default.isUbiquitousItem(at: url) {
do {
try FileManager.default.startDownloadingUbiquitousItem(at: url)
} catch {
print("Download error: \(error)")
}
}
}
}
private func change(notification: NSNotification) -> Int {
guard let changedMetadataItems = notification.userInfo?[NSMetadataQueryUpdateChangedItemsKey] as? [NSMetadataItem] else { return 0 }
var completed = 0
for item in changedMetadataItems {
let status = item.value(forAttribute: NSMetadataUbiquitousItemDownloadingStatusKey) as? String
let index = metadataQuery.index(ofResult: item)
let itemUrl = item.value(forAttribute: NSMetadataItemURLKey) as? URL
let contentChangeDate = item.value(forAttribute: NSMetadataItemFSContentChangeDateKey) as? Date
let creationDate = item.value(forAttribute: NSMetadataItemFSCreationDateKey) as? Date
if status == NSMetadataUbiquitousItemDownloadingStatusCurrent {
completed += 1
}
guard let url = itemUrl?.standardized, status == NSMetadataUbiquitousItemDownloadingStatusCurrent else { continue }
// check projects
let isDirectory = (try? itemUrl?.resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory ?? false
let isPackage = (try? itemUrl?.resourceValues(forKeys: [.isDirectoryKey]))?.isPackage ?? false
// Is folder
if isDirectory && !isPackage && url.pathExtension != "textbundle" {
// Renamed – remove old
if let project = getProjectFromCloudDriveResults(item: item) {
projectsDeletionQueue.append(project)
}
// Add new
if storage.getProjectBy(url: url) == nil {
if let project = storage.addProject(url: url) {
projectsInsertionQueue.append(project)
}
}
continue
}
// Is file
guard storage.isValidNote(url: url) else { continue }
// Note already exist and update completed
if let note = storage.getBy(url: url, caseSensitive: true) {
if note.isTextBundle() && !note.isFullLoadedTextBundle() {
continue
}
if let currentNote = delegate.editorViewController?.editArea.note,
let date = contentChangeDate,
currentNote.isEqualURL(url: url),
date > note.modifiedLocalAt
{
note.modifiedLocalAt = date
// Trying load content from encrypted note with current password
if url.pathExtension == "etp", let password = note.password {
_ = note.unLock(password: password)
}
note.forceLoad()
delegate.refreshTextStorage(note: note)
}
print("File changed: \(url)")
// Not updates in FS attributes, must be loaded from Cloud Drive Meta
note.creationDate = creationDate
notesModificationQueue.append(note)
resolveConflict(url: url)
continue
}
// Note previously exist on different path
if let note = getNoteFromCloudDriveResults(item: item) {
// moved to unavailable dir (i.e. trash) is equal removed
guard storage.getProjectByNote(url: url) != nil else {
storage.removeNotes(notes: [note], fsRemove: false) {_ in
self.notesDeletionQueue.append(note)
}
print("File moved outside: \(url)")
continue
}
// moved to available dir
print("File moved to new url: \(url)")
notesDeletionQueue.append(note)
let srcUrl = note.url
note.url = url
note.parseURL()
note.moveHistory(src: srcUrl, dst: url)
resultsDict[index] = url
notesInsertionQueue.append(note)
continue
}
// Non exist yet, will add
importNote(url: url)
}
return completed
}
private func getNoteFromCloudDriveResults(item: NSMetadataItem) -> Note? {
let itemUrl = item.value(forAttribute: NSMetadataItemURLKey) as? URL
guard let url = itemUrl?.standardized else { return nil }
let index = self.metadataQuery.index(ofResult: item)
guard let prev = resultsDict[index] as? URL else { return nil }
if prev != url {
if let note = storage.getBy(url: prev) {
return note
}
}
return nil
}
private func getProjectFromCloudDriveResults(item: NSMetadataItem) -> Project? {
let itemUrl = item.value(forAttribute: NSMetadataItemURLKey) as? URL
guard let url = itemUrl?.standardized else { return nil }
let index = self.metadataQuery.index(ofResult: item)
guard let prev = resultsDict[index] as? URL else { return nil }
if prev != url {
if let project = storage.getProjectBy(url: prev) {
return project
}
}
return nil
}
private func added(notification: NSNotification) -> Int {
guard let addedMetadataItems =
notification.userInfo?[NSMetadataQueryUpdateAddedItemsKey] as? [NSMetadataItem]
else { return 0 }
for item in addedMetadataItems {
guard let url = (item.value(forAttribute: NSMetadataItemURLKey) as? URL)?.standardized else { continue }
let status = item.value(forAttribute: NSMetadataUbiquitousItemDownloadingStatusKey) as? String
if status != NSMetadataUbiquitousItemDownloadingStatusCurrent
&& FileManager.default.isUbiquitousItem(at: url) {
do {
try FileManager.default.startDownloadingUbiquitousItem(at: url)
} catch {
print("Download error: \(error)")
}
continue
}
// when file moved from outspace to FSNotes space
// i.e. revert from macOS trash to iCloud Drive
if storage.isValidNote(url: url) {
self.importNote(url: url)
}
}
return addedMetadataItems.count
}
private func remove(notification: NSNotification) -> Int {
guard let removedMetadataItems =
notification.userInfo?[NSMetadataQueryUpdateRemovedItemsKey] as?
[NSMetadataItem]
else { return 0 }
for item in removedMetadataItems {
guard let url = (item.value(forAttribute: NSMetadataItemURLKey) as? URL)?.standardized
else { continue }
if let note = storage.getBy(url: url) {
storage.removeNotes(notes: [note], fsRemove: false) {_ in
self.notesDeletionQueue.append(note)
}
}
if let project = storage.getProjectBy(url: url) {
storage.remove(project: project)
self.projectsDeletionQueue.append(project)
}
}
return removedMetadataItems.count
}
public func importNote(url: URL) {
guard let note = storage.importNote(url: url) else { return }
print("File imported: \(note.url)")
if !storage.contains(note: note) {
storage.noteList.append(note)
notesInsertionQueue.append(note)
}
}
public func resolveConflict(url: URL) {
if let conflicts = NSFileVersion.unresolvedConflictVersionsOfItem(at: url as URL) {
for conflict in conflicts {
guard let modificationDate = conflict.modificationDate else {
continue
}
guard let localizedName = conflict.localizedName else {
continue
}
let localizedUrl = URL(fileURLWithPath: localizedName)
let ext = url.pathExtension
let name = localizedUrl.deletingPathExtension().lastPathComponent
let dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = [
.withYear,
.withMonth,
.withDay,
.withTime
]
let dateString: String = dateFormatter.string(from: modificationDate)
let conflictName = "\(name) (CONFLICT \(dateString)).\(ext)"
let to = url.deletingLastPathComponent().appendingPathComponent(conflictName)
if FileManager.default.fileExists(atPath: to.path) {
conflict.isResolved = true
continue
}
// Reload current encrypted note
if let currentNote = delegate.editorViewController?.editArea.note, currentNote.url == url {
if let password = currentNote.password, ext == "etp" {
_ = currentNote.unLock(password: password)
}
currentNote.forceLoad()
delegate.refreshTextStorage(note: currentNote)
}
do {
try FileManager.default.copyItem(at: conflict.url, to: to)
var attributes = [FileAttributeKey : Any]()
attributes[.posixPermissions] = 0o777
try FileManager.default.setAttributes(attributes, ofItemAtPath: to.path)
} catch let error {
print("Conflict resolving error: ", error)
}
conflict.isResolved = true
}
}
}
private func doVisualChanges() {
let insert = notesInsertionQueue
let delete = notesDeletionQueue
let change = notesModificationQueue
notesInsertionQueue.removeAll()
notesDeletionQueue.removeAll()
notesModificationQueue.removeAll()
let projectsDeletion = projectsDeletionQueue
let projectsInsertion = projectsInsertionQueue
projectsDeletionQueue.removeAll()
projectsInsertionQueue.removeAll()
for note in insert {
note.forceLoad()
}
for note in change {
note.forceLoad(skipCreateDate: true)
}
DispatchQueue.main.async {
self.delegate.notesTable.removeRows(notes: delete)
self.delegate.notesTable.insertRows(notes: insert)
self.delegate.notesTable.reloadRows(notes: change)
self.delegate.sidebarTableView.removeRows(projects: projectsDeletion)
self.delegate.sidebarTableView.insertRows(projects: projectsInsertion)
self.delegate.updateNotesCounter()
}
}
}
You can’t perform that action at this time.
