NCUploadAssets.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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 originalImage: UIImage
  37. var cropImage: UIImage?
  38. var localIdentifier: String
  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(originalImage: image, localIdentifier: localIdentifier))
  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. var gridItems: [GridItem] = [GridItem()]
  85. @ObservedObject var uploadAssets: NCUploadAssets
  86. @Environment(\.presentationMode) var presentationMode
  87. init(uploadAssets: NCUploadAssets) {
  88. self.uploadAssets = uploadAssets
  89. uploadAssets.loadImages()
  90. }
  91. func getOriginalFilename() -> String {
  92. CCUtility.setOriginalFileName(isMaintainOriginalFilename, key: NCGlobal.shared.keyFileNameOriginal)
  93. if let asset = uploadAssets.assets.first?.phAsset, let name = (asset.value(forKey: "filename") as? String) {
  94. return name
  95. } else {
  96. return ""
  97. }
  98. }
  99. func setFileNameMask(fileName: String?) -> String {
  100. guard let asset = uploadAssets.assets.first?.phAsset else { return "" }
  101. var preview: String = ""
  102. let creationDate = asset.creationDate ?? Date()
  103. CCUtility.setOriginalFileName(isMaintainOriginalFilename, key: NCGlobal.shared.keyFileNameOriginal)
  104. CCUtility.setFileNameType(isAddFilenametype, key: NCGlobal.shared.keyFileNameType)
  105. if let fileName = fileName {
  106. let fileName = fileName.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
  107. if !fileName.isEmpty {
  108. CCUtility.setFileNameMask(fileName, key: NCGlobal.shared.keyFileNameMask)
  109. preview = CCUtility.createFileName(asset.value(forKey: "filename") as? String,
  110. fileDate: creationDate, fileType: asset.mediaType,
  111. keyFileName: NCGlobal.shared.keyFileNameMask,
  112. keyFileNameType: NCGlobal.shared.keyFileNameType,
  113. keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginal,
  114. forcedNewFileName: false)
  115. } else {
  116. CCUtility.setFileNameMask("", key: NCGlobal.shared.keyFileNameMask)
  117. preview = CCUtility.createFileName(asset.value(forKey: "filename") as? String,
  118. fileDate: creationDate,
  119. fileType: asset.mediaType,
  120. keyFileName: nil,
  121. keyFileNameType: NCGlobal.shared.keyFileNameType,
  122. keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginal,
  123. forcedNewFileName: false)
  124. }
  125. } else {
  126. CCUtility.setFileNameMask("", key: NCGlobal.shared.keyFileNameMask)
  127. preview = CCUtility.createFileName(asset.value(forKey: "filename") as? String,
  128. fileDate: creationDate,
  129. fileType: asset.mediaType,
  130. keyFileName: nil,
  131. keyFileNameType: NCGlobal.shared.keyFileNameType,
  132. keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginal,
  133. forcedNewFileName: false)
  134. }
  135. return String(format: NSLocalizedString("_preview_filename_", comment: ""), "MM, MMM, DD, YY, YYYY, HH, hh, mm, ss, ampm") + ":" + "\n\n" + preview
  136. }
  137. func save(completion: @escaping (_ metadatasNOConflict: [tableMetadata], _ metadatasUploadInConflict: [tableMetadata]) -> Void) {
  138. var metadatasNOConflict: [tableMetadata] = []
  139. var metadatasUploadInConflict: [tableMetadata] = []
  140. for asset in uploadAssets.assets {
  141. guard let asset = asset.phAsset else { continue }
  142. let serverUrl = uploadAssets.serverUrl
  143. var livePhoto: Bool = false
  144. let creationDate = asset.creationDate ?? Date()
  145. let fileName = CCUtility.createFileName(asset.value(forKey: "filename") as? String,
  146. fileDate: creationDate,
  147. fileType: asset.mediaType,
  148. keyFileName: NCGlobal.shared.keyFileNameMask,
  149. keyFileNameType: NCGlobal.shared.keyFileNameType,
  150. keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginal,
  151. forcedNewFileName: false)!
  152. if asset.mediaSubtypes.contains(.photoLive) && CCUtility.getLivePhoto() {
  153. livePhoto = true
  154. }
  155. // Check if is in upload
  156. let isRecordInSessions = NCManageDatabase.shared.getAdvancedMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileName == %@ AND session != ''", uploadAssets.userBaseUrl.account, serverUrl, fileName), sorted: "fileName", ascending: false)
  157. if !isRecordInSessions.isEmpty { continue }
  158. 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)
  159. metadata.assetLocalIdentifier = asset.localIdentifier
  160. metadata.session = NCNetworking.shared.sessionIdentifierBackground
  161. metadata.sessionSelector = NCGlobal.shared.selectorUploadFile
  162. metadata.status = NCGlobal.shared.metadataStatusWaitUpload
  163. // Modified
  164. if let previewStore = uploadAssets.previewStore.first(where: { $0.localIdentifier == asset.localIdentifier }), let image = previewStore.cropImage, let data = image.jpegData(compressionQuality: 1) {
  165. if metadata.contentType == "image/heic" {
  166. let fileNameNoExtension = (fileName as NSString).deletingPathExtension
  167. metadata.contentType = "image/jpeg"
  168. metadata.fileName = fileNameNoExtension + ".jpg"
  169. metadata.fileNameView = fileNameNoExtension + ".jpg"
  170. }
  171. let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  172. do {
  173. try data.write(to: URL(fileURLWithPath: fileNamePath))
  174. metadata.isExtractFile = true
  175. metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNamePath)
  176. metadata.creationDate = asset.creationDate as? NSDate ?? (Date() as NSDate)
  177. metadata.date = asset.modificationDate as? NSDate ?? (Date() as NSDate)
  178. } catch { }
  179. }
  180. if let result = NCManageDatabase.shared.getMetadataConflict(account: uploadAssets.userBaseUrl.account, serverUrl: serverUrl, fileNameView: fileName) {
  181. metadata.fileName = result.fileName
  182. metadatasUploadInConflict.append(metadata)
  183. } else {
  184. metadatasNOConflict.append(metadata)
  185. }
  186. }
  187. // Verify if file(s) exists
  188. if !metadatasUploadInConflict.isEmpty {
  189. completion(metadatasNOConflict, metadatasUploadInConflict)
  190. } else {
  191. NCNetworkingProcessUpload.shared.createProcessUploads(metadatas: metadatasNOConflict, completion: { _ in })
  192. completion(metadatasNOConflict, metadatasUploadInConflict)
  193. }
  194. }
  195. var body: some View {
  196. NavigationView {
  197. List {
  198. if !uploadAssets.previewStore.isEmpty {
  199. Section(header: Text(NSLocalizedString("_modify_photo_", comment: "")), footer: Text(NSLocalizedString("_modify_photo_desc_", comment: ""))) {
  200. ScrollView(.horizontal) {
  201. LazyHGrid(rows: gridItems, alignment: .center, spacing: 10) {
  202. ForEach(0..<uploadAssets.previewStore.count, id: \.self) { index in
  203. VStack {
  204. Image(uiImage: uploadAssets.previewStore[index].cropImage ?? uploadAssets.previewStore[index].originalImage)
  205. .resizable()
  206. .frame(width: 100, height: 100, alignment: .center)
  207. .cornerRadius(10)
  208. .scaledToFit()
  209. .onTapGesture {
  210. self.index = index
  211. isPresentedCrop = true
  212. }.fullScreenCover(isPresented: $isPresentedCrop) {
  213. ImageCropper(previewStore: $uploadAssets.previewStore, index: $index, cropShapeType: $cropShapeType, presetFixedRatioType: $presetFixedRatioType)
  214. .ignoresSafeArea()
  215. }
  216. }
  217. }
  218. }
  219. }
  220. }
  221. }
  222. Section(header: Text(NSLocalizedString("_mode_filename_", comment: ""))) {
  223. Toggle(NSLocalizedString("_maintain_original_filename_", comment: ""), isOn: $isMaintainOriginalFilename)
  224. .toggleStyle(SwitchToggleStyle(tint: Color(NCBrandColor.shared.brand)))
  225. if !isMaintainOriginalFilename {
  226. Toggle(NSLocalizedString("_add_filenametype_", comment: ""), isOn: $isAddFilenametype)
  227. .toggleStyle(SwitchToggleStyle(tint: Color(NCBrandColor.shared.brand)))
  228. }
  229. }
  230. Section {
  231. HStack {
  232. Label {
  233. if NCUtilityFileSystem.shared.getHomeServer(urlBase: uploadAssets.userBaseUrl.urlBase, userId: uploadAssets.userBaseUrl.userId) == uploadAssets.serverUrl {
  234. Text("/")
  235. .frame(maxWidth: .infinity, alignment: .trailing)
  236. } else {
  237. Text((uploadAssets.serverUrl as NSString).lastPathComponent)
  238. .frame(maxWidth: .infinity, alignment: .trailing)
  239. }
  240. } icon: {
  241. Image("folder")
  242. .renderingMode(.template)
  243. .resizable()
  244. .scaledToFit()
  245. .foregroundColor(Color(NCBrandColor.shared.brand))
  246. }
  247. }
  248. .contentShape(Rectangle())
  249. .onTapGesture {
  250. isPresentedSelect = true
  251. }
  252. HStack {
  253. Text(NSLocalizedString("_filename_", comment: ""))
  254. if isMaintainOriginalFilename {
  255. Text(getOriginalFilename())
  256. .frame(maxWidth: .infinity, alignment: .trailing)
  257. } else {
  258. TextField(NSLocalizedString("_enter_filename_", comment: ""), text: $fileName)
  259. .modifier(TextFieldClearButton(text: $fileName))
  260. .multilineTextAlignment(.trailing)
  261. }
  262. }
  263. if !isMaintainOriginalFilename {
  264. Text(setFileNameMask(fileName: fileName))
  265. .font(.system(size: 12))
  266. .foregroundColor(Color.gray)
  267. }
  268. }
  269. .complexModifier { view in
  270. if #available(iOS 15, *) {
  271. view.listRowSeparator(.hidden)
  272. }
  273. }
  274. Button(NSLocalizedString("_save_", comment: "")) {
  275. save { metadatasNOConflict, metadatasUploadInConflict in
  276. if metadatasUploadInConflict.isEmpty {
  277. uploadAssets.dismiss = true
  278. } else {
  279. uploadAssets.metadatasNOConflict = metadatasNOConflict
  280. uploadAssets.metadatasUploadInConflict = metadatasUploadInConflict
  281. isPresentedUploadConflict = true
  282. }
  283. }
  284. }
  285. .frame(maxWidth: .infinity)
  286. .buttonStyle(ButtonRounded(disabled: false))
  287. .listRowBackground(Color(UIColor.systemGroupedBackground))
  288. }
  289. .navigationTitle(NSLocalizedString("_upload_photos_videos_", comment: ""))
  290. .navigationBarTitleDisplayMode(.inline)
  291. }
  292. .sheet(isPresented: $isPresentedSelect) {
  293. SelectView(serverUrl: $uploadAssets.serverUrl)
  294. }
  295. .sheet(isPresented: $isPresentedUploadConflict) {
  296. UploadConflictView(delegate: uploadAssets, serverUrl: uploadAssets.serverUrl, metadatasUploadInConflict: uploadAssets.metadatasUploadInConflict, metadatasNOConflict: uploadAssets.metadatasNOConflict)
  297. }
  298. .onReceive(uploadAssets.$dismiss) { newValue in
  299. if newValue {
  300. presentationMode.wrappedValue.dismiss()
  301. }
  302. }
  303. }
  304. }
  305. // MARK: - ImageCropper
  306. struct ImageCropper: UIViewControllerRepresentable {
  307. @Binding var previewStore: [PreviewStore]
  308. @Binding var index: Int
  309. @Binding var cropShapeType: Mantis.CropShapeType
  310. @Binding var presetFixedRatioType: Mantis.PresetFixedRatioType
  311. @Environment(\.presentationMode) var presentationMode
  312. class Coordinator: CropViewControllerDelegate {
  313. var parent: ImageCropper
  314. var isModified: Bool = false
  315. init(_ parent: ImageCropper) {
  316. self.parent = parent
  317. }
  318. func cropViewControllerDidCrop(_ cropViewController: CropViewController, cropped: UIImage, transformation: Transformation, cropInfo: CropInfo) {
  319. if isModified {
  320. parent.previewStore[parent.index].cropImage = cropped
  321. } else {
  322. parent.previewStore[parent.index].cropImage = nil
  323. }
  324. parent.presentationMode.wrappedValue.dismiss()
  325. }
  326. func cropViewControllerDidCancel(_ cropViewController: CropViewController, original: UIImage) {
  327. parent.presentationMode.wrappedValue.dismiss()
  328. }
  329. func cropViewControllerDidImageTransformed(_ cropViewController: Mantis.CropViewController) {
  330. isModified = true
  331. }
  332. func cropViewControllerDidFailToCrop(_ cropViewController: CropViewController, original: UIImage) { }
  333. func cropViewControllerDidBeginResize(_ cropViewController: CropViewController) { }
  334. func cropViewControllerDidEndResize(_ cropViewController: CropViewController, original: UIImage, cropInfo: CropInfo) { }
  335. }
  336. func makeCoordinator() -> Coordinator {
  337. Coordinator(self)
  338. }
  339. func makeUIViewController(context: Context) -> CropViewController {
  340. var config = Mantis.Config()
  341. if let bundleIdentifier = Bundle.main.bundleIdentifier {
  342. config.localizationConfig.bundle = Bundle(identifier: bundleIdentifier)
  343. config.localizationConfig.tableName = "Localizable"
  344. }
  345. config.cropViewConfig.cropShapeType = cropShapeType
  346. config.presetFixedRatioType = presetFixedRatioType
  347. let image = previewStore[index].originalImage
  348. let cropViewController = Mantis.cropViewController(image: image, config: config)
  349. cropViewController.delegate = context.coordinator
  350. return cropViewController
  351. }
  352. func updateUIViewController(_ uiViewController: CropViewController, context: Context) { }
  353. }
  354. // MARK: - Preview
  355. struct UploadAssetsView_Previews: PreviewProvider {
  356. static var previews: some View {
  357. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  358. let uploadAssets = NCUploadAssets(assets: [], serverUrl: "/", userBaseUrl: appDelegate)
  359. UploadAssetsView(uploadAssets: uploadAssets)
  360. }
  361. }
  362. }