NCNetworkingProcessUpload.swift 14 KB

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