NCUploadAssets.swift 15 KB

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