NCFiles.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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. import RealmSwift
  26. class NCFiles: NCCollectionViewCommon {
  27. internal var isRoot: Bool = true
  28. internal var fileNameBlink: String?
  29. internal var fileNameOpen: String?
  30. internal var matadatasHash: String = ""
  31. required init?(coder aDecoder: NSCoder) {
  32. super.init(coder: aDecoder)
  33. titleCurrentFolder = NCBrandOptions.shared.brand
  34. layoutKey = NCGlobal.shared.layoutViewFiles
  35. enableSearchBar = true
  36. headerRichWorkspaceDisable = false
  37. headerMenuTransferView = true
  38. emptyTitle = "_files_no_files_"
  39. emptyDescription = "_no_file_pull_down_"
  40. }
  41. // MARK: - View Life Cycle
  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) { notification in
  46. if let userInfo = notification.userInfo, let account = userInfo["account"] as? String {
  47. if let controller = userInfo["controller"] as? NCMainTabBarController,
  48. controller == self.controller {
  49. controller.account = account
  50. } else {
  51. return
  52. }
  53. }
  54. self.navigationController?.popToRootViewController(animated: false)
  55. self.serverUrl = self.utilityFileSystem.getHomeServer(session: self.session)
  56. self.isSearchingMode = false
  57. self.isEditMode = false
  58. self.fileSelect.removeAll()
  59. self.layoutForView = self.database.getLayoutForView(account: self.session.account, key: self.layoutKey, serverUrl: self.serverUrl)
  60. if self.isLayoutList {
  61. self.collectionView?.collectionViewLayout = self.listLayout
  62. } else if self.isLayoutGrid {
  63. self.collectionView?.collectionViewLayout = self.gridLayout
  64. } else if self.isLayoutPhoto {
  65. self.collectionView?.collectionViewLayout = self.mediaLayout
  66. }
  67. self.titleCurrentFolder = self.getNavigationTitle()
  68. self.setNavigationLeftItems()
  69. self.dataSource.removeAll()
  70. self.reloadDataSource()
  71. self.getServerData()
  72. }
  73. }
  74. }
  75. override func viewWillAppear(_ animated: Bool) {
  76. if isRoot {
  77. serverUrl = utilityFileSystem.getHomeServer(session: session)
  78. titleCurrentFolder = getNavigationTitle()
  79. }
  80. super.viewWillAppear(animated)
  81. reloadDataSource()
  82. }
  83. override func viewDidAppear(_ animated: Bool) {
  84. super.viewDidAppear(animated)
  85. if !self.dataSource.isEmpty() {
  86. self.blinkCell(fileName: self.fileNameBlink)
  87. self.openFile(fileName: self.fileNameOpen)
  88. self.fileNameBlink = nil
  89. self.fileNameOpen = nil
  90. }
  91. if !isSearchingMode {
  92. getServerData()
  93. }
  94. }
  95. override func viewDidDisappear(_ animated: Bool) {
  96. super.viewDidDisappear(animated)
  97. fileNameBlink = nil
  98. fileNameOpen = nil
  99. }
  100. // MARK: - DataSource
  101. override func reloadDataSource() {
  102. guard !isSearchingMode else {
  103. return super.reloadDataSource()
  104. }
  105. var predicate = self.defaultPredicate
  106. let predicateDirectory = NSPredicate(format: "account == %@ AND serverUrl == %@", session.account, self.serverUrl)
  107. let dataSourceMetadatas = self.dataSource.getMetadatas()
  108. if NCKeychain().getPersonalFilesOnly(account: session.account) {
  109. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND (ownerId == %@ || ownerId == '') AND mountType == '' AND NOT (status IN %@)", session.account, self.serverUrl, session.userId, global.metadataStatusHideInView)
  110. }
  111. self.metadataFolder = database.getMetadataFolder(session: session, serverUrl: self.serverUrl)
  112. self.richWorkspaceText = database.getTableDirectory(predicate: predicateDirectory)?.richWorkspace
  113. let metadatas = self.database.getResultsMetadatasPredicate(predicate, layoutForView: layoutForView)
  114. self.dataSource = NCCollectionViewDataSource(metadatas: metadatas, layoutForView: layoutForView)
  115. if metadatas.isEmpty {
  116. return super.reloadDataSource()
  117. }
  118. self.dataSource.caching(metadatas: metadatas, dataSourceMetadatas: dataSourceMetadatas) { updated in
  119. if updated || self.isNumberOfItemsInAllSectionsNull || self.numberOfItemsInAllSections != metadatas.count {
  120. super.reloadDataSource()
  121. }
  122. }
  123. }
  124. override func getServerData() {
  125. if UIApplication.shared.applicationState == .background {
  126. NextcloudKit.shared.nkCommonInstance.writeLog("[DEBUG] Files not reload datasource network with the application in background")
  127. return
  128. }
  129. guard !isSearchingMode else {
  130. return networkSearch()
  131. }
  132. func downloadMetadata(_ metadata: tableMetadata) -> Bool {
  133. let fileSize = utilityFileSystem.fileProviderStorageSize(metadata.ocId, fileNameView: metadata.fileNameView)
  134. guard fileSize > 0 else { return false }
  135. if let localFile = database.getResultsTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))?.first {
  136. if localFile.etag != metadata.etag {
  137. return true
  138. }
  139. }
  140. return false
  141. }
  142. DispatchQueue.global().async {
  143. self.networkReadFolder { metadatas, isChanged, error in
  144. DispatchQueue.main.async {
  145. self.refreshControl.endRefreshing()
  146. if isChanged || self.isNumberOfItemsInAllSectionsNull {
  147. self.reloadDataSource()
  148. }
  149. }
  150. if error == .success {
  151. let metadatas: [tableMetadata] = metadatas ?? self.dataSource.getMetadatas()
  152. for metadata in metadatas where !metadata.directory && downloadMetadata(metadata) {
  153. if NCNetworking.shared.downloadQueue.operations.filter({ ($0 as? NCOperationDownload)?.metadata.ocId == metadata.ocId }).isEmpty {
  154. NCNetworking.shared.downloadQueue.addOperation(NCOperationDownload(metadata: metadata, selector: NCGlobal.shared.selectorDownloadFile))
  155. }
  156. }
  157. }
  158. }
  159. }
  160. }
  161. private func networkReadFolder(completion: @escaping (_ metadatas: [tableMetadata]?, _ isDataChanged: Bool, _ error: NKError) -> Void) {
  162. NCNetworking.shared.readFile(serverUrlFileName: serverUrl, account: session.account) { task in
  163. self.dataSourceTask = task
  164. if self.dataSource.isEmpty() {
  165. self.collectionView.reloadData()
  166. }
  167. } completion: { account, metadata, error in
  168. let isDirectoryE2EE = NCUtilityFileSystem().isDirectoryE2EE(session: self.session, serverUrl: self.serverUrl)
  169. guard error == .success, let metadata else {
  170. return completion(nil, false, error)
  171. }
  172. /// Check change eTag or E2EE or DataSource empty
  173. self.database.updateDirectoryRichWorkspace(metadata.richWorkspace, account: account, serverUrl: self.serverUrl)
  174. let tableDirectory = self.database.getTableDirectory(ocId: metadata.ocId)
  175. guard tableDirectory?.etag != metadata.etag || metadata.e2eEncrypted || self.dataSource.isEmpty() else {
  176. return completion(nil, false, NKError())
  177. }
  178. /// Check Response DataC hanged
  179. var checkResponseDataChanged = true
  180. if tableDirectory?.etag.isEmpty ?? true || isDirectoryE2EE {
  181. checkResponseDataChanged = false
  182. }
  183. NCNetworking.shared.readFolder(serverUrl: self.serverUrl,
  184. account: metadata.account,
  185. checkResponseDataChanged: checkResponseDataChanged,
  186. queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue) { task in
  187. self.dataSourceTask = task
  188. if self.dataSource.isEmpty() {
  189. self.collectionView.reloadData()
  190. }
  191. } completion: { account, metadataFolder, metadatas, isDataChanged, error in
  192. /// Error
  193. guard error == .success else {
  194. return completion(nil, false, error)
  195. }
  196. /// Updata folder
  197. if let metadataFolder {
  198. self.metadataFolder = metadataFolder
  199. self.richWorkspaceText = metadataFolder.richWorkspace
  200. }
  201. /// check Response Data Changed
  202. if !isDataChanged {
  203. return completion(nil, false, error)
  204. }
  205. guard let metadataFolder,
  206. isDirectoryE2EE,
  207. NCKeychain().isEndToEndEnabled(account: account),
  208. !NCNetworkingE2EE().isInUpload(account: account, serverUrl: self.serverUrl) else {
  209. return completion(metadatas, true, error)
  210. }
  211. /// E2EE
  212. let lock = self.database.getE2ETokenLock(account: account, serverUrl: self.serverUrl)
  213. NCNetworkingE2EE().getMetadata(fileId: metadataFolder.ocId, e2eToken: lock?.e2eToken, account: account) { account, version, e2eMetadata, signature, _, error in
  214. if error == .success, let e2eMetadata = e2eMetadata {
  215. let error = NCEndToEndMetadata().decodeMetadata(e2eMetadata, signature: signature, serverUrl: self.serverUrl, session: self.session)
  216. if error == .success {
  217. if version == "v1", NCCapabilities.shared.getCapabilities(account: account).capabilityE2EEApiVersion == NCGlobal.shared.e2eeVersionV20 {
  218. NextcloudKit.shared.nkCommonInstance.writeLog("[E2EE] Conversion v1 to v2")
  219. NCActivityIndicator.shared.start()
  220. Task {
  221. let serverUrl = metadataFolder.serverUrl + "/" + metadataFolder.fileName
  222. let error = await NCNetworkingE2EE().uploadMetadata(serverUrl: serverUrl, updateVersionV1V2: true, account: account)
  223. if error != .success {
  224. NCContentPresenter().showError(error: error)
  225. }
  226. NCActivityIndicator.shared.stop()
  227. }
  228. }
  229. } else {
  230. // Client Diagnostic
  231. self.database.addDiagnostic(account: account, issue: NCGlobal.shared.diagnosticIssueE2eeErrors)
  232. NCContentPresenter().showError(error: error)
  233. }
  234. } else if error.errorCode == NCGlobal.shared.errorResourceNotFound {
  235. // no metadata found, send a new metadata
  236. Task {
  237. let serverUrl = metadataFolder.serverUrl + "/" + metadataFolder.fileName
  238. let error = await NCNetworkingE2EE().uploadMetadata(serverUrl: serverUrl, account: account)
  239. if error != .success {
  240. NCContentPresenter().showError(error: error)
  241. }
  242. }
  243. } else {
  244. NCContentPresenter().showError(error: NKError(errorCode: NCGlobal.shared.errorE2EEKeyDecodeMetadata, errorDescription: "_e2e_error_"))
  245. }
  246. completion(metadatas, true, error)
  247. }
  248. }
  249. }
  250. }
  251. func blinkCell(fileName: String?) {
  252. if let fileName = fileName, let metadata = database.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileName == %@", session.account, self.serverUrl, fileName)) {
  253. let indexPath = self.dataSource.getIndexPathMetadata(ocId: metadata.ocId)
  254. if let indexPath = indexPath {
  255. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  256. UIView.animate(withDuration: 0.3) {
  257. self.collectionView.scrollToItem(at: indexPath, at: .centeredVertically, animated: false)
  258. } completion: { _ in
  259. if let cell = self.collectionView.cellForItem(at: indexPath) {
  260. cell.backgroundColor = .darkGray
  261. UIView.animate(withDuration: 2) {
  262. cell.backgroundColor = .clear
  263. }
  264. }
  265. }
  266. }
  267. }
  268. }
  269. }
  270. func openFile(fileName: String?) {
  271. if let fileName = fileName, let metadata = database.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileName == %@", session.account, self.serverUrl, fileName)) {
  272. let indexPath = self.dataSource.getIndexPathMetadata(ocId: metadata.ocId)
  273. if let indexPath = indexPath {
  274. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  275. self.collectionView(self.collectionView, didSelectItemAt: indexPath)
  276. }
  277. }
  278. }
  279. }
  280. // MARK: - NCAccountSettingsModelDelegate
  281. override func accountSettingsDidDismiss(tableAccount: tableAccount?, controller: NCMainTabBarController?) {
  282. let currentAccount = session.account
  283. if database.getAllTableAccount().isEmpty {
  284. appDelegate.openLogin(selector: NCGlobal.shared.introLogin)
  285. } else if let account = tableAccount?.account, account != currentAccount {
  286. NCAccount().changeAccount(account, userProfile: nil, controller: controller) { }
  287. } else if isRoot {
  288. titleCurrentFolder = getNavigationTitle()
  289. navigationItem.title = titleCurrentFolder
  290. }
  291. }
  292. }