NCAutoUpload.swift 18 KB

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