NCNetworkingProcess.swift 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. //
  2. // NCNetworkingProcess.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 25/06/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 Photos
  26. import RealmSwift
  27. class NCNetworkingProcess {
  28. static let shared = NCNetworkingProcess()
  29. private let utilityFileSystem = NCUtilityFileSystem()
  30. private let database = NCManageDatabase.shared
  31. private let global = NCGlobal.shared
  32. private let networking = NCNetworking.shared
  33. private var notificationToken: NotificationToken?
  34. private var hasRun: Bool = false
  35. private let lockQueue = DispatchQueue(label: "com.nextcloud.networkingprocess.lockqueue")
  36. private var timerProcess: Timer?
  37. private var enableControllingScreenAwake = true
  38. private init() {
  39. self.startTimer()
  40. self.startObserveTableMetadata()
  41. NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterPlayerIsPlaying), object: nil, queue: nil) { _ in
  42. self.enableControllingScreenAwake = false
  43. }
  44. NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterPlayerStoppedPlaying), object: nil, queue: nil) { _ in
  45. self.enableControllingScreenAwake = true
  46. }
  47. }
  48. private func startObserveTableMetadata() {
  49. do {
  50. let realm = try Realm()
  51. let results = realm.objects(tableMetadata.self).filter(NSPredicate(format: "status IN %@", global.metadataStatusObserve))
  52. notificationToken = results.observe { [weak self] (changes: RealmCollectionChange) in
  53. switch changes {
  54. case .initial:
  55. print("Initial")
  56. case .update(_, _, let insertions, let modifications):
  57. if insertions.count > 0 || modifications.count > 0 {
  58. guard let self else { return }
  59. self.startTimer()
  60. self.lockQueue.async {
  61. guard !self.hasRun, self.networking.isOnline else { return }
  62. self.hasRun = true
  63. Task { [weak self] in
  64. guard let self else { return }
  65. await self.start()
  66. self.hasRun = false
  67. }
  68. }
  69. }
  70. case .error(let error):
  71. print("Error: \(error.localizedDescription)")
  72. }
  73. }
  74. } catch let error {
  75. print("Error: \(error.localizedDescription)")
  76. }
  77. }
  78. private func startTimer() {
  79. self.timerProcess?.invalidate()
  80. self.timerProcess = Timer.scheduledTimer(withTimeInterval: 3, repeats: true, block: { _ in
  81. self.lockQueue.async {
  82. guard !self.hasRun,
  83. self.networking.isOnline,
  84. let results = self.database.getResultsMetadatas(predicate: NSPredicate(format: "status != %d", self.global.metadataStatusNormal))?.freeze()
  85. else { return }
  86. self.hasRun = true
  87. /// Keep screen awake
  88. ///
  89. Task {
  90. let tasks = await self.networking.getAllDataTask()
  91. let hasSynchronizationTask = tasks.contains { $0.taskDescription == NCGlobal.shared.taskDescriptionSynchronization }
  92. let resultsTransfer = results.filter { self.global.metadataStatusInTransfer.contains($0.status) }
  93. if !self.enableControllingScreenAwake { return }
  94. if resultsTransfer.isEmpty && !hasSynchronizationTask {
  95. ScreenAwakeManager.shared.mode = .off
  96. } else {
  97. ScreenAwakeManager.shared.mode = NCKeychain().screenAwakeMode
  98. }
  99. }
  100. if results.isEmpty {
  101. /// Remove Photo CameraRoll
  102. ///
  103. if NCKeychain().removePhotoCameraRoll,
  104. UIApplication.shared.applicationState == .active,
  105. let localIdentifiers = self.database.getAssetLocalIdentifiersUploaded(),
  106. !localIdentifiers.isEmpty {
  107. PHPhotoLibrary.shared().performChanges({
  108. PHAssetChangeRequest.deleteAssets(PHAsset.fetchAssets(withLocalIdentifiers: localIdentifiers, options: nil) as NSFastEnumeration)
  109. }, completionHandler: { _, _ in
  110. self.database.clearAssetLocalIdentifiers(localIdentifiers)
  111. self.hasRun = false
  112. })
  113. } else {
  114. self.hasRun = false
  115. }
  116. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUpdateBadgeNumber,
  117. object: nil,
  118. userInfo: ["counterDownload": 0,
  119. "counterUpload": 0])
  120. } else {
  121. Task { [weak self] in
  122. guard let self else { return }
  123. await self.start()
  124. self.hasRun = false
  125. }
  126. }
  127. }
  128. })
  129. }
  130. @discardableResult
  131. private func start() async -> (counterDownloading: Int, counterUploading: Int) {
  132. let applicationState = await checkApplicationState()
  133. let maxConcurrentOperationDownload = NCBrandOptions.shared.maxConcurrentOperationDownload
  134. var maxConcurrentOperationUpload = NCBrandOptions.shared.maxConcurrentOperationUpload
  135. let sessionUploadSelectors = [global.selectorUploadFileNODelete, global.selectorUploadFile, global.selectorUploadAutoUpload, global.selectorUploadAutoUploadAll]
  136. let metadatasDownloading = self.database.getMetadatas(predicate: NSPredicate(format: "status == %d", global.metadataStatusDownloading))
  137. let metadatasUploading = self.database.getMetadatas(predicate: NSPredicate(format: "status == %d", global.metadataStatusUploading))
  138. let metadatasUploadError: [tableMetadata] = self.database.getMetadatas(predicate: NSPredicate(format: "status == %d", global.metadataStatusUploadError), sortedByKeyPath: "sessionDate", ascending: true) ?? []
  139. let isWiFi = networking.networkReachability == NKCommon.TypeReachability.reachableEthernetOrWiFi
  140. var counterDownloading = metadatasDownloading.count
  141. var counterUploading = metadatasUploading.count
  142. /// ------------------------ WEBDAV
  143. ///
  144. let metadatas = database.getMetadatas(predicate: NSPredicate(format: "status IN %@", global.metadataStatusWaitWebDav))
  145. if !metadatas.isEmpty {
  146. let stop = await metadataStatusWaitWebDav()
  147. if stop {
  148. return (counterDownloading, counterUploading)
  149. }
  150. }
  151. /// ------------------------ DOWNLOAD
  152. ///
  153. let limitDownload = maxConcurrentOperationDownload - counterDownloading
  154. let metadatasWaitDownload = self.database.getMetadatas(predicate: NSPredicate(format: "session == %@ AND status == %d", networking.sessionDownloadBackground, global.metadataStatusWaitDownload), numItems: limitDownload, sorted: "sessionDate", ascending: true)
  155. for metadata in metadatasWaitDownload where counterDownloading < maxConcurrentOperationDownload {
  156. counterDownloading += 1
  157. networking.download(metadata: metadata, withNotificationProgressTask: true)
  158. }
  159. if counterDownloading == 0 {
  160. let metadatasDownloadError: [tableMetadata] = self.database.getMetadatas(predicate: NSPredicate(format: "session == %@ AND status == %d", networking.sessionDownloadBackground, global.metadataStatusDownloadError), sortedByKeyPath: "sessionDate", ascending: true) ?? []
  161. for metadata in metadatasDownloadError {
  162. // Verify COUNTER ERROR
  163. if let transfer = NCTransferProgress.shared.get(ocIdTransfer: metadata.ocIdTransfer),
  164. transfer.countError > 3 {
  165. continue
  166. }
  167. self.database.setMetadataSession(ocId: metadata.ocId,
  168. sessionError: "",
  169. status: global.metadataStatusWaitDownload)
  170. }
  171. }
  172. /// ------------------------ UPLOAD
  173. ///
  174. /// In background max 2 upload otherwise iOS Termination Reason: RUNNINGBOARD 0xdead10cc
  175. if applicationState == .background {
  176. maxConcurrentOperationUpload = 2
  177. }
  178. /// E2EE - only one for time
  179. for metadata in metadatasUploading.unique(map: { $0.serverUrl }) {
  180. if metadata.isDirectoryE2EE {
  181. return (counterDownloading, counterUploading)
  182. }
  183. }
  184. /// CHUNK - only one for time
  185. if !metadatasUploading.filter({ $0.chunk > 0 }).isEmpty {
  186. return (counterDownloading, counterUploading)
  187. }
  188. for sessionSelector in sessionUploadSelectors where counterUploading < maxConcurrentOperationUpload {
  189. let limitUpload = maxConcurrentOperationUpload - counterUploading
  190. let metadatasWaitUpload = self.database.getMetadatas(predicate: NSPredicate(format: "sessionSelector == %@ AND status == %d", sessionSelector, global.metadataStatusWaitUpload), numItems: limitUpload, sorted: "sessionDate", ascending: true)
  191. if !metadatasWaitUpload.isEmpty {
  192. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] PROCESS (UPLOAD) find \(metadatasWaitUpload.count) items")
  193. }
  194. for metadata in metadatasWaitUpload where counterUploading < maxConcurrentOperationUpload {
  195. if NCTransferProgress.shared.get(ocIdTransfer: metadata.ocIdTransfer) != nil {
  196. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Process auto upload skipped file: \(metadata.serverUrl)/\(metadata.fileNameView), because is already in session.")
  197. continue
  198. }
  199. let metadatas = await NCCameraRoll().extractCameraRoll(from: metadata)
  200. if metadatas.isEmpty {
  201. self.database.deleteMetadataOcId(metadata.ocId)
  202. }
  203. for metadata in metadatas where counterUploading < maxConcurrentOperationUpload {
  204. /// isE2EE
  205. let isInDirectoryE2EE = metadata.isDirectoryE2EE
  206. /// NO WiFi
  207. if !isWiFi && metadata.session == networking.sessionUploadBackgroundWWan { continue }
  208. if applicationState != .active && (isInDirectoryE2EE || metadata.chunk > 0) { continue }
  209. if let metadata = self.database.setMetadataStatus(ocId: metadata.ocId, status: global.metadataStatusUploading) {
  210. /// find controller
  211. var controller: NCMainTabBarController?
  212. if let sceneIdentifier = metadata.sceneIdentifier, !sceneIdentifier.isEmpty {
  213. controller = SceneManager.shared.getController(sceneIdentifier: sceneIdentifier)
  214. } else {
  215. for ctlr in SceneManager.shared.getControllers() {
  216. let account = await ctlr.account
  217. if account == metadata.account {
  218. controller = ctlr
  219. }
  220. }
  221. if controller == nil {
  222. controller = await UIApplication.shared.firstWindow?.rootViewController as? NCMainTabBarController
  223. }
  224. }
  225. networking.upload(metadata: metadata, controller: controller)
  226. if isInDirectoryE2EE || metadata.chunk > 0 {
  227. maxConcurrentOperationUpload = 1
  228. }
  229. counterUploading += 1
  230. }
  231. }
  232. }
  233. }
  234. /// No upload available ? --> Retry Upload in Error
  235. ///
  236. if counterUploading == 0 {
  237. for metadata in metadatasUploadError {
  238. // Verify COUNTER ERROR
  239. if let transfer = NCTransferProgress.shared.get(ocIdTransfer: metadata.ocIdTransfer),
  240. transfer.countError > 3 {
  241. continue
  242. }
  243. /// Verify QUOTA
  244. if metadata.sessionError.contains("\(global.errorQuota)") {
  245. NextcloudKit.shared.getUserProfile(account: metadata.account) { _, userProfile, _, error in
  246. if error == .success, let userProfile, userProfile.quotaFree > 0, userProfile.quotaFree > metadata.size {
  247. self.database.setMetadataSession(ocId: metadata.ocId,
  248. session: self.networking.sessionUploadBackground,
  249. sessionError: "",
  250. status: self.global.metadataStatusWaitUpload)
  251. }
  252. }
  253. } else {
  254. self.database.setMetadataSession(ocId: metadata.ocId,
  255. session: self.networking.sessionUploadBackground,
  256. sessionError: "",
  257. status: global.metadataStatusWaitUpload)
  258. }
  259. }
  260. }
  261. return (counterDownloading, counterUploading)
  262. }
  263. private func checkApplicationState() async -> UIApplication.State {
  264. await withCheckedContinuation { continuation in
  265. DispatchQueue.main.async {
  266. let appState = UIApplication.shared.applicationState
  267. continuation.resume(returning: appState)
  268. }
  269. }
  270. }
  271. private func metadataStatusWaitWebDav() async -> Bool {
  272. var returnValue: Bool = false
  273. /// ------------------------ CREATE FOLDER
  274. ///
  275. if let metadatasWaitCreateFolder = self.database.getMetadatas(predicate: NSPredicate(format: "status == %d", global.metadataStatusWaitCreateFolder), sortedByKeyPath: "serverUrl", ascending: true), !metadatasWaitCreateFolder.isEmpty {
  276. for metadata in metadatasWaitCreateFolder {
  277. let error = await networking.createFolder(metadata: metadata)
  278. if error != .success {
  279. if metadata.sessionError.isEmpty {
  280. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  281. let message = String(format: NSLocalizedString("_create_folder_error_", comment: ""), serverUrlFileName)
  282. NCContentPresenter().messageNotification(message, error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  283. }
  284. returnValue = true
  285. }
  286. }
  287. }
  288. /// ------------------------ COPY
  289. ///
  290. if let metadatasWaitCopy = self.database.getMetadatas(predicate: NSPredicate(format: "status == %d", global.metadataStatusWaitCopy), sortedByKeyPath: "serverUrl", ascending: true), !metadatasWaitCopy.isEmpty {
  291. for metadata in metadatasWaitCopy {
  292. let serverUrlTo = metadata.serverUrlTo
  293. let serverUrlFileNameSource = metadata.serverUrl + "/" + metadata.fileName
  294. var serverUrlFileNameDestination = serverUrlTo + "/" + metadata.fileName
  295. let overwrite = (metadata.storeFlag as? NSString)?.boolValue ?? false
  296. /// Within same folder
  297. if metadata.serverUrl == serverUrlTo {
  298. let fileNameCopy = await NCNetworking.shared.createFileName(fileNameBase: metadata.fileName, account: metadata.account, serverUrl: metadata.serverUrl)
  299. serverUrlFileNameDestination = serverUrlTo + "/" + fileNameCopy
  300. }
  301. let result = await networking.copyFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: overwrite, account: metadata.account)
  302. database.setMetadataCopyMove(ocId: metadata.ocId, serverUrlTo: "", overwrite: nil, status: global.metadataStatusNormal)
  303. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterCopyMoveFile, userInfo: ["serverUrl": metadata.serverUrl, "account": metadata.account, "dragdrop": false, "type": "copy"])
  304. if result.error == .success {
  305. NotificationCenter.default.postOnMainThread(name: self.global.notificationCenterGetServerData, userInfo: ["serverUrl": metadata.serverUrl])
  306. NotificationCenter.default.postOnMainThread(name: self.global.notificationCenterGetServerData, userInfo: ["serverUrl": serverUrlTo])
  307. } else {
  308. NCContentPresenter().showError(error: result.error)
  309. }
  310. }
  311. }
  312. /// ------------------------ MOVE
  313. ///
  314. if let metadatasWaitMove = self.database.getMetadatas(predicate: NSPredicate(format: "status == %d", global.metadataStatusWaitMove), sortedByKeyPath: "serverUrl", ascending: true), !metadatasWaitMove.isEmpty {
  315. for metadata in metadatasWaitMove {
  316. let serverUrlTo = metadata.serverUrlTo
  317. let serverUrlFileNameSource = metadata.serverUrl + "/" + metadata.fileName
  318. let serverUrlFileNameDestination = serverUrlTo + "/" + metadata.fileName
  319. let overwrite = (metadata.storeFlag as? NSString)?.boolValue ?? false
  320. let result = await networking.moveFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: overwrite, account: metadata.account)
  321. database.setMetadataCopyMove(ocId: metadata.ocId, serverUrlTo: "", overwrite: nil, status: global.metadataStatusNormal)
  322. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterCopyMoveFile, userInfo: ["serverUrl": metadata.serverUrl, "account": metadata.account, "dragdrop": false, "type": "move"])
  323. if result.error == .success {
  324. if metadata.directory {
  325. self.database.deleteDirectoryAndSubDirectory(serverUrl: utilityFileSystem.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName), account: result.account)
  326. } else {
  327. do {
  328. try FileManager.default.removeItem(atPath: self.utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId))
  329. } catch { }
  330. self.database.deleteVideo(metadata: metadata)
  331. self.database.deleteMetadataOcId(metadata.ocId)
  332. self.database.deleteLocalFileOcId(metadata.ocId)
  333. // LIVE PHOTO
  334. if let metadataLive = self.database.getMetadataLivePhoto(metadata: metadata) {
  335. do {
  336. try FileManager.default.removeItem(atPath: self.utilityFileSystem.getDirectoryProviderStorageOcId(metadataLive.ocId))
  337. } catch { }
  338. self.database.deleteVideo(metadata: metadataLive)
  339. self.database.deleteMetadataOcId(metadataLive.ocId)
  340. self.database.deleteLocalFileOcId(metadataLive.ocId)
  341. }
  342. }
  343. NotificationCenter.default.postOnMainThread(name: self.global.notificationCenterGetServerData, userInfo: ["serverUrl": metadata.serverUrl])
  344. NotificationCenter.default.postOnMainThread(name: self.global.notificationCenterGetServerData, userInfo: ["serverUrl": serverUrlTo])
  345. } else {
  346. NCContentPresenter().showError(error: result.error)
  347. }
  348. }
  349. }
  350. /// ------------------------ FAVORITE
  351. ///
  352. if let metadatasWaitFavorite = self.database.getMetadatas(predicate: NSPredicate(format: "status == %d", global.metadataStatusWaitFavorite), sortedByKeyPath: "serverUrl", ascending: true), !metadatasWaitFavorite.isEmpty {
  353. for metadata in metadatasWaitFavorite {
  354. let session = NCSession.Session(account: metadata.account, urlBase: metadata.urlBase, user: metadata.user, userId: metadata.userId)
  355. let fileName = utilityFileSystem.getFileNamePath(metadata.fileName, serverUrl: metadata.serverUrl, session: session)
  356. let error = await networking.setFavorite(fileName: fileName, favorite: metadata.favorite, account: metadata.account)
  357. if error == .success {
  358. database.setMetadataFavorite(ocId: metadata.ocId, favorite: nil, saveOldFavorite: nil, status: global.metadataStatusNormal)
  359. } else {
  360. let favorite = (metadata.storeFlag as? NSString)?.boolValue ?? false
  361. database.setMetadataFavorite(ocId: metadata.ocId, favorite: favorite, saveOldFavorite: nil, status: global.metadataStatusNormal)
  362. }
  363. NotificationCenter.default.postOnMainThread(name: self.global.notificationCenterFavoriteFile, userInfo: ["ocId": metadata.ocId, "serverUrl": metadata.serverUrl])
  364. }
  365. }
  366. /// ------------------------ RENAME
  367. ///
  368. if let metadatasWaitRename = self.database.getMetadatas(predicate: NSPredicate(format: "status == %d", global.metadataStatusWaitRename), sortedByKeyPath: "serverUrl", ascending: true), !metadatasWaitRename.isEmpty {
  369. for metadata in metadatasWaitRename {
  370. let serverUrlFileNameSource = metadata.serveUrlFileName
  371. let serverUrlFileNameDestination = metadata.serverUrl + "/" + metadata.fileName
  372. let result = await networking.moveFileOrFolder(serverUrlFileNameSource: serverUrlFileNameSource, serverUrlFileNameDestination: serverUrlFileNameDestination, overwrite: false, account: metadata.account)
  373. if result.error == .success {
  374. database.setMetadataServeUrlFileNameStatusNormal(ocId: metadata.ocId)
  375. } else {
  376. database.restoreMetadataFileName(ocId: metadata.ocId)
  377. }
  378. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterRenameFile, userInfo: ["serverUrl": metadata.serverUrl, "account": metadata.account, "error": result.error])
  379. }
  380. }
  381. /// ------------------------ DELETE
  382. ///
  383. if let metadatasWaitDelete = self.database.getMetadatas(predicate: NSPredicate(format: "status == %d", global.metadataStatusWaitDelete), sortedByKeyPath: "serverUrl", ascending: true), !metadatasWaitDelete.isEmpty {
  384. for metadata in metadatasWaitDelete {
  385. if networking.deleteFileOrFolderQueue.operations.filter({ ($0 as? NCOperationDeleteFileOrFolder)?.ocId == metadata.ocId }).isEmpty {
  386. networking.deleteFileOrFolderQueue.addOperation(NCOperationDeleteFileOrFolder(metadata: metadata))
  387. }
  388. }
  389. }
  390. return returnValue
  391. }
  392. // MARK: - Public
  393. func startProcess() {
  394. startTimer()
  395. startObserveTableMetadata()
  396. }
  397. func stopProcess() {
  398. timerProcess?.invalidate()
  399. timerProcess = nil
  400. notificationToken?.invalidate()
  401. notificationToken = nil
  402. }
  403. func refreshProcessingTask() async -> (counterDownloading: Int, counterUploading: Int) {
  404. await withCheckedContinuation { continuation in
  405. self.lockQueue.sync {
  406. guard !self.hasRun, networking.isOnline else { return }
  407. self.hasRun = true
  408. Task { [weak self] in
  409. guard let self else { return }
  410. let result = await self.start()
  411. self.hasRun = false
  412. continuation.resume(returning: result)
  413. }
  414. }
  415. }
  416. }
  417. func createProcessUploads(metadatas: [tableMetadata], verifyAlreadyExists: Bool = false, completion: @escaping (_ items: Int) -> Void = {_ in}) {
  418. var metadatasForUpload: [tableMetadata] = []
  419. for metadata in metadatas {
  420. if verifyAlreadyExists {
  421. if self.database.getMetadata(predicate: NSPredicate(format: "account == %@ && serverUrl == %@ && fileName == %@ && session != ''",
  422. metadata.account,
  423. metadata.serverUrl,
  424. metadata.fileName)) != nil {
  425. continue
  426. }
  427. }
  428. metadatasForUpload.append(metadata)
  429. }
  430. self.database.addMetadatas(metadatasForUpload)
  431. completion(metadatasForUpload.count)
  432. }
  433. }