NCUploadAssets.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. //
  2. // NCUploadAssets.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. class NCHostingUploadAssetsView: NSObject {
  28. func makeShipDetailsUI(assets: [TLPHAsset], serverUrl: String, userBaseUrl: NCUserBaseUrl) -> UIViewController {
  29. let uploadAssets = NCUploadAssets(assets: assets, serverUrl: serverUrl, userBaseUrl: userBaseUrl )
  30. let details = UploadAssetsView(uploadAssets: uploadAssets)
  31. return UIHostingController(rootView: details)
  32. }
  33. }
  34. // MARK: - Class
  35. struct PreviewStore {
  36. var image: UIImage
  37. var localIdentifier: String
  38. var hasChanges: Bool
  39. }
  40. class NCUploadAssets: NSObject, ObservableObject, NCCreateFormUploadConflictDelegate {
  41. @Published var serverUrl: String
  42. @Published var assets: [TLPHAsset]
  43. @Published var userBaseUrl: NCUserBaseUrl
  44. @Published var dismiss = false
  45. @Published var previewStore: [PreviewStore] = []
  46. var metadatasNOConflict: [tableMetadata] = []
  47. var metadatasUploadInConflict: [tableMetadata] = []
  48. init(assets: [TLPHAsset], serverUrl: String, userBaseUrl: NCUserBaseUrl) {
  49. self.assets = assets
  50. self.serverUrl = serverUrl
  51. self.userBaseUrl = userBaseUrl
  52. }
  53. func loadImages() {
  54. DispatchQueue.global().async {
  55. for asset in self.assets {
  56. guard asset.type == .photo, let image = asset.fullResolutionImage, let localIdentifier = asset.phAsset?.localIdentifier else { continue }
  57. self.previewStore.append(PreviewStore(image: image, localIdentifier: localIdentifier, hasChanges: false))
  58. }
  59. }
  60. }
  61. func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
  62. if let metadatas = metadatas {
  63. NCNetworkingProcessUpload.shared.createProcessUploads(metadatas: metadatas, completion: { _ in
  64. self.dismiss = true
  65. })
  66. } else {
  67. self.dismiss = true
  68. }
  69. }
  70. }
  71. // MARK: - View
  72. struct UploadAssetsView: View {
  73. @State private var fileName: String = CCUtility.getFileNameMask(NCGlobal.shared.keyFileNameMask)
  74. @State private var isMaintainOriginalFilename: Bool = CCUtility.getOriginalFileName(NCGlobal.shared.keyFileNameOriginal)
  75. @State private var isAddFilenametype: Bool = CCUtility.getFileNameType(NCGlobal.shared.keyFileNameType)
  76. @State private var isPresentedSelect = false
  77. @State private var isPresentedUploadConflict = false
  78. // Crop
  79. @State private var isPresentedCrop = false
  80. @State private var index: Int = 0
  81. @State private var imageForCrop: UIImage = UIImage()
  82. @State private var cropShapeType: Mantis.CropShapeType = .rect
  83. @State private var presetFixedRatioType: Mantis.PresetFixedRatioType = .canUseMultiplePresetFixedRatio()
  84. @State private var fileNamePath = NSTemporaryDirectory() + "QLTmp.jpg"
  85. @State private var metadata: tableMetadata?
  86. var gridItems: [GridItem] = [GridItem()]
  87. @ObservedObject var uploadAssets: NCUploadAssets
  88. @Environment(\.presentationMode) var presentationMode
  89. init(uploadAssets: NCUploadAssets) {
  90. self.uploadAssets = uploadAssets
  91. uploadAssets.loadImages()
  92. }
  93. func getOriginalFilename() -> String {
  94. CCUtility.setOriginalFileName(isMaintainOriginalFilename, key: NCGlobal.shared.keyFileNameOriginal)
  95. if let asset = uploadAssets.assets.first?.phAsset, let name = (asset.value(forKey: "filename") as? String) {
  96. return name
  97. } else {
  98. return ""
  99. }
  100. }
  101. func setFileNameMask(fileName: String?) -> String {
  102. guard let asset = uploadAssets.assets.first?.phAsset else { return "" }
  103. var preview: String = ""
  104. let creationDate = asset.creationDate ?? Date()
  105. CCUtility.setOriginalFileName(isMaintainOriginalFilename, key: NCGlobal.shared.keyFileNameOriginal)
  106. CCUtility.setFileNameType(isAddFilenametype, key: NCGlobal.shared.keyFileNameType)
  107. if let fileName = fileName {
  108. let fileName = fileName.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
  109. if !fileName.isEmpty {
  110. CCUtility.setFileNameMask(fileName, key: NCGlobal.shared.keyFileNameMask)
  111. preview = CCUtility.createFileName(asset.value(forKey: "filename") as? String,
  112. fileDate: creationDate, fileType: asset.mediaType,
  113. keyFileName: NCGlobal.shared.keyFileNameMask,
  114. keyFileNameType: NCGlobal.shared.keyFileNameType,
  115. keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginal,
  116. forcedNewFileName: false)
  117. } else {
  118. CCUtility.setFileNameMask("", key: NCGlobal.shared.keyFileNameMask)
  119. preview = CCUtility.createFileName(asset.value(forKey: "filename") as? String,
  120. fileDate: creationDate,
  121. fileType: asset.mediaType,
  122. keyFileName: nil,
  123. keyFileNameType: NCGlobal.shared.keyFileNameType,
  124. keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginal,
  125. forcedNewFileName: false)
  126. }
  127. } else {
  128. CCUtility.setFileNameMask("", key: NCGlobal.shared.keyFileNameMask)
  129. preview = CCUtility.createFileName(asset.value(forKey: "filename") as? String,
  130. fileDate: creationDate,
  131. fileType: asset.mediaType,
  132. keyFileName: nil,
  133. keyFileNameType: NCGlobal.shared.keyFileNameType,
  134. keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginal,
  135. forcedNewFileName: false)
  136. }
  137. return String(format: NSLocalizedString("_preview_filename_", comment: ""), "MM, MMM, DD, YY, YYYY, HH, hh, mm, ss, ampm") + ":" + "\n\n" + preview
  138. }
  139. func save(completion: @escaping (_ metadatasNOConflict: [tableMetadata], _ metadatasUploadInConflict: [tableMetadata]) -> Void) {
  140. var metadatasNOConflict: [tableMetadata] = []
  141. var metadatasUploadInConflict: [tableMetadata] = []
  142. for asset in uploadAssets.assets {
  143. guard let asset = asset.phAsset else { continue }
  144. let serverUrl = uploadAssets.serverUrl
  145. var livePhoto: Bool = false
  146. let creationDate = asset.creationDate ?? Date()
  147. let fileName = CCUtility.createFileName(asset.value(forKey: "filename") as? String,
  148. fileDate: creationDate,
  149. fileType: asset.mediaType,
  150. keyFileName: NCGlobal.shared.keyFileNameMask,
  151. keyFileNameType: NCGlobal.shared.keyFileNameType,
  152. keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginal,
  153. forcedNewFileName: false)!
  154. if asset.mediaSubtypes.contains(.photoLive) && CCUtility.getLivePhoto() {
  155. livePhoto = true
  156. }
  157. // Check if is in upload
  158. let isRecordInSessions = NCManageDatabase.shared.getAdvancedMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileName == %@ AND session != ''", uploadAssets.userBaseUrl.account, serverUrl, fileName), sorted: "fileName", ascending: false)
  159. if !isRecordInSessions.isEmpty { continue }
  160. let metadata = NCManageDatabase.shared.createMetadata(account: uploadAssets.userBaseUrl.account, user: uploadAssets.userBaseUrl.user, userId: uploadAssets.userBaseUrl.userId, fileName: fileName, fileNameView: fileName, ocId: NSUUID().uuidString, serverUrl: serverUrl, urlBase: uploadAssets.userBaseUrl.urlBase, url: "", contentType: "", isLivePhoto: livePhoto)
  161. metadata.assetLocalIdentifier = asset.localIdentifier
  162. metadata.session = NCNetworking.shared.sessionIdentifierBackground
  163. metadata.sessionSelector = NCGlobal.shared.selectorUploadFile
  164. metadata.status = NCGlobal.shared.metadataStatusWaitUpload
  165. // Modified
  166. if let previewStore = uploadAssets.previewStore.first(where: { $0.localIdentifier == asset.localIdentifier }), previewStore.hasChanges, let data = previewStore.image.jpegData(compressionQuality: 1) {
  167. if metadata.contentType == "image/heic" {
  168. let fileNameNoExtension = (fileName as NSString).deletingPathExtension
  169. metadata.contentType = "image/jpeg"
  170. metadata.fileName = fileNameNoExtension + ".jpg"
  171. metadata.fileNameView = fileNameNoExtension + ".jpg"
  172. }
  173. let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  174. do {
  175. try data.write(to: URL(fileURLWithPath: fileNamePath))
  176. metadata.isExtractFile = true
  177. metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNamePath)
  178. metadata.creationDate = asset.creationDate as? NSDate ?? (Date() as NSDate)
  179. metadata.date = asset.modificationDate as? NSDate ?? (Date() as NSDate)
  180. } catch { }
  181. }
  182. if let result = NCManageDatabase.shared.getMetadataConflict(account: uploadAssets.userBaseUrl.account, serverUrl: serverUrl, fileNameView: fileName) {
  183. metadata.fileName = result.fileName
  184. metadatasUploadInConflict.append(metadata)
  185. } else {
  186. metadatasNOConflict.append(metadata)
  187. }
  188. }
  189. // Verify if file(s) exists
  190. if !metadatasUploadInConflict.isEmpty {
  191. completion(metadatasNOConflict, metadatasUploadInConflict)
  192. } else {
  193. NCNetworkingProcessUpload.shared.createProcessUploads(metadatas: metadatasNOConflict, completion: { _ in })
  194. completion(metadatasNOConflict, metadatasUploadInConflict)
  195. }
  196. }
  197. func copyImageforQL() {
  198. let image = uploadAssets.previewStore[index].image
  199. if let data = image.jpegData(compressionQuality: 1) {
  200. try? data.write(to: URL(fileURLWithPath: fileNamePath))
  201. }
  202. }
  203. var body: some View {
  204. NavigationView {
  205. List {
  206. if !uploadAssets.previewStore.isEmpty {
  207. Section(header: Text(NSLocalizedString("_modify_photo_", comment: "")), footer: Text(NSLocalizedString("_modify_photo_desc_", comment: ""))) {
  208. ScrollView(.horizontal) {
  209. LazyHGrid(rows: gridItems, alignment: .center, spacing: 10) {
  210. ForEach(0..<uploadAssets.previewStore.count, id: \.self) { index in
  211. VStack {
  212. Image(uiImage: uploadAssets.previewStore[index].image)
  213. .resizable()
  214. .frame(width: 100, height: 100, alignment: .center)
  215. .cornerRadius(10)
  216. .scaledToFit()
  217. .onTapGesture {
  218. self.index = index
  219. isPresentedCrop = true
  220. copyImageforQL()
  221. }.fullScreenCover(isPresented: $isPresentedCrop) {
  222. ViewerQuickLook(url: URL(fileURLWithPath: fileNamePath), isPresented: $isPresentedCrop, previewStore: $uploadAssets.previewStore[index])
  223. .ignoresSafeArea()
  224. }
  225. }
  226. }
  227. }
  228. }
  229. }
  230. }
  231. Section(header: Text(NSLocalizedString("_mode_filename_", comment: ""))) {
  232. Toggle(NSLocalizedString("_maintain_original_filename_", comment: ""), isOn: $isMaintainOriginalFilename)
  233. .toggleStyle(SwitchToggleStyle(tint: Color(NCBrandColor.shared.brand)))
  234. if !isMaintainOriginalFilename {
  235. Toggle(NSLocalizedString("_add_filenametype_", comment: ""), isOn: $isAddFilenametype)
  236. .toggleStyle(SwitchToggleStyle(tint: Color(NCBrandColor.shared.brand)))
  237. }
  238. }
  239. Section {
  240. HStack {
  241. Label {
  242. if NCUtilityFileSystem.shared.getHomeServer(urlBase: uploadAssets.userBaseUrl.urlBase, userId: uploadAssets.userBaseUrl.userId) == uploadAssets.serverUrl {
  243. Text("/")
  244. .frame(maxWidth: .infinity, alignment: .trailing)
  245. } else {
  246. Text((uploadAssets.serverUrl as NSString).lastPathComponent)
  247. .frame(maxWidth: .infinity, alignment: .trailing)
  248. }
  249. } icon: {
  250. Image("folder")
  251. .renderingMode(.template)
  252. .resizable()
  253. .scaledToFit()
  254. .foregroundColor(Color(NCBrandColor.shared.brand))
  255. }
  256. }
  257. .contentShape(Rectangle())
  258. .onTapGesture {
  259. isPresentedSelect = true
  260. }
  261. HStack {
  262. Text(NSLocalizedString("_filename_", comment: ""))
  263. if isMaintainOriginalFilename {
  264. Text(getOriginalFilename())
  265. .frame(maxWidth: .infinity, alignment: .trailing)
  266. } else {
  267. TextField(NSLocalizedString("_enter_filename_", comment: ""), text: $fileName)
  268. .modifier(TextFieldClearButton(text: $fileName))
  269. .multilineTextAlignment(.trailing)
  270. }
  271. }
  272. if !isMaintainOriginalFilename {
  273. Text(setFileNameMask(fileName: fileName))
  274. .font(.system(size: 12))
  275. .foregroundColor(Color.gray)
  276. }
  277. }
  278. .complexModifier { view in
  279. if #available(iOS 15, *) {
  280. view.listRowSeparator(.hidden)
  281. }
  282. }
  283. Button(NSLocalizedString("_save_", comment: "")) {
  284. save { metadatasNOConflict, metadatasUploadInConflict in
  285. if metadatasUploadInConflict.isEmpty {
  286. uploadAssets.dismiss = true
  287. } else {
  288. uploadAssets.metadatasNOConflict = metadatasNOConflict
  289. uploadAssets.metadatasUploadInConflict = metadatasUploadInConflict
  290. isPresentedUploadConflict = true
  291. }
  292. }
  293. }
  294. .frame(maxWidth: .infinity)
  295. .buttonStyle(ButtonRounded(disabled: false))
  296. .listRowBackground(Color(UIColor.systemGroupedBackground))
  297. }
  298. .navigationTitle(NSLocalizedString("_upload_photos_videos_", comment: ""))
  299. .navigationBarTitleDisplayMode(.inline)
  300. }
  301. .sheet(isPresented: $isPresentedSelect) {
  302. SelectView(serverUrl: $uploadAssets.serverUrl)
  303. }
  304. .sheet(isPresented: $isPresentedUploadConflict) {
  305. UploadConflictView(delegate: uploadAssets, serverUrl: uploadAssets.serverUrl, metadatasUploadInConflict: uploadAssets.metadatasUploadInConflict, metadatasNOConflict: uploadAssets.metadatasNOConflict)
  306. }
  307. .onReceive(uploadAssets.$dismiss) { newValue in
  308. if newValue {
  309. presentationMode.wrappedValue.dismiss()
  310. }
  311. }
  312. }
  313. }
  314. // MARK: - Preview
  315. struct UploadAssetsView_Previews: PreviewProvider {
  316. static var previews: some View {
  317. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  318. let uploadAssets = NCUploadAssets(assets: [], serverUrl: "/", userBaseUrl: appDelegate)
  319. UploadAssetsView(uploadAssets: uploadAssets)
  320. }
  321. }
  322. }