NCAutoUpload.swift 17 KB

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