NCUploadAssets.swift 18 KB

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