NCNetworkingProcessUpload.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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 JGProgressHUD
  27. import RealmSwift
  28. class NCNetworkingProcessUpload: NSObject {
  29. public static let shared: NCNetworkingProcessUpload = {
  30. let instance = NCNetworkingProcessUpload()
  31. return instance
  32. }()
  33. private let appDelegate = (UIApplication.shared.delegate as? AppDelegate)!
  34. private lazy var rootViewController = appDelegate.window?.rootViewController
  35. private lazy var hudView = rootViewController?.view
  36. private var notificationToken: NotificationToken?
  37. private var timerProcess: Timer?
  38. private var pauseProcess: Bool = false
  39. private var hud: JGProgressHUD?
  40. func observeTableMetadata() {
  41. do {
  42. let realm = try Realm()
  43. let results = realm.objects(tableMetadata.self).filter("session != '' || sessionError != ''")
  44. notificationToken = results.observe { [weak self] (changes: RealmCollectionChange) in
  45. switch changes {
  46. case .initial:
  47. print("Initial")
  48. case .update(_, let deletions, let insertions, let modifications):
  49. if !deletions.isEmpty || !insertions.isEmpty || !modifications.isEmpty {
  50. self?.invalidateObserveTableMetadata()
  51. self?.start(completition: { items in
  52. print("[LOG] PROCESS-UPLOAD-OBSERVE \(items)")
  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 { items in
  83. print("[LOG] PROCESS-UPLOAD-TIMER \(items)")
  84. }
  85. }
  86. func start(completition: @escaping (_ items: Int) -> Void) {
  87. if appDelegate.account.isEmpty || pauseProcess {
  88. return completition(0)
  89. } else {
  90. pauseProcess = true
  91. }
  92. let applicationState = UIApplication.shared.applicationState
  93. let queue = DispatchQueue.global()
  94. var maxConcurrentOperationUpload = NCBrandOptions.shared.maxConcurrentOperationUpload
  95. if applicationState == .active {
  96. hud = JGProgressHUD()
  97. }
  98. queue.async {
  99. let metadatasUpload = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND status == %d", self.appDelegate.account, NCGlobal.shared.metadataStatusUploading))
  100. let isWiFi = NCNetworking.shared.networkReachability == NKCommon.TypeReachability.reachableEthernetOrWiFi
  101. var counterUpload = metadatasUpload.count
  102. let sessionSelectors = [NCGlobal.shared.selectorUploadFileNODelete, NCGlobal.shared.selectorUploadFile, NCGlobal.shared.selectorUploadAutoUpload, NCGlobal.shared.selectorUploadAutoUploadAll]
  103. // ** TEST ONLY ONE **
  104. // E2EE
  105. let uniqueMetadatas = metadatasUpload.unique(map: { $0.serverUrl })
  106. for metadata in uniqueMetadatas {
  107. if metadata.isDirectoryE2EE {
  108. self.pauseProcess = false
  109. return completition(counterUpload)
  110. }
  111. }
  112. // CHUNK
  113. if !metadatasUpload.filter({ $0.chunk > 0 }).isEmpty {
  114. self.pauseProcess = false
  115. return completition(counterUpload)
  116. }
  117. NCNetworking.shared.getOcIdInBackgroundSession(queue: queue, completion: { listOcId in
  118. for sessionSelector in sessionSelectors where counterUpload < maxConcurrentOperationUpload {
  119. let limit = maxConcurrentOperationUpload - counterUpload
  120. let metadatas = NCManageDatabase.shared.getAdvancedMetadatas(predicate: NSPredicate(format: "account == %@ AND sessionSelector == %@ AND status == %d", self.appDelegate.account, sessionSelector, NCGlobal.shared.metadataStatusWaitUpload), page: 1, limit: limit, sorted: "date", ascending: true)
  121. if !metadatas.isEmpty {
  122. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] PROCESS-UPLOAD find \(metadatas.count) items")
  123. }
  124. for metadata in metadatas where counterUpload < maxConcurrentOperationUpload {
  125. // Is already in upload background? skipped
  126. if listOcId.contains(metadata.ocId) {
  127. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Process auto upload skipped file: \(metadata.serverUrl)/\(metadata.fileNameView), because is already in session.")
  128. continue
  129. }
  130. // Session Extension ? skipped
  131. if metadata.session == NCNetworking.shared.sessionUploadBackgroundExtension {
  132. continue
  133. }
  134. let semaphore = DispatchSemaphore(value: 0)
  135. let cameraRoll = NCCameraRoll()
  136. cameraRoll.extractCameraRoll(from: metadata) { metadatas in
  137. if metadatas.isEmpty {
  138. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  139. }
  140. for metadata in metadatas where counterUpload < maxConcurrentOperationUpload {
  141. // isE2EE
  142. let isInDirectoryE2EE = metadata.isDirectoryE2EE
  143. // NO WiFi
  144. if !isWiFi && metadata.session == NCNetworking.shared.sessionUploadBackgroundWWan {
  145. continue
  146. }
  147. if applicationState != .active && (isInDirectoryE2EE || metadata.chunk > 0) {
  148. continue
  149. }
  150. if let metadata = NCManageDatabase.shared.setMetadataStatus(ocId: metadata.ocId, status: NCGlobal.shared.metadataStatusUploading) {
  151. NCNetworking.shared.upload(metadata: metadata, hudView: self.hudView, hud: self.hud)
  152. if isInDirectoryE2EE || metadata.chunk > 0 {
  153. maxConcurrentOperationUpload = 1
  154. }
  155. counterUpload += 1
  156. }
  157. }
  158. semaphore.signal()
  159. }
  160. semaphore.wait()
  161. }
  162. }
  163. // Update Badge Number
  164. NotificationCenter.default.post(
  165. name: Notification.Name(rawValue: NCGlobal.shared.notificationCenterUpdateBadgeNumber),
  166. object: nil)
  167. // No upload available ? --> Retry Upload in Error
  168. if counterUpload == 0 {
  169. let metadatas = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND status == %d", self.appDelegate.account, NCGlobal.shared.metadataStatusUploadError))
  170. for metadata in metadatas {
  171. // Verify QUOTA
  172. if metadata.sessionError.contains("\(NCGlobal.shared.errorQuota)") {
  173. NextcloudKit.shared.getUserProfile { _, userProfile, _, error in
  174. if error == .success, let userProfile, userProfile.quotaFree > 0, userProfile.quotaFree > metadata.size {
  175. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId,
  176. session: NCNetworking.shared.sessionUploadBackground,
  177. sessionError: "",
  178. status: NCGlobal.shared.metadataStatusWaitUpload)
  179. }
  180. }
  181. } else {
  182. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId,
  183. session: NCNetworking.shared.sessionUploadBackground,
  184. sessionError: "",
  185. status: NCGlobal.shared.metadataStatusWaitUpload)
  186. }
  187. }
  188. // verify delete Asset Local Identifiers in auto upload (DELETE Photos album)
  189. if applicationState == .active && metadatas.isEmpty {
  190. self.deleteAssetLocalIdentifiers(account: self.appDelegate.account) {
  191. self.pauseProcess = false
  192. }
  193. } else {
  194. self.pauseProcess = false
  195. }
  196. } else {
  197. self.pauseProcess = false
  198. }
  199. completition(counterUpload)
  200. })
  201. }
  202. }
  203. private func deleteAssetLocalIdentifiers(account: String, completition: @escaping () -> Void) {
  204. DispatchQueue.main.async {
  205. guard !self.appDelegate.isPasscodePresented else {
  206. return completition()
  207. }
  208. let metadatasSessionUpload = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND session CONTAINS[cd] %@", account, "upload"))
  209. if !metadatasSessionUpload.isEmpty { return completition() }
  210. let localIdentifiers = NCManageDatabase.shared.getAssetLocalIdentifiersUploaded(account: account)
  211. if localIdentifiers.isEmpty { return completition() }
  212. let assets = PHAsset.fetchAssets(withLocalIdentifiers: localIdentifiers, options: nil)
  213. PHPhotoLibrary.shared().performChanges({
  214. PHAssetChangeRequest.deleteAssets(assets as NSFastEnumeration)
  215. }, completionHandler: { _, _ in
  216. NCManageDatabase.shared.clearAssetLocalIdentifiers(localIdentifiers, account: self.appDelegate.account)
  217. completition()
  218. })
  219. }
  220. }
  221. // MARK: -
  222. func createProcessUploads(metadatas: [tableMetadata], verifyAlreadyExists: Bool = false, completion: @escaping (_ items: Int) -> Void) {
  223. var metadatasForUpload: [tableMetadata] = []
  224. for metadata in metadatas {
  225. if verifyAlreadyExists {
  226. if NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ && serverUrl == %@ && fileName == %@ && session != ''", metadata.account, metadata.serverUrl, metadata.fileName)) != nil {
  227. continue
  228. }
  229. }
  230. metadatasForUpload.append(metadata)
  231. }
  232. NCManageDatabase.shared.addMetadatas(metadatasForUpload)
  233. completion(metadatasForUpload.count)
  234. }
  235. // MARK: -
  236. func verifyUploadZombie() {
  237. Task {
  238. let utilityFileSystem = NCUtilityFileSystem()
  239. var notificationCenter: Bool = false
  240. // selectorUploadFileShareExtension (FOREGROUND)
  241. if let results = NCManageDatabase.shared.getResultsMetadatas(predicate: NSPredicate(format: "session == %@ AND sessionSelector == %@", NextcloudKit.shared.nkCommonInstance.sessionIdentifierUpload, NCGlobal.shared.selectorUploadFileShareExtension)) {
  242. for metadata in results {
  243. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  244. utilityFileSystem.removeFile(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId))
  245. notificationCenter = true
  246. }
  247. }
  248. // metadataStatusUploading (FOREGROUND)
  249. if let results = NCManageDatabase.shared.getResultsMetadatas(predicate: NSPredicate(format: "session == %@ AND status == %d", NextcloudKit.shared.nkCommonInstance.sessionIdentifierUpload, NCGlobal.shared.metadataStatusUploading)) {
  250. if results.isEmpty { NCNetworking.shared.transferInForegorund = nil }
  251. for metadata in results {
  252. let fileNameLocalPath = utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  253. if NCNetworking.shared.uploadRequest[fileNameLocalPath] == nil {
  254. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId,
  255. status: NCGlobal.shared.metadataStatusWaitUpload)
  256. notificationCenter = true
  257. }
  258. }
  259. }
  260. // metadataStatusDownloading (FOREGROUND)
  261. if let results = NCManageDatabase.shared.getResultsMetadatas(predicate: NSPredicate(format: "session == %@ AND status == %d", NextcloudKit.shared.nkCommonInstance.sessionIdentifierDownload, NCGlobal.shared.metadataStatusDownloading)) {
  262. for metadata in results {
  263. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId,
  264. session: "",
  265. sessionError: "",
  266. selector: "",
  267. status: NCGlobal.shared.metadataStatusNormal,
  268. errorCode: 0)
  269. notificationCenter = true
  270. }
  271. }
  272. // metadataStatusUploading (BACKGROUND)
  273. let results = 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))
  274. for metadata in results {
  275. var taskUpload: URLSessionTask?
  276. var session: URLSession?
  277. if metadata.session == NCNetworking.shared.sessionUploadBackground {
  278. session = NCNetworking.shared.sessionManagerUploadBackground
  279. } else if metadata.session == NCNetworking.shared.sessionUploadBackgroundWWan {
  280. session = NCNetworking.shared.sessionManagerUploadBackgroundWWan
  281. }
  282. if let tasks = await session?.allTasks {
  283. for task in tasks {
  284. if task.taskIdentifier == metadata.sessionTaskIdentifier { taskUpload = task }
  285. }
  286. if taskUpload == nil, let metadata = NCManageDatabase.shared.getResultMetadata(predicate: NSPredicate(format: "ocId == %@ AND status == %d", metadata.ocId, NCGlobal.shared.metadataStatusUploading)) {
  287. NCManageDatabase.shared.setMetadataSession(ocId: metadata.ocId,
  288. session: NCNetworking.shared.sessionUploadBackground,
  289. sessionError: "",
  290. status: NCGlobal.shared.metadataStatusWaitUpload)
  291. notificationCenter = true
  292. }
  293. }
  294. }
  295. if notificationCenter {
  296. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource)
  297. }
  298. }
  299. }
  300. }