NCNetworkingProcess.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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 JGProgressHUD
  27. import RealmSwift
  28. class NCNetworkingProcess: NSObject {
  29. public static let shared: NCNetworkingProcess = {
  30. let instance = NCNetworkingProcess()
  31. return instance
  32. }()
  33. private let appDelegate = (UIApplication.shared.delegate as? AppDelegate)!
  34. private let utilityFileSystem = NCUtilityFileSystem()
  35. private lazy var rootViewController = appDelegate.window?.rootViewController
  36. private lazy var hudView = rootViewController?.view
  37. private var notificationToken: NotificationToken?
  38. private var timerProcess: Timer?
  39. private var pauseProcess: Bool = false
  40. private var hud: JGProgressHUD?
  41. func observeTableMetadata() {
  42. do {
  43. let realm = try Realm()
  44. let results = realm.objects(tableMetadata.self).filter("session != '' || sessionError != ''")
  45. notificationToken = results.observe { [weak self] (changes: RealmCollectionChange) in
  46. switch changes {
  47. case .initial:
  48. break
  49. case .update(_, let deletions, let insertions, let modifications):
  50. if !deletions.isEmpty || !insertions.isEmpty || !modifications.isEmpty {
  51. self?.invalidateObserveTableMetadata()
  52. self?.start(completition: { _, _ in
  53. DispatchQueue.main.async {
  54. self?.observeTableMetadata()
  55. }
  56. })
  57. }
  58. case .error(let error):
  59. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to TableMetadata: \(error)")
  60. }
  61. }
  62. } catch let error as NSError {
  63. NSLog("Could not access database: ", error)
  64. }
  65. }
  66. func invalidateObserveTableMetadata() {
  67. notificationToken?.invalidate()
  68. notificationToken = nil
  69. }
  70. func startTimer() {
  71. DispatchQueue.main.async {
  72. self.timerProcess?.invalidate()
  73. self.timerProcess = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(self.processTimer), userInfo: nil, repeats: true)
  74. }
  75. }
  76. func stopTimer() {
  77. DispatchQueue.main.async {
  78. self.timerProcess?.invalidate()
  79. }
  80. }
  81. @objc private func processTimer() {
  82. start { itemsDownload, itemsUpload in
  83. print("[LOG] PROCESS (TIMER) Download: \(itemsDownload) Upload: \(itemsUpload)")
  84. NotificationCenter.default.post(name: Notification.Name(rawValue: NCGlobal.shared.notificationCenterUpdateBadgeNumber), object: nil)
  85. }
  86. }
  87. func start(completition: @escaping (_ itemsDownload: Int, _ itemsUpload: Int) -> Void) {
  88. if appDelegate.account.isEmpty || pauseProcess {
  89. return completition(0, 0)
  90. } else {
  91. pauseProcess = true
  92. }
  93. let applicationState = UIApplication.shared.applicationState
  94. let queue = DispatchQueue.global()
  95. let maxConcurrentOperationDownload = NCBrandOptions.shared.maxConcurrentOperationDownload
  96. var maxConcurrentOperationUpload = NCBrandOptions.shared.maxConcurrentOperationUpload
  97. if applicationState == .active {
  98. hud = JGProgressHUD()
  99. }
  100. queue.async {
  101. let metadatasDownloading = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND status == %d", self.appDelegate.account, NCGlobal.shared.metadataStatusDownloading))
  102. let metadatasUploading = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND status == %d", self.appDelegate.account, NCGlobal.shared.metadataStatusUploading))
  103. let isWiFi = NCNetworking.shared.networkReachability == NKCommon.TypeReachability.reachableEthernetOrWiFi
  104. var counterDownload = metadatasDownloading.count
  105. var counterUpload = metadatasUploading.count
  106. let semaphore = DispatchSemaphore(value: 0)
  107. // DOWNLOAD
  108. //
  109. let limitDownload = maxConcurrentOperationDownload - counterDownload
  110. let metadatasDownload = NCManageDatabase.shared.getAdvancedMetadatas(predicate: NSPredicate(format: "account == %@ AND session == %@ AND status == %d", self.appDelegate.account, NCNetworking.shared.sessionDownloadBackground, NCGlobal.shared.metadataStatusWaitDownload), page: 1, limit: limitDownload, sorted: "sessionDate", ascending: true)
  111. for metadata in metadatasDownload where counterDownload < maxConcurrentOperationDownload {
  112. NCNetworking.shared.download(metadata: metadata, withNotificationProgressTask: true) {
  113. } completion: { _, _ in
  114. counterDownload += 1
  115. semaphore.signal()
  116. }
  117. semaphore.wait()
  118. }
  119. if counterDownload == 0 {
  120. let metadatasDownloadInError: [tableMetadata] = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND session == %@ AND status == %d", self.appDelegate.account, NCNetworking.shared.sessionDownloadBackground, NCGlobal.shared.metadataStatusDownloadError), sorted: "sessionDate", ascending: true) ?? []
  121. for metadata in metadatasDownloadInError {
  122. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId,
  123. sessionError: "",
  124. status: NCGlobal.shared.metadataStatusWaitDownload)
  125. }
  126. }
  127. // UPLOAD
  128. //
  129. // ** TEST ONLY ONE **
  130. // E2EE
  131. let uniqueMetadatas = metadatasUploading.unique(map: { $0.serverUrl })
  132. for metadata in uniqueMetadatas {
  133. if metadata.isDirectoryE2EE {
  134. self.pauseProcess = false
  135. return completition(counterDownload, counterUpload)
  136. }
  137. }
  138. // CHUNK
  139. if !metadatasUploading.filter({ $0.chunk > 0 }).isEmpty {
  140. self.pauseProcess = false
  141. return completition(counterDownload, counterUpload)
  142. }
  143. NCNetworking.shared.getUploadBackgroundSession(queue: queue, completion: { filesNameLocalPath in
  144. let sessionUploadSelectors = [NCGlobal.shared.selectorUploadFileNODelete, NCGlobal.shared.selectorUploadFile, NCGlobal.shared.selectorUploadAutoUpload, NCGlobal.shared.selectorUploadAutoUploadAll]
  145. for sessionSelector in sessionUploadSelectors where counterUpload < maxConcurrentOperationUpload {
  146. let limitUpload = maxConcurrentOperationUpload - counterUpload
  147. let metadatasUpload = NCManageDatabase.shared.getAdvancedMetadatas(predicate: NSPredicate(format: "account == %@ AND sessionSelector == %@ AND status == %d", self.appDelegate.account, sessionSelector, NCGlobal.shared.metadataStatusWaitUpload), page: 1, limit: limitUpload, sorted: "sessionDate", ascending: true)
  148. if !metadatasUpload.isEmpty {
  149. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] PROCESS (UPLOAD) find \(metadatasUpload.count) items")
  150. }
  151. for metadata in metadatasUpload where counterUpload < maxConcurrentOperationUpload {
  152. // Is already in upload background? skipped
  153. let fileNameLocalPath = self.utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  154. if filesNameLocalPath.contains(fileNameLocalPath) {
  155. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Process auto upload skipped file: \(metadata.serverUrl)/\(metadata.fileNameView), because is already in session.")
  156. continue
  157. }
  158. // Session Extension ? skipped
  159. if metadata.session == NCNetworking.shared.sessionUploadBackgroundExtension {
  160. continue
  161. }
  162. let cameraRoll = NCCameraRoll()
  163. cameraRoll.extractCameraRoll(from: metadata) { metadatas in
  164. if metadatas.isEmpty {
  165. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  166. }
  167. for metadata in metadatas where counterUpload < maxConcurrentOperationUpload {
  168. // isE2EE
  169. let isInDirectoryE2EE = metadata.isDirectoryE2EE
  170. // NO WiFi
  171. if !isWiFi && metadata.session == NCNetworking.shared.sessionUploadBackgroundWWan {
  172. continue
  173. }
  174. if applicationState != .active && (isInDirectoryE2EE || metadata.chunk > 0) {
  175. continue
  176. }
  177. if let metadata = NCManageDatabase.shared.setMetadataStatus(ocId: metadata.ocId, status: NCGlobal.shared.metadataStatusUploading) {
  178. NCNetworking.shared.upload(metadata: metadata, hudView: self.hudView, hud: self.hud)
  179. if isInDirectoryE2EE || metadata.chunk > 0 {
  180. maxConcurrentOperationUpload = 1
  181. }
  182. counterUpload += 1
  183. }
  184. }
  185. semaphore.signal()
  186. }
  187. semaphore.wait()
  188. }
  189. }
  190. // No upload available ? --> Retry Upload in Error
  191. if counterUpload == 0 {
  192. let metadatasUploadInError: [tableMetadata] = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND status == %d", self.appDelegate.account, NCGlobal.shared.metadataStatusUploadError), sorted: "sessionDate", ascending: true) ?? []
  193. for metadata in metadatasUploadInError {
  194. // Verify QUOTA
  195. if metadata.sessionError.contains("\(NCGlobal.shared.errorQuota)") {
  196. NextcloudKit.shared.getUserProfile { _, userProfile, _, error in
  197. if error == .success, let userProfile, userProfile.quotaFree > 0, userProfile.quotaFree > metadata.size {
  198. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId,
  199. session: NCNetworking.shared.sessionUploadBackground,
  200. sessionError: "",
  201. status: NCGlobal.shared.metadataStatusWaitUpload)
  202. }
  203. }
  204. } else {
  205. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId,
  206. session: NCNetworking.shared.sessionUploadBackground,
  207. sessionError: "",
  208. status: NCGlobal.shared.metadataStatusWaitUpload)
  209. }
  210. }
  211. // verify delete Asset Local Identifiers in auto upload (DELETE Photos album)
  212. if applicationState == .active && metadatasUploadInError.isEmpty {
  213. self.deleteAssetLocalIdentifiers(account: self.appDelegate.account) {
  214. self.pauseProcess = false
  215. }
  216. } else {
  217. self.pauseProcess = false
  218. }
  219. } else {
  220. self.pauseProcess = false
  221. }
  222. completition(counterDownload, counterUpload)
  223. })
  224. }
  225. }
  226. private func deleteAssetLocalIdentifiers(account: String, completition: @escaping () -> Void) {
  227. DispatchQueue.main.async {
  228. guard !NCPasscode.shared.isPasscodePresented else {
  229. return completition()
  230. }
  231. let metadatasSessionUpload = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND session CONTAINS[cd] %@", account, "upload"))
  232. if !metadatasSessionUpload.isEmpty { return completition() }
  233. let localIdentifiers = NCManageDatabase.shared.getAssetLocalIdentifiersUploaded(account: account)
  234. if localIdentifiers.isEmpty { return completition() }
  235. let assets = PHAsset.fetchAssets(withLocalIdentifiers: localIdentifiers, options: nil)
  236. PHPhotoLibrary.shared().performChanges({
  237. PHAssetChangeRequest.deleteAssets(assets as NSFastEnumeration)
  238. }, completionHandler: { _, _ in
  239. NCManageDatabase.shared.clearAssetLocalIdentifiers(localIdentifiers, account: self.appDelegate.account)
  240. completition()
  241. })
  242. }
  243. }
  244. // MARK: -
  245. func createProcessUploads(metadatas: [tableMetadata], verifyAlreadyExists: Bool = false, completion: @escaping (_ items: Int) -> Void = {_ in}) {
  246. var metadatasForUpload: [tableMetadata] = []
  247. for metadata in metadatas {
  248. if verifyAlreadyExists {
  249. if NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ && serverUrl == %@ && fileName == %@ && session != ''", metadata.account, metadata.serverUrl, metadata.fileName)) != nil {
  250. continue
  251. }
  252. }
  253. metadatasForUpload.append(metadata)
  254. }
  255. NCManageDatabase.shared.addMetadatas(metadatasForUpload)
  256. completion(metadatasForUpload.count)
  257. }
  258. // MARK: -
  259. func verifyUploadZombie() {
  260. Task {
  261. var notificationCenter: Bool = false
  262. // selectorUploadFileShareExtension (FOREGROUND)
  263. if let results = NCManageDatabase.shared.getResultsMetadatas(predicate: NSPredicate(format: "session == %@ AND sessionSelector == %@", NextcloudKit.shared.nkCommonInstance.sessionIdentifierUpload, NCGlobal.shared.selectorUploadFileShareExtension)) {
  264. for metadata in results {
  265. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  266. utilityFileSystem.removeFile(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId))
  267. notificationCenter = true
  268. }
  269. }
  270. // metadataStatusUploading (FOREGROUND)
  271. if let results = NCManageDatabase.shared.getResultsMetadatas(predicate: NSPredicate(format: "session == %@ AND status == %d", NextcloudKit.shared.nkCommonInstance.sessionIdentifierUpload, NCGlobal.shared.metadataStatusUploading)) {
  272. if results.isEmpty { NCNetworking.shared.transferInForegorund = nil }
  273. for metadata in results {
  274. let fileNameLocalPath = utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  275. if NCNetworking.shared.uploadRequest[fileNameLocalPath] == nil {
  276. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId,
  277. status: NCGlobal.shared.metadataStatusWaitUpload)
  278. notificationCenter = true
  279. }
  280. }
  281. }
  282. // metadataStatusDownloading (FOREGROUND)
  283. if let results = NCManageDatabase.shared.getResultsMetadatas(predicate: NSPredicate(format: "session == %@ AND status == %d", NextcloudKit.shared.nkCommonInstance.sessionIdentifierDownload, NCGlobal.shared.metadataStatusDownloading)) {
  284. for metadata in results {
  285. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId,
  286. session: "",
  287. sessionError: "",
  288. selector: "",
  289. status: NCGlobal.shared.metadataStatusNormal)
  290. notificationCenter = true
  291. }
  292. }
  293. // metadataStatusUploading (BACKGROUND)
  294. let resultsUpload = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "(session == %@ OR session == %@ OR session == %@) AND status == %d", NCNetworking.shared.sessionUploadBackground, NCNetworking.shared.sessionUploadBackgroundWWan, NCNetworking.shared.sessionUploadBackgroundExtension, NCGlobal.shared.metadataStatusUploading))
  295. for metadata in resultsUpload {
  296. var taskUpload: URLSessionTask?
  297. var session: URLSession?
  298. if metadata.session == NCNetworking.shared.sessionUploadBackground {
  299. session = NCNetworking.shared.sessionManagerUploadBackground
  300. } else if metadata.session == NCNetworking.shared.sessionUploadBackgroundWWan {
  301. session = NCNetworking.shared.sessionManagerUploadBackgroundWWan
  302. }
  303. if let tasks = await session?.allTasks {
  304. for task in tasks {
  305. if task.taskIdentifier == metadata.sessionTaskIdentifier { taskUpload = task }
  306. }
  307. if taskUpload == nil, let metadata = NCManageDatabase.shared.getResultMetadata(predicate: NSPredicate(format: "ocId == %@ AND status == %d", metadata.ocId, NCGlobal.shared.metadataStatusUploading)) {
  308. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId,
  309. session: NCNetworking.shared.sessionUploadBackground,
  310. sessionError: "",
  311. status: NCGlobal.shared.metadataStatusWaitUpload)
  312. notificationCenter = true
  313. }
  314. }
  315. }
  316. // metadataStatusDowloading (BACKGROUND)
  317. let resultsDownload = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "session == %@ AND status == %d", NCNetworking.shared.sessionDownloadBackground, NCGlobal.shared.metadataStatusDownloading))
  318. for metadata in resultsDownload {
  319. var taskDownload: URLSessionTask?
  320. let session: URLSession? = NCNetworking.shared.sessionManagerDownloadBackground
  321. if let tasks = await session?.allTasks {
  322. for task in tasks {
  323. if task.taskIdentifier == metadata.sessionTaskIdentifier { taskDownload = task }
  324. }
  325. if taskDownload == nil, let metadata = NCManageDatabase.shared.getResultMetadata(predicate: NSPredicate(format: "ocId == %@ AND status == %d", metadata.ocId, NCGlobal.shared.metadataStatusDownloading)) {
  326. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId,
  327. session: NCNetworking.shared.sessionDownloadBackground,
  328. sessionError: "",
  329. status: NCGlobal.shared.metadataStatusWaitDownload)
  330. notificationCenter = true
  331. }
  332. }
  333. }
  334. if notificationCenter {
  335. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource)
  336. }
  337. }
  338. }
  339. }