NCUploadAssets.swift 18 KB

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