NCUploadAssetsModel.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. //
  2. // NCUploadAssetsModel.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/01/23.
  6. // Copyright © 2023 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 SwiftUI
  24. import NextcloudKit
  25. import TLPhotoPicker
  26. import Mantis
  27. import Photos
  28. import QuickLook
  29. // MARK: - Class
  30. struct PreviewStore {
  31. var id: String
  32. var asset: TLPHAsset
  33. var assetType: TLPHAsset.AssetType
  34. var data: Data?
  35. var fileName: String
  36. var image: UIImage
  37. }
  38. class NCUploadAssetsModel: ObservableObject, NCCreateFormUploadConflictDelegate {
  39. @Published var serverUrl: String
  40. @Published var assets: [TLPHAsset]
  41. @Published var previewStore: [PreviewStore] = []
  42. @Published var dismissView = false
  43. @Published var hiddenSave = true
  44. @Published var useAutoUploadFolder = false
  45. @Published var useAutoUploadSubFolder = false
  46. @Published var showHUD = false
  47. @Published var uploadInProgress = false
  48. /// Root View Controller
  49. @Published var controller: NCMainTabBarController?
  50. /// Session
  51. var session: NCSession.Session {
  52. NCSession.shared.getSession(controller: controller)
  53. }
  54. let database = NCManageDatabase.shared
  55. var metadatasNOConflict: [tableMetadata] = []
  56. var metadatasUploadInConflict: [tableMetadata] = []
  57. var timer: Timer?
  58. init(assets: [TLPHAsset], serverUrl: String, controller: NCMainTabBarController?) {
  59. self.assets = assets
  60. self.serverUrl = serverUrl
  61. self.controller = controller
  62. self.showHUD = true
  63. DispatchQueue.global(qos: .userInteractive).async {
  64. for asset in self.assets {
  65. guard let image = asset.fullResolutionImage?.resizeImage(size: CGSize(width: 300, height: 300), isAspectRation: true),
  66. let localIdentifier = asset.phAsset?.localIdentifier else { continue }
  67. DispatchQueue.main.async {
  68. self.previewStore.append(PreviewStore(id: localIdentifier, asset: asset, assetType: asset.type, fileName: "", image: image))
  69. }
  70. }
  71. DispatchQueue.main.async {
  72. self.showHUD = false
  73. self.hiddenSave = false
  74. }
  75. }
  76. }
  77. func getTextServerUrl() -> String {
  78. if let directory = database.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", session.account, serverUrl)), let metadata = database.getMetadataFromOcId(directory.ocId) {
  79. return (metadata.fileNameView)
  80. } else {
  81. return (serverUrl as NSString).lastPathComponent
  82. }
  83. }
  84. func getOriginalFilenameForPreview() -> NSString {
  85. if let asset = assets.first?.phAsset {
  86. return asset.originalFilename
  87. } else {
  88. return ""
  89. }
  90. }
  91. func deleteAsset(index: Int) {
  92. assets.remove(at: index)
  93. previewStore.remove(at: index)
  94. if previewStore.isEmpty {
  95. dismissView = true
  96. }
  97. }
  98. func presentedQuickLook(index: Int, fileNamePath: String) -> Bool {
  99. var image: UIImage?
  100. if let imageData = previewStore[index].data {
  101. image = UIImage(data: imageData)
  102. } else if let imageFullResolution = previewStore[index].asset.fullResolutionImage?.fixedOrientation() {
  103. image = imageFullResolution
  104. }
  105. if let image = image {
  106. if let data = image.jpegData(compressionQuality: 1) {
  107. do {
  108. try data.write(to: URL(fileURLWithPath: fileNamePath))
  109. return true
  110. } catch {
  111. }
  112. }
  113. }
  114. return false
  115. }
  116. func startTimer(navigationItem: UINavigationItem) {
  117. self.timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true, block: { _ in
  118. guard let buttonDone = navigationItem.leftBarButtonItems?.first, let buttonCrop = navigationItem.leftBarButtonItems?.last else { return }
  119. buttonCrop.isEnabled = true
  120. buttonDone.isEnabled = true
  121. if let markup = navigationItem.rightBarButtonItems?.first(where: { $0.accessibilityIdentifier == "QLOverlayMarkupButtonAccessibilityIdentifier" }) {
  122. if let originalButton = markup.value(forKey: "originalButton") as AnyObject? {
  123. if let symbolImageName = originalButton.value(forKey: "symbolImageName") as? String {
  124. if symbolImageName == "pencil.tip.crop.circle.on" {
  125. buttonCrop.isEnabled = false
  126. buttonDone.isEnabled = false
  127. }
  128. }
  129. }
  130. }
  131. })
  132. }
  133. func stopTimer() {
  134. self.timer?.invalidate()
  135. }
  136. func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
  137. guard let metadatas = metadatas else {
  138. self.showHUD = false
  139. self.uploadInProgress.toggle()
  140. return
  141. }
  142. func createProcessUploads() {
  143. if !self.dismissView {
  144. NCNetworkingProcess.shared.createProcessUploads(metadatas: metadatas, completion: { _ in
  145. self.dismissView = true
  146. })
  147. }
  148. }
  149. if useAutoUploadFolder {
  150. DispatchQueue.global().async {
  151. let assets = self.assets.compactMap { $0.phAsset }
  152. let result = NCNetworking.shared.createFolder(assets: assets, useSubFolder: self.useAutoUploadSubFolder, withPush: false, session: self.session)
  153. DispatchQueue.main.async {
  154. self.showHUD = false
  155. self.uploadInProgress.toggle()
  156. if result {
  157. createProcessUploads()
  158. } else {
  159. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_error_createsubfolders_upload_")
  160. NCContentPresenter().showError(error: error)
  161. }
  162. }
  163. }
  164. } else {
  165. createProcessUploads()
  166. }
  167. }
  168. func save(completion: @escaping (_ metadatasNOConflict: [tableMetadata], _ metadatasUploadInConflict: [tableMetadata]) -> Void) {
  169. let utilityFileSystem = NCUtilityFileSystem()
  170. var metadatasNOConflict: [tableMetadata] = []
  171. var metadatasUploadInConflict: [tableMetadata] = []
  172. let autoUploadPath = database.getAccountAutoUploadPath(session: self.session)
  173. var serverUrl = useAutoUploadFolder ? autoUploadPath : serverUrl
  174. for tlAsset in assets {
  175. guard let asset = tlAsset.phAsset, let previewStore = previewStore.first(where: { $0.id == asset.localIdentifier }) else { continue }
  176. let assetFileName = asset.originalFilename
  177. var livePhoto: Bool = false
  178. let creationDate = asset.creationDate ?? Date()
  179. let ext = assetFileName.pathExtension.lowercased()
  180. let fileName = previewStore.fileName.isEmpty ? utilityFileSystem.createFileName(assetFileName as String, fileDate: creationDate, fileType: asset.mediaType)
  181. : (previewStore.fileName + "." + ext)
  182. if previewStore.assetType == .livePhoto && NCKeychain().livePhoto && previewStore.data == nil {
  183. livePhoto = true
  184. }
  185. // Auto upload with subfolder
  186. if useAutoUploadSubFolder {
  187. serverUrl = utilityFileSystem.createGranularityPath(asset: asset, serverUrl: serverUrl)
  188. }
  189. // Check if is in upload
  190. if let results = database.getResultsMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileName == %@ AND session != ''",
  191. session.account,
  192. serverUrl,
  193. fileName), sortedByKeyPath: "fileName", ascending: false), !results.isEmpty {
  194. continue
  195. }
  196. let metadataForUpload = database.createMetadata(fileName: fileName,
  197. fileNameView: fileName,
  198. ocId: NSUUID().uuidString,
  199. serverUrl: serverUrl,
  200. url: "",
  201. contentType: "",
  202. session: session,
  203. sceneIdentifier: controller?.sceneIdentifier)
  204. if livePhoto {
  205. metadataForUpload.livePhotoFile = (metadataForUpload.fileName as NSString).deletingPathExtension + ".mov"
  206. }
  207. metadataForUpload.assetLocalIdentifier = asset.localIdentifier
  208. metadataForUpload.session = NCNetworking.shared.sessionUploadBackground
  209. metadataForUpload.sessionSelector = NCGlobal.shared.selectorUploadFile
  210. metadataForUpload.status = NCGlobal.shared.metadataStatusWaitUpload
  211. metadataForUpload.sessionDate = Date()
  212. if let previewStore = self.previewStore.first(where: { $0.id == asset.localIdentifier }), let data = previewStore.data {
  213. if metadataForUpload.contentType == "image/heic" {
  214. let fileNameNoExtension = (fileName as NSString).deletingPathExtension
  215. metadataForUpload.contentType = "image/jpeg"
  216. metadataForUpload.fileName = fileNameNoExtension + ".jpg"
  217. metadataForUpload.fileNameView = fileNameNoExtension + ".jpg"
  218. }
  219. let fileNamePath = utilityFileSystem.getDirectoryProviderStorageOcId(metadataForUpload.ocId, fileNameView: metadataForUpload.fileNameView)
  220. do {
  221. try data.write(to: URL(fileURLWithPath: fileNamePath))
  222. metadataForUpload.isExtractFile = true
  223. metadataForUpload.size = utilityFileSystem.getFileSize(filePath: fileNamePath)
  224. metadataForUpload.creationDate = asset.creationDate as? NSDate ?? (Date() as NSDate)
  225. metadataForUpload.date = asset.modificationDate as? NSDate ?? (Date() as NSDate)
  226. } catch { }
  227. }
  228. if let result = database.getMetadataConflict(account: session.account, serverUrl: serverUrl, fileNameView: fileName) {
  229. metadataForUpload.fileName = result.fileName
  230. metadatasUploadInConflict.append(metadataForUpload)
  231. } else {
  232. metadatasNOConflict.append(metadataForUpload)
  233. }
  234. }
  235. completion(metadatasNOConflict, metadatasUploadInConflict)
  236. }
  237. }