NCUploadAssets.swift 18 KB

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