NCAutoUpload.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. //
  2. // NCAutoUpload.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 27/01/21.
  6. // Copyright © 2021 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 CoreLocation
  25. import NCCommunication
  26. import Photos
  27. import NextcloudKit
  28. import Queuer
  29. class NCAutoUpload: NSObject {
  30. @objc static let shared: NCAutoUpload = {
  31. let instance = NCAutoUpload()
  32. return instance
  33. }()
  34. private var endForAssetToUpload: Bool = false
  35. // MARK: -
  36. @objc func initAutoUpload(viewController: UIViewController?, completion: @escaping (_ items: Int) -> Void) {
  37. guard let account = NCManageDatabase.shared.getActiveAccount(), account.autoUpload else {
  38. completion(0)
  39. return
  40. }
  41. NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: viewController) { hasPermission in
  42. guard hasPermission else {
  43. NCManageDatabase.shared.setAccountAutoUploadProperty("autoUpload", state: false)
  44. completion(0)
  45. return
  46. }
  47. self.uploadAssetsNewAndFull(viewController: viewController, selector: NCGlobal.shared.selectorUploadAutoUpload, log: "Init Auto Upload") { items in
  48. completion(items)
  49. }
  50. }
  51. }
  52. @objc func autoUploadFullPhotos(viewController: UIViewController?, log: String) {
  53. NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: viewController) { hasPermission in
  54. guard hasPermission else { return }
  55. #if !EXTENSION
  56. NCContentPresenter.shared.messageNotification("_attention_", description: "_create_full_upload_", delay: NCGlobal.shared.dismissAfterSecondLong, type: .info, errorCode: NCGlobal.shared.errorNoError, priority: .max)
  57. NCActivityIndicator.shared.start()
  58. #endif
  59. self.uploadAssetsNewAndFull(viewController: viewController, selector: NCGlobal.shared.selectorUploadAutoUploadAll, log: log) { _ in
  60. #if !EXTENSION
  61. NCActivityIndicator.shared.stop()
  62. #endif
  63. }
  64. }
  65. }
  66. private func uploadAssetsNewAndFull(viewController: UIViewController?, selector: String, log: String, completion: @escaping (_ items: Int) -> Void) {
  67. guard let account = NCManageDatabase.shared.getActiveAccount() else {
  68. completion(0)
  69. return
  70. }
  71. DispatchQueue.global(qos: .background).async {
  72. let autoUploadPath = NCManageDatabase.shared.getAccountAutoUploadPath(urlBase: account.urlBase, account: account.account)
  73. var metadatas: [tableMetadata] = []
  74. self.getCameraRollAssets(viewController: viewController, account: account, selector: selector, alignPhotoLibrary: false) { assets in
  75. guard let assets = assets, !assets.isEmpty else {
  76. #if EXTENSION_WIDGET
  77. NKCommon.shared.writeLog("Automatic upload widget, no new assets found [" + log + "]")
  78. #else
  79. NCCommunicationCommon.shared.writeLog("Automatic upload, no new assets found [" + log + "]")
  80. #endif
  81. completion(0)
  82. return
  83. }
  84. #if EXTENSION_WIDGET
  85. NKCommon.shared.writeLog("Automatic upload widget, new \(assets.count) assets found [" + log + "]")
  86. #else
  87. NCCommunicationCommon.shared.writeLog("Automatic upload, new \(assets.count) assets found [" + log + "]")
  88. #endif
  89. // Create the folder for auto upload & if request the subfolders
  90. if !NCNetworking.shared.createFolder(assets: assets, selector: selector, useSubFolder: account.autoUploadCreateSubfolder, account: account.account, urlBase: account.urlBase) {
  91. #if !EXTENSION
  92. if selector == NCGlobal.shared.selectorUploadAutoUploadAll {
  93. NCContentPresenter.shared.messageNotification("_error_", description: "_error_createsubfolders_upload_", delay: NCGlobal.shared.dismissAfterSecond, type: .error, errorCode: NCGlobal.shared.errorInternalError, priority: .max)
  94. }
  95. #endif
  96. return completion(0)
  97. }
  98. self.endForAssetToUpload = false
  99. for asset in assets {
  100. var livePhoto = false
  101. var session: String = ""
  102. guard let assetDate = asset.creationDate else { continue }
  103. let assetMediaType = asset.mediaType
  104. var serverUrl: String = ""
  105. let fileName = CCUtility.createFileName(asset.value(forKey: "filename") as? String, fileDate: assetDate, fileType: assetMediaType, keyFileName: NCGlobal.shared.keyFileNameAutoUploadMask, keyFileNameType: NCGlobal.shared.keyFileNameAutoUploadType, keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginalAutoUpload, forcedNewFileName: false)!
  106. let formatter = DateFormatter()
  107. formatter.dateFormat = "yyyy"
  108. let yearString = formatter.string(from: assetDate)
  109. formatter.dateFormat = "MM"
  110. let monthString = formatter.string(from: assetDate)
  111. if asset.mediaSubtypes.contains(.photoLive) && CCUtility.getLivePhoto() {
  112. livePhoto = true
  113. }
  114. if selector == NCGlobal.shared.selectorUploadAutoUploadAll {
  115. session = NCCommunicationCommon.shared.sessionIdentifierUpload
  116. } else {
  117. if assetMediaType == PHAssetMediaType.image && account.autoUploadWWAnPhoto == false {
  118. session = NCNetworking.shared.sessionIdentifierBackground
  119. } else if assetMediaType == PHAssetMediaType.video && account.autoUploadWWAnVideo == false {
  120. session = NCNetworking.shared.sessionIdentifierBackground
  121. } else if assetMediaType == PHAssetMediaType.image && account.autoUploadWWAnPhoto {
  122. session = NCNetworking.shared.sessionIdentifierBackgroundWWan
  123. } else if assetMediaType == PHAssetMediaType.video && account.autoUploadWWAnVideo {
  124. session = NCNetworking.shared.sessionIdentifierBackgroundWWan
  125. } else { session = NCNetworking.shared.sessionIdentifierBackground }
  126. }
  127. if account.autoUploadCreateSubfolder {
  128. serverUrl = autoUploadPath + "/" + yearString + "/" + monthString
  129. } else {
  130. serverUrl = autoUploadPath
  131. }
  132. // MOST COMPATIBLE SEARCH --> HEIC --> JPG
  133. var fileNameSearchMetadata = fileName
  134. let ext = (fileNameSearchMetadata as NSString).pathExtension.uppercased()
  135. if ext == "HEIC" && CCUtility.getFormatCompatibility() {
  136. fileNameSearchMetadata = (fileNameSearchMetadata as NSString).deletingPathExtension + ".jpg"
  137. }
  138. if NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView == %@", account.account, serverUrl, fileNameSearchMetadata)) != nil {
  139. if selector == NCGlobal.shared.selectorUploadAutoUpload {
  140. NCManageDatabase.shared.addPhotoLibrary([asset], account: account.account)
  141. }
  142. } else {
  143. let metadata = NCManageDatabase.shared.createMetadata(account: account.account, user: account.user, userId: account.userId, fileName: fileName, fileNameView: fileName, ocId: NSUUID().uuidString, serverUrl: serverUrl, urlBase: account.urlBase, url: "", contentType: "", isLivePhoto: livePhoto)
  144. metadata.assetLocalIdentifier = asset.localIdentifier
  145. metadata.session = session
  146. metadata.sessionSelector = selector
  147. metadata.status = NCGlobal.shared.metadataStatusWaitUpload
  148. if assetMediaType == PHAssetMediaType.video {
  149. metadata.classFile = NCCommunicationCommon.typeClassFile.video.rawValue
  150. } else if assetMediaType == PHAssetMediaType.image {
  151. metadata.classFile = NCCommunicationCommon.typeClassFile.image.rawValue
  152. }
  153. if selector == NCGlobal.shared.selectorUploadAutoUpload {
  154. #if EXTENSION_WIDGET
  155. NKCommon.shared.writeLog("Automatic upload widget added \(metadata.fileNameView) with Identifier \(metadata.assetLocalIdentifier)")
  156. #else
  157. NCCommunicationCommon.shared.writeLog("Automatic upload added \(metadata.fileNameView) with Identifier \(metadata.assetLocalIdentifier)")
  158. #endif
  159. NCManageDatabase.shared.addPhotoLibrary([asset], account: account.account)
  160. }
  161. metadatas.append(metadata)
  162. }
  163. }
  164. self.endForAssetToUpload = true
  165. // AUTO UPLOAD ALL
  166. #if !EXTENSION
  167. if selector == NCGlobal.shared.selectorUploadAutoUploadAll {
  168. (UIApplication.shared.delegate as! AppDelegate).networkingProcessUpload?.createProcessUploads(metadatas: metadatas)
  169. completion(metadatas.count)
  170. }
  171. #endif
  172. // AUTO UPLOAD
  173. self.createProcessUploads(metadatas: metadatas, completion: completion)
  174. }
  175. }
  176. }
  177. // MARK: -
  178. func createProcessUploads(metadatas: [tableMetadata], completion: @escaping (_ items: Int) -> Void) {
  179. var metadatasForUpload: [tableMetadata] = []
  180. var numStartUpload: Int = 0
  181. let maxConcurrentOperationUpload = 5
  182. for metadata in metadatas {
  183. if NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ && serverUrl == %@ && fileName == %@ && session != ''", metadata.account, metadata.serverUrl, metadata.fileName)) != nil {
  184. continue
  185. }
  186. metadatasForUpload.append(metadata)
  187. }
  188. NCManageDatabase.shared.addMetadatas(metadatasForUpload)
  189. // Max file in Uploadading
  190. let metadatasInUpload = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "status == %d OR status == %d", NCGlobal.shared.metadataStatusInUpload, NCGlobal.shared.metadataStatusUploading))
  191. let counterUpload = maxConcurrentOperationUpload - metadatasInUpload.count
  192. if counterUpload <= 0 {
  193. return completion(0)
  194. }
  195. // Extract file
  196. let metadatas = NCManageDatabase.shared.getAdvancedMetadatas(predicate: NSPredicate(format: "sessionSelector == %@ AND status == %d", NCGlobal.shared.selectorUploadAutoUpload, NCGlobal.shared.metadataStatusWaitUpload), page: 0, limit: counterUpload, sorted: "date", ascending: true)
  197. for metadata in metadatas {
  198. let metadata = tableMetadata.init(value: metadata)
  199. let semaphore = Semaphore()
  200. NCUtility.shared.extractFiles(from: metadata) { metadatas in
  201. if metadatas.isEmpty {
  202. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  203. }
  204. for metadata in metadatas {
  205. #if !EXTENSION
  206. if (metadata.e2eEncrypted || metadata.chunk) && UIApplication.shared.applicationState != .active { continue }
  207. #else
  208. if (metadata.e2eEncrypted || metadata.chunk) { continue }
  209. #endif
  210. let isWiFi = NCNetworking.shared.networkReachability == NCCommunicationCommon.typeReachability.reachableEthernetOrWiFi
  211. if metadata.session == NCNetworking.shared.sessionIdentifierBackgroundWWan && !isWiFi { continue }
  212. guard let metadata = NCManageDatabase.shared.setMetadataStatus(ocId: metadata.ocId, status: NCGlobal.shared.metadataStatusInUpload) else { continue }
  213. // Upload
  214. let semaphoreUpload = Semaphore()
  215. NCNetworking.shared.upload(metadata: metadata) {
  216. numStartUpload += 1
  217. } completion: { errorCode, errorDescription in
  218. semaphoreUpload.continue()
  219. }
  220. semaphoreUpload.wait()
  221. }
  222. semaphore.continue()
  223. }
  224. semaphore.wait()
  225. }
  226. DispatchQueue.main.async {
  227. completion(numStartUpload)
  228. }
  229. }
  230. // MARK: -
  231. @objc func alignPhotoLibrary(viewController: UIViewController?) {
  232. guard let activeAccount = NCManageDatabase.shared.getActiveAccount() else { return }
  233. getCameraRollAssets(viewController: viewController, account: activeAccount, selector: NCGlobal.shared.selectorUploadAutoUploadAll, alignPhotoLibrary: true) { assets in
  234. NCManageDatabase.shared.clearTable(tablePhotoLibrary.self, account: activeAccount.account)
  235. guard let assets = assets else { return }
  236. NCManageDatabase.shared.addPhotoLibrary(assets, account: activeAccount.account)
  237. #if EXTENSION_WIDGET
  238. NKCommon.shared.writeLog("Widget align Photo Library \(assets.count)")
  239. #else
  240. NCCommunicationCommon.shared.writeLog("Align Photo Library \(assets.count)")
  241. #endif
  242. }
  243. }
  244. private func getCameraRollAssets(viewController: UIViewController?, account: tableAccount, selector: String, alignPhotoLibrary: Bool, completion: @escaping (_ assets: [PHAsset]?) -> Void) {
  245. NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: viewController) { hasPermission in
  246. guard hasPermission else {
  247. completion(nil)
  248. return
  249. }
  250. let assetCollection = PHAssetCollection.fetchAssetCollections(with: PHAssetCollectionType.smartAlbum, subtype: PHAssetCollectionSubtype.smartAlbumUserLibrary, options: nil)
  251. if assetCollection.count == 0 {
  252. completion(nil)
  253. return
  254. }
  255. let predicateImage = NSPredicate(format: "mediaType == %i", PHAssetMediaType.image.rawValue)
  256. let predicateVideo = NSPredicate(format: "mediaType == %i", PHAssetMediaType.video.rawValue)
  257. var predicate: NSPredicate?
  258. let fetchOptions = PHFetchOptions()
  259. var newAssets: [PHAsset] = []
  260. if alignPhotoLibrary || (account.autoUploadImage && account.autoUploadVideo) {
  261. predicate = NSCompoundPredicate(orPredicateWithSubpredicates: [predicateImage, predicateVideo])
  262. } else if account.autoUploadImage {
  263. predicate = predicateImage
  264. } else if account.autoUploadVideo {
  265. predicate = predicateVideo
  266. } else {
  267. return completion(nil)
  268. }
  269. fetchOptions.predicate = predicate
  270. let assets: PHFetchResult<PHAsset> = PHAsset.fetchAssets(in: assetCollection.firstObject!, options: fetchOptions)
  271. if selector == NCGlobal.shared.selectorUploadAutoUpload {
  272. var creationDate = ""
  273. var idAsset = ""
  274. let idsAsset = NCManageDatabase.shared.getPhotoLibraryIdAsset(image: account.autoUploadImage, video: account.autoUploadVideo, account: account.account)
  275. assets.enumerateObjects { asset, _, _ in
  276. if asset.creationDate != nil { creationDate = String(describing: asset.creationDate!) }
  277. idAsset = account.account + asset.localIdentifier + creationDate
  278. if !(idsAsset?.contains(idAsset) ?? false) {
  279. newAssets.append(asset)
  280. }
  281. }
  282. } else {
  283. assets.enumerateObjects { asset, _, _ in
  284. newAssets.append(asset)
  285. }
  286. }
  287. completion(newAssets)
  288. }
  289. }
  290. }