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