NCAutoUpload.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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. class NCAutoUpload: NSObject {
  28. @objc static let shared: NCAutoUpload = {
  29. let instance = NCAutoUpload()
  30. return instance
  31. }()
  32. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  33. private var endForAssetToUpload: Bool = false
  34. // MARK: -
  35. @objc func initAutoUpload(viewController: UIViewController?, completion: @escaping (_ items: Int) -> Void) {
  36. guard let activeAccount = NCManageDatabase.shared.getActiveAccount(), activeAccount.autoUpload else {
  37. completion(0)
  38. return
  39. }
  40. NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: viewController) { hasPermission in
  41. guard hasPermission else {
  42. NCManageDatabase.shared.setAccountAutoUploadProperty("autoUpload", state: false)
  43. completion(0)
  44. return
  45. }
  46. self.uploadAssetsNewAndFull(viewController: viewController, selector: NCGlobal.shared.selectorUploadAutoUpload, log: "Init Auto Upload") { items in
  47. if items > 0 {
  48. self.appDelegate.networkingProcessUpload?.startProcess()
  49. }
  50. completion(items)
  51. }
  52. }
  53. }
  54. @objc func autoUploadFullPhotos(viewController: UIViewController?, log: String) {
  55. NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: appDelegate.window?.rootViewController) { hasPermission in
  56. guard hasPermission else { return }
  57. NCContentPresenter.shared.messageNotification("_attention_", description: "_create_full_upload_", delay: NCGlobal.shared.dismissAfterSecondLong, type: .info, errorCode: NCGlobal.shared.errorNoError, priority: .max)
  58. NCUtility.shared.startActivityIndicator(backgroundView: nil, blurEffect: true)
  59. self.uploadAssetsNewAndFull(viewController: viewController, selector: NCGlobal.shared.selectorUploadAutoUploadAll, log: log) { _ in
  60. NCUtility.shared.stopActivityIndicator()
  61. }
  62. }
  63. }
  64. private func uploadAssetsNewAndFull(viewController: UIViewController?, selector: String, log: String, completion: @escaping (_ items: Int) -> Void) {
  65. guard !appDelegate.account.isEmpty else {
  66. completion(0)
  67. return
  68. }
  69. guard let account = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", appDelegate.account)) else { return }
  70. let autoUploadPath = NCManageDatabase.shared.getAccountAutoUploadPath(urlBase: account.urlBase, account: account.account)
  71. var metadataFull: [tableMetadata] = []
  72. var counterItemsUpload: Int = 0
  73. DispatchQueue.global(qos: .background).async {
  74. self.getCameraRollAssets(viewController: viewController, account: account, selector: selector, alignPhotoLibrary: false) { assets in
  75. guard let assets = assets, !assets.isEmpty else {
  76. NCCommunicationCommon.shared.writeLog("Automatic upload, no new assets found [" + log + "]")
  77. completion(counterItemsUpload)
  78. return
  79. }
  80. NCCommunicationCommon.shared.writeLog("Automatic upload, new \(assets.count) assets found [" + log + "]")
  81. // Create the folder for auto upload & if request the subfolders
  82. if !NCNetworking.shared.createFolder(assets: assets, selector: selector, useSubFolder: account.autoUploadCreateSubfolder, account: account.account, urlBase: account.urlBase) {
  83. if selector == NCGlobal.shared.selectorUploadAutoUploadAll {
  84. NCContentPresenter.shared.messageNotification("_error_", description: "_error_createsubfolders_upload_", delay: NCGlobal.shared.dismissAfterSecond, type: .error, errorCode: NCGlobal.shared.errorInternalError, priority: .max)
  85. }
  86. return completion(counterItemsUpload)
  87. }
  88. self.endForAssetToUpload = false
  89. for asset in assets {
  90. var livePhoto = false
  91. var session: String = ""
  92. guard let assetDate = asset.creationDate else { continue }
  93. let assetMediaType = asset.mediaType
  94. let formatter = DateFormatter()
  95. var serverUrl: String = ""
  96. 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)!
  97. if asset.mediaSubtypes.contains(.photoLive) && CCUtility.getLivePhoto() {
  98. livePhoto = true
  99. }
  100. if selector == NCGlobal.shared.selectorUploadAutoUploadAll {
  101. session = NCCommunicationCommon.shared.sessionIdentifierUpload
  102. } else {
  103. if assetMediaType == PHAssetMediaType.image && account.autoUploadWWAnPhoto == false {
  104. session = NCNetworking.shared.sessionIdentifierBackground
  105. } else if assetMediaType == PHAssetMediaType.video && account.autoUploadWWAnVideo == false {
  106. session = NCNetworking.shared.sessionIdentifierBackground
  107. } else if assetMediaType == PHAssetMediaType.image && account.autoUploadWWAnPhoto {
  108. session = NCNetworking.shared.sessionIdentifierBackgroundWWan
  109. } else if assetMediaType == PHAssetMediaType.video && account.autoUploadWWAnVideo {
  110. session = NCNetworking.shared.sessionIdentifierBackgroundWWan
  111. } else { session = NCNetworking.shared.sessionIdentifierBackground }
  112. }
  113. formatter.dateFormat = "yyyy"
  114. let yearString = formatter.string(from: assetDate)
  115. formatter.dateFormat = "MM"
  116. let monthString = formatter.string(from: assetDate)
  117. if account.autoUploadCreateSubfolder {
  118. serverUrl = autoUploadPath + "/" + yearString + "/" + monthString
  119. } else {
  120. serverUrl = autoUploadPath
  121. }
  122. // MOST COMPATIBLE SEARCH --> HEIC --> JPG
  123. var fileNameSearchMetadata = fileName
  124. let ext = (fileNameSearchMetadata as NSString).pathExtension.uppercased()
  125. if ext == "HEIC" && CCUtility.getFormatCompatibility() {
  126. fileNameSearchMetadata = (fileNameSearchMetadata as NSString).deletingPathExtension + ".jpg"
  127. }
  128. if NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView == %@", account.account, serverUrl, fileNameSearchMetadata)) != nil {
  129. if selector == NCGlobal.shared.selectorUploadAutoUpload {
  130. NCManageDatabase.shared.addPhotoLibrary([asset], account: account.account)
  131. }
  132. } else {
  133. /* INSERT METADATA FOR UPLOAD */
  134. let metadataForUpload = 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)
  135. metadataForUpload.assetLocalIdentifier = asset.localIdentifier
  136. metadataForUpload.session = session
  137. metadataForUpload.sessionSelector = selector
  138. if selector != NCGlobal.shared.selectorUploadAutoUploadAll {
  139. metadataForUpload.isAutoupload = true
  140. }
  141. metadataForUpload.status = NCGlobal.shared.metadataStatusWaitUpload
  142. if assetMediaType == PHAssetMediaType.video {
  143. metadataForUpload.classFile = NCCommunicationCommon.typeClassFile.video.rawValue
  144. } else if assetMediaType == PHAssetMediaType.image {
  145. metadataForUpload.classFile = NCCommunicationCommon.typeClassFile.image.rawValue
  146. }
  147. if selector == NCGlobal.shared.selectorUploadAutoUpload {
  148. NCCommunicationCommon.shared.writeLog("Automatic upload added \(metadataForUpload.fileNameView) with Identifier \(metadataForUpload.assetLocalIdentifier)")
  149. NCManageDatabase.shared.addPhotoLibrary([asset], account: account.account)
  150. } else if selector == NCGlobal.shared.selectorUploadAutoUploadAll {
  151. metadataFull.append(metadataForUpload)
  152. }
  153. counterItemsUpload += 1
  154. /* INSERT METADATA MOV LIVE PHOTO FOR UPLOAD */
  155. if livePhoto {
  156. let fileName = (fileName as NSString).deletingPathExtension + ".mov"
  157. let ocId = NSUUID().uuidString
  158. let metadataForUpload = NCManageDatabase.shared.createMetadata(account: account.account, user: account.user, userId: account.userId, fileName: fileName, fileNameView: fileName, ocId: ocId, serverUrl: serverUrl, urlBase: account.urlBase, url: "", contentType: "", isLivePhoto: livePhoto)
  159. metadataForUpload.session = session
  160. metadataForUpload.sessionSelector = selector
  161. if selector != NCGlobal.shared.selectorUploadAutoUploadAll {
  162. metadataForUpload.isAutoupload = true
  163. }
  164. metadataForUpload.status = NCGlobal.shared.metadataStatusWaitUpload
  165. metadataForUpload.classFile = NCCommunicationCommon.typeClassFile.video.rawValue
  166. if selector == NCGlobal.shared.selectorUploadAutoUpload {
  167. NCCommunicationCommon.shared.writeLog("Automatic upload added Live Photo \(metadataForUpload.fileNameView) with Identifier \(metadataForUpload.assetLocalIdentifier)")
  168. } else if selector == NCGlobal.shared.selectorUploadAutoUploadAll {
  169. metadataFull.append(metadataForUpload)
  170. }
  171. }
  172. }
  173. }
  174. self.endForAssetToUpload = true
  175. completion(counterItemsUpload)
  176. }
  177. }
  178. }
  179. // MARK: -
  180. @objc func alignPhotoLibrary(viewController: UIViewController?) {
  181. guard let activeAccount = NCManageDatabase.shared.getActiveAccount() else { return }
  182. getCameraRollAssets(viewController: viewController, account: activeAccount, selector: NCGlobal.shared.selectorUploadAutoUploadAll, alignPhotoLibrary: true) { assets in
  183. NCManageDatabase.shared.clearTable(tablePhotoLibrary.self, account: activeAccount.account)
  184. guard let assets = assets else { return }
  185. NCManageDatabase.shared.addPhotoLibrary(assets, account: activeAccount.account)
  186. NCCommunicationCommon.shared.writeLog("Align Photo Library \(assets.count)")
  187. }
  188. }
  189. private func getCameraRollAssets(viewController: UIViewController?, account: tableAccount, selector: String, alignPhotoLibrary: Bool, completion: @escaping (_ assets: [PHAsset]?) -> Void) {
  190. NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: viewController) { hasPermission in
  191. guard hasPermission else {
  192. completion(nil)
  193. return
  194. }
  195. let assetCollection = PHAssetCollection.fetchAssetCollections(with: PHAssetCollectionType.smartAlbum, subtype: PHAssetCollectionSubtype.smartAlbumUserLibrary, options: nil)
  196. if assetCollection.count == 0 {
  197. completion(nil)
  198. return
  199. }
  200. let predicateImage = NSPredicate(format: "mediaType == %i", PHAssetMediaType.image.rawValue)
  201. let predicateVideo = NSPredicate(format: "mediaType == %i", PHAssetMediaType.video.rawValue)
  202. var predicate: NSPredicate?
  203. let fetchOptions = PHFetchOptions()
  204. var newAssets: [PHAsset] = []
  205. if alignPhotoLibrary || (account.autoUploadImage && account.autoUploadVideo) {
  206. predicate = NSCompoundPredicate(orPredicateWithSubpredicates: [predicateImage, predicateVideo])
  207. } else if account.autoUploadImage {
  208. predicate = predicateImage
  209. } else if account.autoUploadVideo {
  210. predicate = predicateVideo
  211. } else {
  212. return completion(nil)
  213. }
  214. fetchOptions.predicate = predicate
  215. let assets: PHFetchResult<PHAsset> = PHAsset.fetchAssets(in: assetCollection.firstObject!, options: fetchOptions)
  216. if selector == NCGlobal.shared.selectorUploadAutoUpload {
  217. var creationDate = ""
  218. var idAsset = ""
  219. let idsAsset = NCManageDatabase.shared.getPhotoLibraryIdAsset(image: account.autoUploadImage, video: account.autoUploadVideo, account: account.account)
  220. assets.enumerateObjects { asset, _, _ in
  221. if asset.creationDate != nil { creationDate = String(describing: asset.creationDate!) }
  222. idAsset = account.account + asset.localIdentifier + creationDate
  223. if !(idsAsset?.contains(idAsset) ?? false) {
  224. newAssets.append(asset)
  225. }
  226. }
  227. } else {
  228. assets.enumerateObjects { asset, _, _ in
  229. newAssets.append(asset)
  230. }
  231. }
  232. completion(newAssets)
  233. }
  234. }
  235. }