NCAutoUpload.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. completion(items)
  48. }
  49. }
  50. }
  51. @objc func autoUploadFullPhotos(viewController: UIViewController?, log: String) {
  52. NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: appDelegate.window?.rootViewController) { hasPermission in
  53. guard hasPermission else { return }
  54. NCContentPresenter.shared.messageNotification("_attention_", description: "_create_full_upload_", delay: NCGlobal.shared.dismissAfterSecondLong, type: .info, errorCode: NCGlobal.shared.errorNoError, priority: .max)
  55. NCUtility.shared.startActivityIndicator(backgroundView: nil, blurEffect: true)
  56. self.uploadAssetsNewAndFull(viewController: viewController, selector: NCGlobal.shared.selectorUploadAutoUploadAll, log: log) { _ in
  57. NCUtility.shared.stopActivityIndicator()
  58. }
  59. }
  60. }
  61. private func uploadAssetsNewAndFull(viewController: UIViewController?, selector: String, log: String, completion: @escaping (_ items: Int) -> Void) {
  62. guard !appDelegate.account.isEmpty else {
  63. completion(0)
  64. return
  65. }
  66. guard let account = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", appDelegate.account)) else { return }
  67. DispatchQueue.global(qos: .background).async {
  68. let autoUploadPath = NCManageDatabase.shared.getAccountAutoUploadPath(urlBase: account.urlBase, account: account.account)
  69. var metadatas: [tableMetadata] = []
  70. self.getCameraRollAssets(viewController: viewController, account: account, selector: selector, alignPhotoLibrary: false) { assets in
  71. guard let assets = assets, !assets.isEmpty else {
  72. NCCommunicationCommon.shared.writeLog("Automatic upload, no new assets found [" + log + "]")
  73. completion(0)
  74. return
  75. }
  76. NCCommunicationCommon.shared.writeLog("Automatic upload, new \(assets.count) assets found [" + log + "]")
  77. // Create the folder for auto upload & if request the subfolders
  78. if !NCNetworking.shared.createFolder(assets: assets, selector: selector, useSubFolder: account.autoUploadCreateSubfolder, account: account.account, urlBase: account.urlBase) {
  79. if selector == NCGlobal.shared.selectorUploadAutoUploadAll {
  80. NCContentPresenter.shared.messageNotification("_error_", description: "_error_createsubfolders_upload_", delay: NCGlobal.shared.dismissAfterSecond, type: .error, errorCode: NCGlobal.shared.errorInternalError, priority: .max)
  81. }
  82. return completion(0)
  83. }
  84. self.endForAssetToUpload = false
  85. for asset in assets {
  86. var livePhoto = false
  87. var session: String = ""
  88. guard let assetDate = asset.creationDate else { continue }
  89. let assetMediaType = asset.mediaType
  90. var serverUrl: String = ""
  91. 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)!
  92. let formatter = DateFormatter()
  93. formatter.dateFormat = "yyyy"
  94. let yearString = formatter.string(from: assetDate)
  95. formatter.dateFormat = "MM"
  96. let monthString = formatter.string(from: assetDate)
  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. if account.autoUploadCreateSubfolder {
  114. serverUrl = autoUploadPath + "/" + yearString + "/" + monthString
  115. } else {
  116. serverUrl = autoUploadPath
  117. }
  118. // MOST COMPATIBLE SEARCH --> HEIC --> JPG
  119. var fileNameSearchMetadata = fileName
  120. let ext = (fileNameSearchMetadata as NSString).pathExtension.uppercased()
  121. if ext == "HEIC" && CCUtility.getFormatCompatibility() {
  122. fileNameSearchMetadata = (fileNameSearchMetadata as NSString).deletingPathExtension + ".jpg"
  123. }
  124. if NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView == %@", account.account, serverUrl, fileNameSearchMetadata)) != nil {
  125. if selector == NCGlobal.shared.selectorUploadAutoUpload {
  126. NCManageDatabase.shared.addPhotoLibrary([asset], account: account.account)
  127. }
  128. } else {
  129. 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)
  130. metadata.assetLocalIdentifier = asset.localIdentifier
  131. metadata.session = session
  132. metadata.sessionSelector = selector
  133. metadata.status = NCGlobal.shared.metadataStatusWaitUpload
  134. if assetMediaType == PHAssetMediaType.video {
  135. metadata.classFile = NCCommunicationCommon.typeClassFile.video.rawValue
  136. } else if assetMediaType == PHAssetMediaType.image {
  137. metadata.classFile = NCCommunicationCommon.typeClassFile.image.rawValue
  138. }
  139. if selector == NCGlobal.shared.selectorUploadAutoUpload {
  140. NCCommunicationCommon.shared.writeLog("Automatic upload added \(metadata.fileNameView) with Identifier \(metadata.assetLocalIdentifier)")
  141. NCManageDatabase.shared.addPhotoLibrary([asset], account: account.account)
  142. }
  143. metadatas.append(metadata)
  144. }
  145. }
  146. self.endForAssetToUpload = true
  147. if selector == NCGlobal.shared.selectorUploadAutoUploadAll {
  148. self.appDelegate.networkingProcessUpload?.createProcessUploads(metadatas: metadatas)
  149. } else {
  150. self.appDelegate.networkingProcessUpload?.createProcessUploads(metadatas: metadatas, verifyAlreadyExists: true)
  151. }
  152. completion(metadatas.count)
  153. }
  154. }
  155. }
  156. // MARK: -
  157. @objc func alignPhotoLibrary(viewController: UIViewController?) {
  158. guard let activeAccount = NCManageDatabase.shared.getActiveAccount() else { return }
  159. getCameraRollAssets(viewController: viewController, account: activeAccount, selector: NCGlobal.shared.selectorUploadAutoUploadAll, alignPhotoLibrary: true) { assets in
  160. NCManageDatabase.shared.clearTable(tablePhotoLibrary.self, account: activeAccount.account)
  161. guard let assets = assets else { return }
  162. NCManageDatabase.shared.addPhotoLibrary(assets, account: activeAccount.account)
  163. NCCommunicationCommon.shared.writeLog("Align Photo Library \(assets.count)")
  164. }
  165. }
  166. private func getCameraRollAssets(viewController: UIViewController?, account: tableAccount, selector: String, alignPhotoLibrary: Bool, completion: @escaping (_ assets: [PHAsset]?) -> Void) {
  167. NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: viewController) { hasPermission in
  168. guard hasPermission else {
  169. completion(nil)
  170. return
  171. }
  172. let assetCollection = PHAssetCollection.fetchAssetCollections(with: PHAssetCollectionType.smartAlbum, subtype: PHAssetCollectionSubtype.smartAlbumUserLibrary, options: nil)
  173. if assetCollection.count == 0 {
  174. completion(nil)
  175. return
  176. }
  177. let predicateImage = NSPredicate(format: "mediaType == %i", PHAssetMediaType.image.rawValue)
  178. let predicateVideo = NSPredicate(format: "mediaType == %i", PHAssetMediaType.video.rawValue)
  179. var predicate: NSPredicate?
  180. let fetchOptions = PHFetchOptions()
  181. var newAssets: [PHAsset] = []
  182. if alignPhotoLibrary || (account.autoUploadImage && account.autoUploadVideo) {
  183. predicate = NSCompoundPredicate(orPredicateWithSubpredicates: [predicateImage, predicateVideo])
  184. } else if account.autoUploadImage {
  185. predicate = predicateImage
  186. } else if account.autoUploadVideo {
  187. predicate = predicateVideo
  188. } else {
  189. return completion(nil)
  190. }
  191. fetchOptions.predicate = predicate
  192. let assets: PHFetchResult<PHAsset> = PHAsset.fetchAssets(in: assetCollection.firstObject!, options: fetchOptions)
  193. if selector == NCGlobal.shared.selectorUploadAutoUpload {
  194. var creationDate = ""
  195. var idAsset = ""
  196. let idsAsset = NCManageDatabase.shared.getPhotoLibraryIdAsset(image: account.autoUploadImage, video: account.autoUploadVideo, account: account.account)
  197. assets.enumerateObjects { asset, _, _ in
  198. if asset.creationDate != nil { creationDate = String(describing: asset.creationDate!) }
  199. idAsset = account.account + asset.localIdentifier + creationDate
  200. if !(idsAsset?.contains(idAsset) ?? false) {
  201. newAssets.append(asset)
  202. }
  203. }
  204. } else {
  205. assets.enumerateObjects { asset, _, _ in
  206. newAssets.append(asset)
  207. }
  208. }
  209. completion(newAssets)
  210. }
  211. }
  212. }