NCUploadAssets.swift 21 KB

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