NCFiles.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. //
  2. // NCFiles.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 26/09/2020.
  6. // Copyright © 2020 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 NextcloudKit
  25. class NCFiles: NCCollectionViewCommon {
  26. internal var isRoot: Bool = true
  27. internal var fileNameBlink: String?
  28. internal var fileNameOpen: String?
  29. // MARK: - View Life Cycle
  30. required init?(coder aDecoder: NSCoder) {
  31. super.init(coder: aDecoder)
  32. titleCurrentFolder = NCBrandOptions.shared.brand
  33. layoutKey = NCGlobal.shared.layoutViewFiles
  34. enableSearchBar = true
  35. headerMenuButtonsView = true
  36. headerRichWorkspaceDisable = false
  37. headerMenuTransferView = true
  38. emptyImage = UIImage(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
  39. emptyTitle = "_files_no_files_"
  40. emptyDescription = "_no_file_pull_down_"
  41. }
  42. override func viewDidLoad() {
  43. super.viewDidLoad()
  44. if isRoot {
  45. NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeUser), object: nil, queue: nil) { _ in
  46. self.navigationController?.popToRootViewController(animated: false)
  47. self.serverUrl = self.utilityFileSystem.getHomeServer(urlBase: self.appDelegate.urlBase, userId: self.appDelegate.userId)
  48. self.appDelegate.activeServerUrl = self.serverUrl
  49. self.isSearchingMode = false
  50. self.isEditMode = false
  51. self.selectOcId.removeAll()
  52. self.selectIndexPath.removeAll()
  53. self.layoutForView = NCManageDatabase.shared.getLayoutForView(account: self.appDelegate.account, key: self.layoutKey, serverUrl: self.serverUrl)
  54. self.gridLayout.itemForLine = CGFloat(self.layoutForView?.itemForLine ?? 3)
  55. if self.layoutForView?.layout == NCGlobal.shared.layoutList {
  56. self.collectionView?.collectionViewLayout = self.listLayout
  57. } else {
  58. self.collectionView?.collectionViewLayout = self.gridLayout
  59. }
  60. self.titleCurrentFolder = self.getNavigationTitle()
  61. self.setNavigationItems()
  62. self.reloadDataSource()
  63. self.reloadDataSourceNetwork()
  64. }
  65. }
  66. }
  67. override func viewWillAppear(_ animated: Bool) {
  68. if isRoot {
  69. serverUrl = utilityFileSystem.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId)
  70. titleCurrentFolder = getNavigationTitle()
  71. }
  72. super.viewWillAppear(animated)
  73. if dataSource.metadatas.isEmpty {
  74. reloadDataSource()
  75. }
  76. reloadDataSourceNetwork()
  77. }
  78. override func viewWillDisappear(_ animated: Bool) {
  79. super.viewWillDisappear(animated)
  80. fileNameBlink = nil
  81. fileNameOpen = nil
  82. }
  83. // MARK: - DataSource + NC Endpoint
  84. override func queryDB() {
  85. super.queryDB()
  86. let metadatas = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", self.appDelegate.account, self.serverUrl))
  87. let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", self.appDelegate.account, self.serverUrl))
  88. if self.metadataFolder == nil {
  89. self.metadataFolder = NCManageDatabase.shared.getMetadataFolder(account: self.appDelegate.account, urlBase: self.appDelegate.urlBase, userId: self.appDelegate.userId, serverUrl: self.serverUrl)
  90. }
  91. self.richWorkspaceText = directory?.richWorkspace
  92. self.dataSource = NCDataSource(
  93. metadatas: metadatas,
  94. account: self.appDelegate.account,
  95. directory: directory,
  96. sort: self.layoutForView?.sort,
  97. ascending: self.layoutForView?.ascending,
  98. directoryOnTop: self.layoutForView?.directoryOnTop,
  99. favoriteOnTop: true,
  100. groupByField: self.groupByField,
  101. providers: self.providers,
  102. searchResults: self.searchResults)
  103. }
  104. override func reloadDataSource(withQueryDB: Bool = true) {
  105. super.reloadDataSource(withQueryDB: withQueryDB)
  106. if !self.dataSource.metadatas.isEmpty {
  107. self.blinkCell(fileName: self.fileNameBlink)
  108. self.openFile(fileName: self.fileNameOpen)
  109. self.fileNameBlink = nil
  110. self.fileNameOpen = nil
  111. }
  112. }
  113. override func reloadDataSourceNetwork() {
  114. guard !isSearchingMode else {
  115. return networkSearch()
  116. }
  117. func downloadMetadata(_ metadata: tableMetadata) -> Bool {
  118. let fileSize = utilityFileSystem.fileProviderStorageSize(metadata.ocId, fileNameView: metadata.fileNameView)
  119. guard fileSize > 0 else { return false }
  120. if let localFile = NCManageDatabase.shared.getResultsTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))?.first {
  121. if localFile.etag != metadata.etag {
  122. return true
  123. }
  124. }
  125. return false
  126. }
  127. super.reloadDataSourceNetwork()
  128. networkReadFolder { tableDirectory, metadatas, metadatasChangedCount, metadatasChanged, error in
  129. if error == .success {
  130. for metadata in metadatas ?? [] where !metadata.directory && downloadMetadata(metadata) {
  131. if NCNetworking.shared.downloadQueue.operations.filter({ ($0 as? NCOperationDownload)?.metadata.ocId == metadata.ocId }).isEmpty {
  132. NCNetworking.shared.downloadQueue.addOperation(NCOperationDownload(metadata: metadata, selector: NCGlobal.shared.selectorDownloadFile))
  133. }
  134. }
  135. self.richWorkspaceText = tableDirectory?.richWorkspace
  136. if metadatasChangedCount != 0 || metadatasChanged {
  137. self.reloadDataSource()
  138. } else {
  139. self.reloadDataSource(withQueryDB: false)
  140. }
  141. } else {
  142. self.reloadDataSource(withQueryDB: false)
  143. }
  144. }
  145. }
  146. private func networkReadFolder(completion: @escaping(_ tableDirectory: tableDirectory?, _ metadatas: [tableMetadata]?, _ metadatasChangedCount: Int, _ metadatasChanged: Bool, _ error: NKError) -> Void) {
  147. var tableDirectory: tableDirectory?
  148. NCNetworking.shared.readFile(serverUrlFileName: serverUrl) { account, metadataFolder, error in
  149. guard error == .success, let metadataFolder else {
  150. return completion(nil, nil, 0, false, error)
  151. }
  152. tableDirectory = NCManageDatabase.shared.setDirectory(serverUrl: self.serverUrl, richWorkspace: metadataFolder.richWorkspace, account: account)
  153. // swiftlint:disable empty_string
  154. let forceReplaceMetadatas = tableDirectory?.etag == ""
  155. // swiftlint:enable empty_string
  156. if tableDirectory?.etag != metadataFolder.etag || metadataFolder.e2eEncrypted {
  157. NCNetworking.shared.readFolder(serverUrl: self.serverUrl,
  158. account: self.appDelegate.account,
  159. forceReplaceMetadatas: forceReplaceMetadatas) { _, metadataFolder, metadatas, metadatasChangedCount, metadatasChanged, error in
  160. guard error == .success else {
  161. return completion(tableDirectory, nil, 0, false, error)
  162. }
  163. self.metadataFolder = metadataFolder
  164. // E2EE
  165. if let metadataFolder = metadataFolder,
  166. metadataFolder.e2eEncrypted,
  167. NCKeychain().isEndToEndEnabled(account: self.appDelegate.account),
  168. !NCNetworkingE2EE().isInUpload(account: self.appDelegate.account, serverUrl: self.serverUrl) {
  169. let lock = NCManageDatabase.shared.getE2ETokenLock(account: self.appDelegate.account, serverUrl: self.serverUrl)
  170. NextcloudKit.shared.getE2EEMetadata(fileId: metadataFolder.ocId, e2eToken: lock?.e2eToken, options: NCNetworkingE2EE().getOptions()) { account, e2eMetadata, signature, _, error in
  171. if error == .success, let e2eMetadata = e2eMetadata {
  172. let error = NCEndToEndMetadata().decodeMetadata(e2eMetadata, signature: signature, serverUrl: self.serverUrl, account: account, urlBase: self.appDelegate.urlBase, userId: self.appDelegate.userId)
  173. if error == .success {
  174. self.reloadDataSource()
  175. } else {
  176. // Client Diagnostic
  177. NCManageDatabase.shared.addDiagnostic(account: account, issue: NCGlobal.shared.diagnosticIssueE2eeErrors)
  178. NCContentPresenter().showError(error: error)
  179. }
  180. } else if error.errorCode == NCGlobal.shared.errorResourceNotFound {
  181. // no metadata found, send a new metadata
  182. Task {
  183. let serverUrl = metadataFolder.serverUrl + "/" + metadataFolder.fileName
  184. let error = await NCNetworkingE2EE().uploadMetadata(account: metadataFolder.account, serverUrl: serverUrl, userId: metadataFolder.userId)
  185. if error != .success {
  186. NCContentPresenter().showError(error: error)
  187. }
  188. }
  189. } else {
  190. NCContentPresenter().showError(error: NKError(errorCode: NCGlobal.shared.errorE2EEKeyDecodeMetadata, errorDescription: "_e2e_error_"))
  191. }
  192. completion(tableDirectory, metadatas, metadatasChangedCount, metadatasChanged, error)
  193. }
  194. } else {
  195. completion(tableDirectory, metadatas, metadatasChangedCount, metadatasChanged, error)
  196. }
  197. }
  198. } else {
  199. completion(tableDirectory, nil, 0, false, NKError())
  200. }
  201. }
  202. }
  203. func blinkCell(fileName: String?) {
  204. if let fileName = fileName, let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileName == %@", self.appDelegate.account, self.serverUrl, fileName)) {
  205. let (indexPath, _) = self.dataSource.getIndexPathMetadata(ocId: metadata.ocId)
  206. if let indexPath = indexPath {
  207. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  208. UIView.animate(withDuration: 0.3) {
  209. self.collectionView.scrollToItem(at: indexPath, at: .centeredVertically, animated: false)
  210. } completion: { _ in
  211. if let cell = self.collectionView.cellForItem(at: indexPath) {
  212. cell.backgroundColor = .darkGray
  213. UIView.animate(withDuration: 2) {
  214. cell.backgroundColor = .clear
  215. }
  216. }
  217. }
  218. }
  219. }
  220. }
  221. }
  222. func openFile(fileName: String?) {
  223. if let fileName = fileName, let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileName == %@", self.appDelegate.account, self.serverUrl, fileName)) {
  224. let (indexPath, _) = self.dataSource.getIndexPathMetadata(ocId: metadata.ocId)
  225. if let indexPath = indexPath {
  226. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  227. self.collectionView(self.collectionView, didSelectItemAt: indexPath)
  228. }
  229. }
  230. }
  231. }
  232. }