NCAutoUpload.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. class NCAutoUpload: NSObject {
  29. @objc static let shared: NCAutoUpload = {
  30. let instance = NCAutoUpload()
  31. return instance
  32. }()
  33. private var endForAssetToUpload: Bool = false
  34. // MARK: -
  35. @objc func initAutoUpload(viewController: UIViewController?, completion: @escaping (_ items: Int) -> Void) {
  36. guard let account = NCManageDatabase.shared.getActiveAccount(), account.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: viewController) { hasPermission in
  53. guard hasPermission else { return }
  54. #if !EXTENSION
  55. NCContentPresenter.shared.messageNotification("_attention_", description: "_create_full_upload_", delay: NCGlobal.shared.dismissAfterSecondLong, type: .info, errorCode: NCGlobal.shared.errorNoError, priority: .max)
  56. NCActivityIndicator.shared.start()
  57. #endif
  58. self.uploadAssetsNewAndFull(viewController: viewController, selector: NCGlobal.shared.selectorUploadAutoUploadAll, log: log) { _ in
  59. #if !EXTENSION
  60. NCActivityIndicator.shared.stop()
  61. #endif
  62. }
  63. }
  64. }
  65. private func uploadAssetsNewAndFull(viewController: UIViewController?, selector: String, log: String, completion: @escaping (_ items: Int) -> Void) {
  66. guard let account = NCManageDatabase.shared.getActiveAccount() else {
  67. completion(0)
  68. return
  69. }
  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. #if EXTENSION_WIDGET
  76. NKCommon.shared.writeLog("Automatic upload widget, no new assets found [" + log + "]")
  77. #else
  78. NCCommunicationCommon.shared.writeLog("Automatic upload, no new assets found [" + log + "]")
  79. #endif
  80. completion(0)
  81. return
  82. }
  83. #if EXTENSION_WIDGET
  84. NKCommon.shared.writeLog("Automatic upload widget, new \(assets.count) assets found [" + log + "]")
  85. #else
  86. NCCommunicationCommon.shared.writeLog("Automatic upload, new \(assets.count) assets found [" + log + "]")
  87. #endif
  88. // Create the folder for auto upload & if request the subfolders
  89. if !NCNetworking.shared.createFolder(assets: assets, selector: selector, useSubFolder: account.autoUploadCreateSubfolder, account: account.account, urlBase: account.urlBase) {
  90. #if !EXTENSION
  91. if selector == NCGlobal.shared.selectorUploadAutoUploadAll {
  92. NCContentPresenter.shared.messageNotification("_error_", description: "_error_createsubfolders_upload_", delay: NCGlobal.shared.dismissAfterSecond, type: .error, errorCode: NCGlobal.shared.errorInternalError, priority: .max)
  93. }
  94. #endif
  95. return completion(0)
  96. }
  97. self.endForAssetToUpload = false
  98. for asset in assets {
  99. var livePhoto = false
  100. var session: String = ""
  101. guard let assetDate = asset.creationDate else { continue }
  102. let assetMediaType = asset.mediaType
  103. var serverUrl: String = ""
  104. 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)!
  105. let formatter = DateFormatter()
  106. formatter.dateFormat = "yyyy"
  107. let yearString = formatter.string(from: assetDate)
  108. formatter.dateFormat = "MM"
  109. let monthString = formatter.string(from: assetDate)
  110. if asset.mediaSubtypes.contains(.photoLive) && CCUtility.getLivePhoto() {
  111. livePhoto = true
  112. }
  113. if selector == NCGlobal.shared.selectorUploadAutoUploadAll {
  114. session = NCCommunicationCommon.shared.sessionIdentifierUpload
  115. } else {
  116. if assetMediaType == PHAssetMediaType.image && account.autoUploadWWAnPhoto == false {
  117. session = NCNetworking.shared.sessionIdentifierBackground
  118. } else if assetMediaType == PHAssetMediaType.video && account.autoUploadWWAnVideo == false {
  119. session = NCNetworking.shared.sessionIdentifierBackground
  120. } else if assetMediaType == PHAssetMediaType.image && account.autoUploadWWAnPhoto {
  121. session = NCNetworking.shared.sessionIdentifierBackgroundWWan
  122. } else if assetMediaType == PHAssetMediaType.video && account.autoUploadWWAnVideo {
  123. session = NCNetworking.shared.sessionIdentifierBackgroundWWan
  124. } else { session = NCNetworking.shared.sessionIdentifierBackground }
  125. }
  126. if account.autoUploadCreateSubfolder {
  127. serverUrl = autoUploadPath + "/" + yearString + "/" + monthString
  128. } else {
  129. serverUrl = autoUploadPath
  130. }
  131. // MOST COMPATIBLE SEARCH --> HEIC --> JPG
  132. var fileNameSearchMetadata = fileName
  133. let ext = (fileNameSearchMetadata as NSString).pathExtension.uppercased()
  134. if ext == "HEIC" && CCUtility.getFormatCompatibility() {
  135. fileNameSearchMetadata = (fileNameSearchMetadata as NSString).deletingPathExtension + ".jpg"
  136. }
  137. if NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView == %@", account.account, serverUrl, fileNameSearchMetadata)) != nil {
  138. if selector == NCGlobal.shared.selectorUploadAutoUpload {
  139. NCManageDatabase.shared.addPhotoLibrary([asset], account: account.account)
  140. }
  141. } else {
  142. 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)
  143. metadata.assetLocalIdentifier = asset.localIdentifier
  144. metadata.session = session
  145. metadata.sessionSelector = selector
  146. metadata.status = NCGlobal.shared.metadataStatusWaitUpload
  147. if assetMediaType == PHAssetMediaType.video {
  148. metadata.classFile = NCCommunicationCommon.typeClassFile.video.rawValue
  149. } else if assetMediaType == PHAssetMediaType.image {
  150. metadata.classFile = NCCommunicationCommon.typeClassFile.image.rawValue
  151. }
  152. if selector == NCGlobal.shared.selectorUploadAutoUpload {
  153. #if EXTENSION_WIDGET
  154. NKCommon.shared.writeLog("Automatic upload widget added \(metadata.fileNameView) with Identifier \(metadata.assetLocalIdentifier)")
  155. #else
  156. NCCommunicationCommon.shared.writeLog("Automatic upload added \(metadata.fileNameView) with Identifier \(metadata.assetLocalIdentifier)")
  157. #endif
  158. NCManageDatabase.shared.addPhotoLibrary([asset], account: account.account)
  159. }
  160. metadatas.append(metadata)
  161. }
  162. }
  163. self.endForAssetToUpload = true
  164. #if !EXTENSION
  165. if selector == NCGlobal.shared.selectorUploadAutoUploadAll {
  166. (UIApplication.shared.delegate as! AppDelegate).networkingProcessUpload?.createProcessUploads(metadatas: metadatas)
  167. } else {
  168. (UIApplication.shared.delegate as! AppDelegate).networkingProcessUpload?.createProcessUploads(metadatas: metadatas, verifyAlreadyExists: true)
  169. }
  170. #elseif EXTENSION_WIDGET
  171. if selector == NCGlobal.shared.selectorUploadAutoUpload {
  172. let networkingProcessUpload = NCNetworkingProcessUpload()
  173. networkingProcessUpload.createProcessUploads(metadatas: metadatas, verifyAlreadyExists: true)
  174. }
  175. #endif
  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. #if EXTENSION_WIDGET
  188. NKCommon.shared.writeLog("Widget align Photo Library \(assets.count)")
  189. #else
  190. NCCommunicationCommon.shared.writeLog("Align Photo Library \(assets.count)")
  191. #endif
  192. }
  193. }
  194. private func getCameraRollAssets(viewController: UIViewController?, account: tableAccount, selector: String, alignPhotoLibrary: Bool, completion: @escaping (_ assets: [PHAsset]?) -> Void) {
  195. NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: viewController) { hasPermission in
  196. guard hasPermission else {
  197. completion(nil)
  198. return
  199. }
  200. let assetCollection = PHAssetCollection.fetchAssetCollections(with: PHAssetCollectionType.smartAlbum, subtype: PHAssetCollectionSubtype.smartAlbumUserLibrary, options: nil)
  201. if assetCollection.count == 0 {
  202. completion(nil)
  203. return
  204. }
  205. let predicateImage = NSPredicate(format: "mediaType == %i", PHAssetMediaType.image.rawValue)
  206. let predicateVideo = NSPredicate(format: "mediaType == %i", PHAssetMediaType.video.rawValue)
  207. var predicate: NSPredicate?
  208. let fetchOptions = PHFetchOptions()
  209. var newAssets: [PHAsset] = []
  210. if alignPhotoLibrary || (account.autoUploadImage && account.autoUploadVideo) {
  211. predicate = NSCompoundPredicate(orPredicateWithSubpredicates: [predicateImage, predicateVideo])
  212. } else if account.autoUploadImage {
  213. predicate = predicateImage
  214. } else if account.autoUploadVideo {
  215. predicate = predicateVideo
  216. } else {
  217. return completion(nil)
  218. }
  219. fetchOptions.predicate = predicate
  220. let assets: PHFetchResult<PHAsset> = PHAsset.fetchAssets(in: assetCollection.firstObject!, options: fetchOptions)
  221. if selector == NCGlobal.shared.selectorUploadAutoUpload {
  222. var creationDate = ""
  223. var idAsset = ""
  224. let idsAsset = NCManageDatabase.shared.getPhotoLibraryIdAsset(image: account.autoUploadImage, video: account.autoUploadVideo, account: account.account)
  225. assets.enumerateObjects { asset, _, _ in
  226. if asset.creationDate != nil { creationDate = String(describing: asset.creationDate!) }
  227. idAsset = account.account + asset.localIdentifier + creationDate
  228. if !(idsAsset?.contains(idAsset) ?? false) {
  229. newAssets.append(asset)
  230. }
  231. }
  232. } else {
  233. assets.enumerateObjects { asset, _, _ in
  234. newAssets.append(asset)
  235. }
  236. }
  237. completion(newAssets)
  238. }
  239. }
  240. }