FileProviderEnumerator.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. //
  2. // FileProviderEnumerator.swift
  3. // Files
  4. //
  5. // Created by Marino Faggiana on 26/03/18.
  6. // Copyright © 2018 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import UIKit
  24. import FileProvider
  25. import NextcloudKit
  26. class FileProviderEnumerator: NSObject, NSFileProviderEnumerator {
  27. var enumeratedItemIdentifier: NSFileProviderItemIdentifier
  28. var serverUrl: String?
  29. let fpUtility = fileProviderUtility()
  30. init(enumeratedItemIdentifier: NSFileProviderItemIdentifier) {
  31. self.enumeratedItemIdentifier = enumeratedItemIdentifier
  32. // Select ServerUrl
  33. if enumeratedItemIdentifier == .rootContainer {
  34. serverUrl = fileProviderData.shared.homeServerUrl
  35. } else {
  36. let metadata = fpUtility.getTableMetadataFromItemIdentifier(enumeratedItemIdentifier)
  37. if metadata != nil {
  38. if let directorySource = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata!.account, metadata!.serverUrl)) {
  39. serverUrl = directorySource.serverUrl + "/" + metadata!.fileName
  40. }
  41. }
  42. }
  43. super.init()
  44. }
  45. func invalidate() {
  46. }
  47. func enumerateItems(for observer: NSFileProviderEnumerationObserver, startingAt page: NSFileProviderPage) {
  48. var items: [NSFileProviderItemProtocol] = []
  49. /*** WorkingSet ***/
  50. if enumeratedItemIdentifier == .workingSet {
  51. var itemIdentifierMetadata: [NSFileProviderItemIdentifier: tableMetadata] = [:]
  52. // ***** Tags *****
  53. let tags = NCManageDatabase.shared.getTags(predicate: NSPredicate(format: "account == %@", fileProviderData.shared.account))
  54. for tag in tags {
  55. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(tag.ocId) else { continue }
  56. fpUtility.createocIdentifierOnFileSystem(metadata: metadata)
  57. itemIdentifierMetadata[fpUtility.getItemIdentifier(metadata: metadata)] = metadata
  58. }
  59. // ***** Favorite *****
  60. fileProviderData.shared.listFavoriteIdentifierRank = NCManageDatabase.shared.getTableMetadatasDirectoryFavoriteIdentifierRank(account: fileProviderData.shared.account)
  61. for (identifier, _) in fileProviderData.shared.listFavoriteIdentifierRank {
  62. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(identifier) else { continue }
  63. itemIdentifierMetadata[fpUtility.getItemIdentifier(metadata: metadata)] = metadata
  64. }
  65. // create items
  66. for (_, metadata) in itemIdentifierMetadata {
  67. let parentItemIdentifier = fpUtility.getParentItemIdentifier(metadata: metadata)
  68. if parentItemIdentifier != nil {
  69. let item = FileProviderItem(metadata: metadata, parentItemIdentifier: parentItemIdentifier!)
  70. items.append(item)
  71. }
  72. }
  73. observer.didEnumerate(items)
  74. observer.finishEnumerating(upTo: nil)
  75. } else {
  76. /*** ServerUrl ***/
  77. guard let serverUrl = serverUrl else {
  78. observer.finishEnumerating(upTo: nil)
  79. return
  80. }
  81. if page == NSFileProviderPage.initialPageSortedByDate as NSFileProviderPage || page == NSFileProviderPage.initialPageSortedByName as NSFileProviderPage {
  82. self.readFileOrFolder(serverUrl: serverUrl) { metadatas in
  83. self.completeObserver(observer, numPage: 1, metadatas: metadatas)
  84. }
  85. } else {
  86. let numPage = Int(String(data: page.rawValue, encoding: .utf8)!)!
  87. completeObserver(observer, numPage: numPage, metadatas: nil)
  88. }
  89. }
  90. }
  91. func enumerateChanges(for observer: NSFileProviderChangeObserver, from anchor: NSFileProviderSyncAnchor) {
  92. var itemsDelete: [NSFileProviderItemIdentifier] = []
  93. var itemsUpdate: [FileProviderItem] = []
  94. // Report the deleted items
  95. //
  96. if self.enumeratedItemIdentifier == .workingSet {
  97. for (itemIdentifier, _) in fileProviderData.shared.fileProviderSignalDeleteWorkingSetItemIdentifier {
  98. itemsDelete.append(itemIdentifier)
  99. }
  100. fileProviderData.shared.fileProviderSignalDeleteWorkingSetItemIdentifier.removeAll()
  101. } else {
  102. for (itemIdentifier, _) in fileProviderData.shared.fileProviderSignalDeleteContainerItemIdentifier {
  103. itemsDelete.append(itemIdentifier)
  104. }
  105. fileProviderData.shared.fileProviderSignalDeleteContainerItemIdentifier.removeAll()
  106. }
  107. // Report the updated items
  108. //
  109. if self.enumeratedItemIdentifier == .workingSet {
  110. for (_, item) in fileProviderData.shared.fileProviderSignalUpdateWorkingSetItem {
  111. itemsUpdate.append(item)
  112. }
  113. fileProviderData.shared.fileProviderSignalUpdateWorkingSetItem.removeAll()
  114. } else {
  115. for (_, item) in fileProviderData.shared.fileProviderSignalUpdateContainerItem {
  116. itemsUpdate.append(item)
  117. }
  118. fileProviderData.shared.fileProviderSignalUpdateContainerItem.removeAll()
  119. }
  120. observer.didDeleteItems(withIdentifiers: itemsDelete)
  121. observer.didUpdate(itemsUpdate)
  122. let data = "\(fileProviderData.shared.currentAnchor)".data(using: .utf8)
  123. observer.finishEnumeratingChanges(upTo: NSFileProviderSyncAnchor(data!), moreComing: false)
  124. }
  125. func currentSyncAnchor(completionHandler: @escaping (NSFileProviderSyncAnchor?) -> Void) {
  126. let data = "\(fileProviderData.shared.currentAnchor)".data(using: .utf8)
  127. completionHandler(NSFileProviderSyncAnchor(data!))
  128. }
  129. // --------------------------------------------------------------------------------------------
  130. // MARK: - User Function + Network
  131. // --------------------------------------------------------------------------------------------
  132. func completeObserver(_ observer: NSFileProviderEnumerationObserver, numPage: Int, metadatas: [tableMetadata]?) {
  133. var numPage = numPage
  134. var items: [NSFileProviderItemProtocol] = []
  135. if metadatas != nil {
  136. for metadata in metadatas! {
  137. if metadata.e2eEncrypted || (!metadata.session.isEmpty && metadata.session != NCNetworking.shared.sessionIdentifierBackgroundExtension) { continue }
  138. fpUtility.createocIdentifierOnFileSystem(metadata: metadata)
  139. let parentItemIdentifier = fpUtility.getParentItemIdentifier(metadata: metadata)
  140. if parentItemIdentifier != nil {
  141. let item = FileProviderItem(metadata: metadata, parentItemIdentifier: parentItemIdentifier!)
  142. items.append(item)
  143. }
  144. }
  145. observer.didEnumerate(items)
  146. }
  147. if items.count == fileProviderData.shared.itemForPage {
  148. numPage += 1
  149. let providerPage = NSFileProviderPage("\(numPage)".data(using: .utf8)!)
  150. observer.finishEnumerating(upTo: providerPage)
  151. } else {
  152. observer.finishEnumerating(upTo: nil)
  153. }
  154. }
  155. func readFileOrFolder(serverUrl: String, completionHandler: @escaping (_ metadatas: [tableMetadata]?) -> Void) {
  156. var directoryEtag: String?
  157. if let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", fileProviderData.shared.account, serverUrl)) {
  158. directoryEtag = tableDirectory.etag
  159. }
  160. NextcloudKit.shared.readFileOrFolder(serverUrlFileName: serverUrl, depth: "0", showHiddenFiles: NCKeychain().showHiddenFiles) { account, files, _, error in
  161. if directoryEtag != files.first?.etag {
  162. NextcloudKit.shared.readFileOrFolder(serverUrlFileName: serverUrl, depth: "1", showHiddenFiles: NCKeychain().showHiddenFiles) { account, files, _, error in
  163. if error == .success {
  164. DispatchQueue.global().async {
  165. NCManageDatabase.shared.convertFilesToMetadatas(files, useMetadataFolder: true) { _, metadatasFolder, metadatas in
  166. let metadatasResult = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND status == %d", account, serverUrl, NCGlobal.shared.metadataStatusNormal))
  167. NCManageDatabase.shared.updateMetadatas(metadatas, metadatasResult: metadatasResult)
  168. for metadata in metadatasFolder {
  169. let serverUrl = metadata.serverUrl + "/" + metadata.fileNameView
  170. NCManageDatabase.shared.addDirectory(encrypted: metadata.e2eEncrypted, favorite: metadata.favorite, ocId: metadata.ocId, fileId: metadata.fileId, etag: nil, permissions: metadata.permissions, serverUrl: serverUrl, account: metadata.account)
  171. }
  172. let metadatas = NCManageDatabase.shared.getAdvancedMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", fileProviderData.shared.account, serverUrl), sorted: "fileName", ascending: true)
  173. completionHandler(metadatas)
  174. }
  175. }
  176. } else {
  177. let metadatas = NCManageDatabase.shared.getAdvancedMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", fileProviderData.shared.account, serverUrl), sorted: "fileName", ascending: true)
  178. completionHandler(metadatas)
  179. }
  180. }
  181. } else {
  182. let metadatas = NCManageDatabase.shared.getAdvancedMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", fileProviderData.shared.account, serverUrl), sorted: "fileName", ascending: true)
  183. completionHandler(metadatas)
  184. }
  185. }
  186. }
  187. }