NCUploadAssets.swift 18 KB

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