NCNetworkingProcessUpload.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. //
  2. // NCNetworkingProcessUpload.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. class NCNetworkingProcessUpload: NSObject {
  27. public static let shared: NCNetworkingProcessUpload = {
  28. let instance = NCNetworkingProcessUpload()
  29. return instance
  30. }()
  31. var timerProcess: Timer?
  32. func startTimer() {
  33. timerProcess?.invalidate()
  34. timerProcess = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(processTimer), userInfo: nil, repeats: true)
  35. }
  36. func stopTimer() {
  37. timerProcess?.invalidate()
  38. }
  39. @objc func processTimer() {
  40. process { _ in }
  41. }
  42. func process(completition: @escaping (_ items: Int) -> Void) {
  43. guard let account = NCManageDatabase.shared.getActiveAccount() else { return }
  44. stopTimer()
  45. let applicationState = UIApplication.shared.applicationState
  46. let queue = DispatchQueue.global()
  47. var maxConcurrentOperationUpload = 10
  48. queue.async {
  49. let metadatasUpload = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "status == %d OR status == %d", NCGlobal.shared.metadataStatusInUpload, NCGlobal.shared.metadataStatusUploading))
  50. let isWiFi = NCNetworking.shared.networkReachability == NKCommon.typeReachability.reachableEthernetOrWiFi
  51. var counterUpload: Int = 0
  52. let sessionSelectors = [NCGlobal.shared.selectorUploadFileNODelete, NCGlobal.shared.selectorUploadFile, NCGlobal.shared.selectorUploadAutoUpload, NCGlobal.shared.selectorUploadAutoUploadAll]
  53. counterUpload = metadatasUpload.count
  54. print("[LOG] PROCESS-UPLOAD \(counterUpload)")
  55. // Update Badge
  56. let counterBadge = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "status == %d OR status == %d OR status == %d", NCGlobal.shared.metadataStatusWaitUpload, NCGlobal.shared.metadataStatusInUpload, NCGlobal.shared.metadataStatusUploading))
  57. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUpdateBadgeNumber, userInfo: ["counter":counterBadge.count])
  58. NCNetworking.shared.getOcIdInBackgroundSession(queue: queue, completion: { listOcId in
  59. for sessionSelector in sessionSelectors where counterUpload < maxConcurrentOperationUpload {
  60. let limit = maxConcurrentOperationUpload - counterUpload
  61. let metadatas = NCManageDatabase.shared.getAdvancedMetadatas(predicate: NSPredicate(format: "sessionSelector == %@ AND status == %d", sessionSelector, NCGlobal.shared.metadataStatusWaitUpload), page: 1, limit: limit, sorted: "date", ascending: true)
  62. if metadatas.count > 0 {
  63. NKCommon.shared.writeLog("[INFO] PROCESS-UPLOAD find \(metadatas.count) items")
  64. }
  65. for metadata in metadatas where counterUpload < maxConcurrentOperationUpload {
  66. // Different account
  67. if account.account != metadata.account {
  68. NKCommon.shared.writeLog("[INFO] Process auto upload skipped file: \(metadata.serverUrl)/\(metadata.fileNameView) on account: \(metadata.account), because the actual account is \(account.account).")
  69. continue
  70. }
  71. // Is already in upload background? skipped
  72. if listOcId.contains(metadata.ocId) {
  73. NKCommon.shared.writeLog("[INFO] Process auto upload skipped file: \(metadata.serverUrl)/\(metadata.fileNameView), because is already in session.")
  74. continue
  75. }
  76. // Chunk or E2EE ... only one ? skipped
  77. if metadatasUpload.filter({ $0.chunk || $0.e2eEncrypted }).count > 0 {
  78. continue
  79. }
  80. // Session Extension ? skipped
  81. if metadata.session == NCNetworking.shared.sessionIdentifierBackgroundExtension {
  82. continue
  83. }
  84. let semaphore = DispatchSemaphore(value: 0)
  85. NCUtility.shared.extractFiles(from: metadata) { metadatas in
  86. if metadatas.isEmpty {
  87. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  88. }
  89. for metadata in metadatas where counterUpload < maxConcurrentOperationUpload {
  90. // NO WiFi
  91. if !isWiFi && metadata.session == NCNetworking.shared.sessionIdentifierBackgroundWWan {
  92. continue
  93. }
  94. // NO E2EE, CHUCK in background
  95. if applicationState != .active && (metadata.e2eEncrypted || metadata.chunk) {
  96. continue
  97. }
  98. if let metadata = NCManageDatabase.shared.setMetadataStatus(ocId: metadata.ocId, status: NCGlobal.shared.metadataStatusInUpload) {
  99. NCNetworking.shared.upload(metadata: metadata)
  100. if metadata.e2eEncrypted || metadata.chunk {
  101. maxConcurrentOperationUpload = 1
  102. }
  103. counterUpload += 1
  104. }
  105. }
  106. semaphore.signal()
  107. }
  108. semaphore.wait()
  109. }
  110. }
  111. // No upload available ? --> Retry Upload in Error
  112. if counterUpload == 0 {
  113. let metadatas = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "status == %d", NCGlobal.shared.metadataStatusUploadError))
  114. for metadata in metadatas {
  115. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: NCNetworking.shared.sessionIdentifierBackground, sessionError: "", sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusWaitUpload)
  116. }
  117. }
  118. // verify delete Asset Local Identifiers in auto upload (DELETE Photos album)
  119. DispatchQueue.main.async {
  120. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  121. if applicationState == .active && counterUpload == 0 && !appDelegate.isPasscodePresented() {
  122. self.deleteAssetLocalIdentifiers(account: account.account) {
  123. self.startTimer()
  124. }
  125. } else if applicationState == .active {
  126. self.startTimer()
  127. }
  128. completition(counterUpload)
  129. }
  130. })
  131. }
  132. }
  133. private func deleteAssetLocalIdentifiers(account: String, completition: @escaping () -> Void) {
  134. if UIApplication.shared.applicationState != .active {
  135. completition()
  136. return
  137. }
  138. let metadatasSessionUpload = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND session CONTAINS[cd] %@", account, "upload"))
  139. if !metadatasSessionUpload.isEmpty {
  140. completition()
  141. return
  142. }
  143. let localIdentifiers = NCManageDatabase.shared.getAssetLocalIdentifiersUploaded(account: account)
  144. if localIdentifiers.isEmpty {
  145. completition()
  146. return
  147. }
  148. let assets = PHAsset.fetchAssets(withLocalIdentifiers: localIdentifiers, options: nil)
  149. PHPhotoLibrary.shared().performChanges({
  150. PHAssetChangeRequest.deleteAssets(assets as NSFastEnumeration)
  151. }, completionHandler: { _, _ in
  152. DispatchQueue.main.async {
  153. NCManageDatabase.shared.clearAssetLocalIdentifiers(localIdentifiers, account: account)
  154. completition()
  155. }
  156. })
  157. }
  158. // MARK: -
  159. func createProcessUploads(metadatas: [tableMetadata], verifyAlreadyExists: Bool = false, completion: @escaping (_ items: Int) -> Void) {
  160. var metadatasForUpload: [tableMetadata] = []
  161. for metadata in metadatas {
  162. if verifyAlreadyExists {
  163. if NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ && serverUrl == %@ && fileName == %@ && session != ''", metadata.account, metadata.serverUrl, metadata.fileName)) != nil {
  164. continue
  165. }
  166. }
  167. metadatasForUpload.append(metadata)
  168. }
  169. NCManageDatabase.shared.addMetadatas(metadatasForUpload)
  170. completion(metadatasForUpload.count)
  171. }
  172. // MARK: -
  173. func verifyUploadZombie() {
  174. var session: URLSession?
  175. // remove leaning upload share extension
  176. let metadatasUploadShareExtension = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "session == %@ AND sessionSelector == %@", NKCommon.shared.sessionIdentifierUpload, NCGlobal.shared.selectorUploadFileShareExtension))
  177. for metadata in metadatasUploadShareExtension {
  178. let path = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId)!
  179. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  180. NCManageDatabase.shared.deleteChunks(account: metadata.account, ocId: metadata.ocId)
  181. NCUtilityFileSystem.shared.deleteFile(filePath: path)
  182. }
  183. // verify metadataStatusInUpload (BACKGROUND)
  184. let metadatasInUploadBackground = NCManageDatabase.shared.getMetadatas(
  185. predicate: NSPredicate(
  186. format: "(session == %@ OR session == %@ OR session == %@) AND status == %d AND sessionTaskIdentifier == 0",
  187. NCNetworking.shared.sessionIdentifierBackground,
  188. NCNetworking.shared.sessionIdentifierBackgroundExtension,
  189. NCNetworking.shared.sessionIdentifierBackgroundWWan,
  190. NCGlobal.shared.metadataStatusInUpload))
  191. for metadata in metadatasInUploadBackground {
  192. DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
  193. if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "ocId == %@ AND status == %d AND sessionTaskIdentifier == 0", metadata.ocId, NCGlobal.shared.metadataStatusInUpload)) {
  194. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: NCNetworking.shared.sessionIdentifierBackground, sessionError: "", sessionSelector: nil, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusWaitUpload)
  195. }
  196. }
  197. }
  198. // metadataStatusUploading (BACKGROUND)
  199. let metadatasUploadingBackground = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "(session == %@ OR session == %@ OR session == %@) AND status == %d", NCNetworking.shared.sessionIdentifierBackground, NCNetworking.shared.sessionIdentifierBackgroundWWan, NCNetworking.shared.sessionIdentifierBackgroundExtension, NCGlobal.shared.metadataStatusUploading))
  200. for metadata in metadatasUploadingBackground {
  201. if metadata.session == NCNetworking.shared.sessionIdentifierBackground {
  202. session = NCNetworking.shared.sessionManagerBackground
  203. } else if metadata.session == NCNetworking.shared.sessionIdentifierBackgroundWWan {
  204. session = NCNetworking.shared.sessionManagerBackgroundWWan
  205. }
  206. var taskUpload: URLSessionTask?
  207. session?.getAllTasks(completionHandler: { tasks in
  208. for task in tasks {
  209. if task.taskIdentifier == metadata.sessionTaskIdentifier {
  210. taskUpload = task
  211. }
  212. }
  213. if taskUpload == nil {
  214. if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "ocId == %@ AND status == %d", metadata.ocId, NCGlobal.shared.metadataStatusUploading)) {
  215. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: NCNetworking.shared.sessionIdentifierBackground, sessionError: "", sessionSelector: nil, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusWaitUpload)
  216. }
  217. }
  218. })
  219. }
  220. // metadataStatusUploading OR metadataStatusInUpload (FOREGROUND)
  221. let metadatasUploading = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "session == %@ AND (status == %d OR status == %d)", NKCommon.shared.sessionIdentifierUpload, NCGlobal.shared.metadataStatusUploading, NCGlobal.shared.metadataStatusInUpload))
  222. for metadata in metadatasUploading {
  223. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  224. if NCNetworking.shared.uploadRequest[fileNameLocalPath] == nil {
  225. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: nil, sessionError: "", sessionSelector: nil, sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusWaitUpload)
  226. }
  227. }
  228. // download
  229. let metadatasDownload = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "session == %@", NKCommon.shared.sessionIdentifierDownload))
  230. for metadata in metadatasDownload {
  231. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId, session: "", sessionError: "", sessionSelector: "", sessionTaskIdentifier: 0, status: NCGlobal.shared.metadataStatusNormal)
  232. }
  233. }
  234. }