NCUploadAssets.swift 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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. import QuickLook
  29. class NCHostingUploadAssetsView: NSObject {
  30. func makeShipDetailsUI(assets: [TLPHAsset], serverUrl: String, userBaseUrl: NCUserBaseUrl) -> UIViewController {
  31. let uploadAssets = NCUploadAssets(assets: assets, serverUrl: serverUrl, userBaseUrl: userBaseUrl )
  32. let details = UploadAssetsView(uploadAssets: uploadAssets)
  33. return UIHostingController(rootView: details)
  34. }
  35. }
  36. // MARK: - Class
  37. struct PreviewStore {
  38. var id: String
  39. var asset: TLPHAsset
  40. var assetType: TLPHAsset.AssetType
  41. var data: Data?
  42. var fileName: String
  43. var image: UIImage
  44. }
  45. class NCUploadAssets: NSObject, ObservableObject, NCCreateFormUploadConflictDelegate {
  46. @Published var serverUrl: String
  47. @Published var assets: [TLPHAsset]
  48. @Published var userBaseUrl: NCUserBaseUrl
  49. @Published var dismiss = false
  50. @Published var isUseAutoUploadFolder: Bool = false
  51. @Published var isUseAutoUploadSubFolder: Bool = false
  52. @Published var previewStore: [PreviewStore] = []
  53. @Published var showHUD: Bool = false
  54. @Published var uploadInProgress: Bool = false
  55. var metadatasNOConflict: [tableMetadata] = []
  56. var metadatasUploadInConflict: [tableMetadata] = []
  57. var timer: Timer?
  58. init(assets: [TLPHAsset], serverUrl: String, userBaseUrl: NCUserBaseUrl) {
  59. self.assets = assets
  60. self.serverUrl = serverUrl
  61. self.userBaseUrl = userBaseUrl
  62. }
  63. func loadImages() {
  64. var previewStore: [PreviewStore] = []
  65. DispatchQueue.global().async {
  66. for asset in self.assets {
  67. guard let image = asset.fullResolutionImage?.resizeImage(size: CGSize(width: 300, height: 300), isAspectRation: true), let localIdentifier = asset.phAsset?.localIdentifier else { continue }
  68. previewStore.append(PreviewStore(id: localIdentifier, asset: asset, assetType: asset.type, fileName: "", image: image))
  69. }
  70. DispatchQueue.main.async {
  71. self.previewStore = previewStore
  72. }
  73. }
  74. }
  75. func startTimer(navigationItem: UINavigationItem) {
  76. self.timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true, block: { _ in
  77. guard let buttonDone = navigationItem.leftBarButtonItems?.first, let buttonCrop = navigationItem.leftBarButtonItems?.last else { return }
  78. buttonCrop.isEnabled = true
  79. buttonDone.isEnabled = true
  80. if let markup = navigationItem.rightBarButtonItems?.first(where: { $0.accessibilityIdentifier == "QLOverlayMarkupButtonAccessibilityIdentifier" }) {
  81. if let originalButton = markup.value(forKey: "originalButton") as AnyObject? {
  82. if let symbolImageName = originalButton.value(forKey: "symbolImageName") as? String {
  83. if symbolImageName == "pencil.tip.crop.circle.on" {
  84. buttonCrop.isEnabled = false
  85. buttonDone.isEnabled = false
  86. }
  87. }
  88. }
  89. }
  90. })
  91. }
  92. func stopTimer() {
  93. self.timer?.invalidate()
  94. }
  95. func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
  96. guard let metadatas = metadatas else {
  97. self.showHUD = false
  98. self.uploadInProgress.toggle()
  99. return
  100. }
  101. func createProcessUploads() {
  102. if !self.dismiss {
  103. NCNetworkingProcessUpload.shared.createProcessUploads(metadatas: metadatas, completion: { _ in
  104. self.dismiss = true
  105. })
  106. }
  107. }
  108. if isUseAutoUploadFolder {
  109. DispatchQueue.global().async {
  110. let assets = self.assets.compactMap { $0.phAsset }
  111. let result = NCNetworking.shared.createFolder(assets: assets, selector: NCGlobal.shared.selectorUploadFile, useSubFolder: self.isUseAutoUploadSubFolder, account: self.userBaseUrl.account, urlBase: self.userBaseUrl.urlBase, userId: self.userBaseUrl.userId, withPush: false)
  112. DispatchQueue.main.async {
  113. self.showHUD = false
  114. self.uploadInProgress.toggle()
  115. if result {
  116. createProcessUploads()
  117. } else {
  118. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_error_createsubfolders_upload_")
  119. NCContentPresenter.shared.showError(error: error)
  120. }
  121. }
  122. }
  123. } else {
  124. createProcessUploads()
  125. }
  126. }
  127. }
  128. // MARK: - View
  129. struct UploadAssetsView: View {
  130. @State private var fileName: String = CCUtility.getFileNameMask(NCGlobal.shared.keyFileNameMask)
  131. @State private var isMaintainOriginalFilename: Bool = CCUtility.getOriginalFileName(NCGlobal.shared.keyFileNameOriginal)
  132. @State private var isAddFilenametype: Bool = CCUtility.getFileNameType(NCGlobal.shared.keyFileNameType)
  133. @State private var isPresentedSelect = false
  134. @State private var isPresentedUploadConflict = false
  135. @State private var isPresentedQuickLook = false
  136. @State private var isPresentedAlert = false
  137. @State private var fileNamePath = NSTemporaryDirectory() + "Photo.jpg"
  138. @State private var renameFileName: String = ""
  139. @State private var renameIndex: Int = 0
  140. @State private var metadata: tableMetadata?
  141. @State private var index: Int = 0
  142. var gridItems: [GridItem] = [GridItem()]
  143. @ObservedObject var uploadAssets: NCUploadAssets
  144. @Environment(\.presentationMode) var presentationMode
  145. init(uploadAssets: NCUploadAssets) {
  146. self.uploadAssets = uploadAssets
  147. uploadAssets.loadImages()
  148. }
  149. func getTextServerUrl(_ serverUrl: String) -> String {
  150. if let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", uploadAssets.userBaseUrl.account, serverUrl)), let metadata = NCManageDatabase.shared.getMetadataFromOcId(directory.ocId) {
  151. return (metadata.fileNameView)
  152. } else {
  153. return (serverUrl as NSString).lastPathComponent
  154. }
  155. }
  156. private func setFileNameMaskForPreview(fileName: String?) -> String {
  157. guard let asset = uploadAssets.assets.first?.phAsset else { return "" }
  158. var preview: String = ""
  159. let creationDate = asset.creationDate ?? Date()
  160. CCUtility.setOriginalFileName(isMaintainOriginalFilename, key: NCGlobal.shared.keyFileNameOriginal)
  161. CCUtility.setFileNameType(isAddFilenametype, key: NCGlobal.shared.keyFileNameType)
  162. CCUtility.setFileNameMask(fileName, key: NCGlobal.shared.keyFileNameMask)
  163. preview = CCUtility.createFileName(
  164. getOriginalFilenameForPreview() as String,
  165. fileDate: creationDate,
  166. fileType: asset.mediaType,
  167. keyFileName: fileName.isEmptyOrNil ? nil : NCGlobal.shared.keyFileNameMask,
  168. keyFileNameType: NCGlobal.shared.keyFileNameType,
  169. keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginal,
  170. forcedNewFileName: false
  171. )
  172. let trimmedPreview = preview.trimmingCharacters(in: .whitespacesAndNewlines)
  173. return String(format: NSLocalizedString("_preview_filename_", comment: ""), "MM, MMM, DD, YY, YYYY, HH, hh, mm, ss, ampm") + ":" + "\n\n" + (trimmedPreview as NSString).deletingPathExtension
  174. }
  175. private func save(completion: @escaping (_ metadatasNOConflict: [tableMetadata], _ metadatasUploadInConflict: [tableMetadata]) -> Void) {
  176. var metadatasNOConflict: [tableMetadata] = []
  177. var metadatasUploadInConflict: [tableMetadata] = []
  178. let autoUploadPath = NCManageDatabase.shared.getAccountAutoUploadPath(urlBase: uploadAssets.userBaseUrl.urlBase, userId: uploadAssets.userBaseUrl.userId, account: uploadAssets.userBaseUrl.account)
  179. var serverUrl = uploadAssets.isUseAutoUploadFolder ? autoUploadPath : uploadAssets.serverUrl
  180. let autoUploadSubfolderGranularity = NCManageDatabase.shared.getAccountAutoUploadSubfolderGranularity()
  181. for tlAsset in uploadAssets.assets {
  182. guard let asset = tlAsset.phAsset, let previewStore = uploadAssets.previewStore.first(where: { $0.id == asset.localIdentifier }) else { continue }
  183. let assetFileName = asset.originalFilename
  184. var livePhoto: Bool = false
  185. let creationDate = asset.creationDate ?? Date()
  186. let ext = assetFileName.pathExtension.lowercased()
  187. let fileName = previewStore.fileName.isEmpty
  188. ? CCUtility.createFileName(assetFileName as String,
  189. fileDate: creationDate,
  190. fileType: asset.mediaType,
  191. keyFileName: NCGlobal.shared.keyFileNameMask,
  192. keyFileNameType: NCGlobal.shared.keyFileNameType,
  193. keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginal,
  194. forcedNewFileName: false)!
  195. : (previewStore.fileName + "." + ext)
  196. if previewStore.assetType == .livePhoto && CCUtility.getLivePhoto() && previewStore.data == nil {
  197. livePhoto = true
  198. }
  199. // Auto upload with subfolder
  200. if uploadAssets.isUseAutoUploadSubFolder {
  201. let dateFormatter = DateFormatter()
  202. dateFormatter.dateFormat = "yyyy"
  203. let yearString = dateFormatter.string(from: creationDate)
  204. dateFormatter.dateFormat = "MM"
  205. let monthString = dateFormatter.string(from: creationDate)
  206. dateFormatter.dateFormat = "dd"
  207. let dayString = dateFormatter.string(from: creationDate)
  208. if autoUploadSubfolderGranularity == 0 {
  209. serverUrl = autoUploadPath + "/" + yearString
  210. } else if autoUploadSubfolderGranularity == 2 {
  211. serverUrl = autoUploadPath + "/" + yearString + "/" + monthString + "/" + dayString
  212. } else { // Month Granularity is default
  213. serverUrl = autoUploadPath + "/" + yearString + "/" + monthString
  214. }
  215. }
  216. // Check if is in upload
  217. let isRecordInSessions = NCManageDatabase.shared.getAdvancedMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileName == %@ AND session != ''", uploadAssets.userBaseUrl.account, serverUrl, fileName), sorted: "fileName", ascending: false)
  218. if !isRecordInSessions.isEmpty { continue }
  219. 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)
  220. metadata.assetLocalIdentifier = asset.localIdentifier
  221. metadata.session = NCNetworking.shared.sessionIdentifierBackground
  222. metadata.sessionSelector = NCGlobal.shared.selectorUploadFile
  223. metadata.status = NCGlobal.shared.metadataStatusWaitUpload
  224. // Modified
  225. if let previewStore = uploadAssets.previewStore.first(where: { $0.id == asset.localIdentifier }), let data = previewStore.data {
  226. if metadata.contentType == "image/heic" {
  227. let fileNameNoExtension = (fileName as NSString).deletingPathExtension
  228. metadata.contentType = "image/jpeg"
  229. metadata.fileName = fileNameNoExtension + ".jpg"
  230. metadata.fileNameView = fileNameNoExtension + ".jpg"
  231. }
  232. let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  233. do {
  234. try data.write(to: URL(fileURLWithPath: fileNamePath))
  235. metadata.isExtractFile = true
  236. metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNamePath)
  237. metadata.creationDate = asset.creationDate as? NSDate ?? (Date() as NSDate)
  238. metadata.date = asset.modificationDate as? NSDate ?? (Date() as NSDate)
  239. } catch { }
  240. }
  241. if let result = NCManageDatabase.shared.getMetadataConflict(account: uploadAssets.userBaseUrl.account, serverUrl: serverUrl, fileNameView: fileName) {
  242. metadata.fileName = result.fileName
  243. metadatasUploadInConflict.append(metadata)
  244. } else {
  245. metadatasNOConflict.append(metadata)
  246. }
  247. }
  248. completion(metadatasNOConflict, metadatasUploadInConflict)
  249. }
  250. private func presentedQuickLook(index: Int) {
  251. var image: UIImage?
  252. if let imageData = uploadAssets.previewStore[index].data {
  253. image = UIImage(data: imageData)
  254. } else if let imageFullResolution = uploadAssets.previewStore[index].asset.fullResolutionImage?.fixedOrientation() {
  255. image = imageFullResolution
  256. }
  257. if let image = image {
  258. if let data = image.jpegData(compressionQuality: 1) {
  259. do {
  260. try data.write(to: URL(fileURLWithPath: fileNamePath))
  261. self.index = index
  262. isPresentedQuickLook = true
  263. } catch {
  264. }
  265. }
  266. }
  267. }
  268. private func deleteAsset(index: Int) {
  269. uploadAssets.assets.remove(at: index)
  270. uploadAssets.previewStore.remove(at: index)
  271. if uploadAssets.previewStore.isEmpty {
  272. uploadAssets.dismiss = true
  273. }
  274. }
  275. private func getOriginalFilenameForPreview() -> NSString {
  276. CCUtility.setOriginalFileName(isMaintainOriginalFilename, key: NCGlobal.shared.keyFileNameOriginal)
  277. if let asset = uploadAssets.assets.first?.phAsset {
  278. return asset.originalFilename
  279. } else {
  280. return ""
  281. }
  282. }
  283. var body: some View {
  284. NavigationView {
  285. ZStack(alignment: .top) {
  286. List {
  287. Section(footer: Text(NSLocalizedString("_modify_image_desc_", comment: ""))) {
  288. ScrollView(.horizontal) {
  289. LazyHGrid(rows: gridItems, alignment: .center, spacing: 10) {
  290. ForEach(0..<uploadAssets.previewStore.count, id: \.self) { index in
  291. let item = uploadAssets.previewStore[index]
  292. Menu {
  293. Button(action: {
  294. renameFileName = uploadAssets.previewStore[index].fileName
  295. renameIndex = index
  296. isPresentedAlert = true
  297. }) {
  298. Label(NSLocalizedString("_rename_", comment: ""), systemImage: "pencil")
  299. }
  300. if item.asset.type == .photo || item.asset.type == .livePhoto {
  301. Button(action: {
  302. presentedQuickLook(index: index)
  303. }) {
  304. Label(NSLocalizedString("_modify_", comment: ""), systemImage: "pencil.tip.crop.circle")
  305. }
  306. }
  307. if item.data != nil {
  308. Button(action: {
  309. if let image = uploadAssets.previewStore[index].asset.fullResolutionImage?.resizeImage(size: CGSize(width: 300, height: 300), isAspectRation: true) {
  310. uploadAssets.previewStore[index].image = image
  311. uploadAssets.previewStore[index].data = nil
  312. uploadAssets.previewStore[index].assetType = uploadAssets.previewStore[index].asset.type
  313. }
  314. }) {
  315. Label(NSLocalizedString("_undo_modify_", comment: ""), systemImage: "arrow.uturn.backward.circle")
  316. }
  317. }
  318. if item.data == nil && item.asset.type == .livePhoto && item.assetType == .livePhoto {
  319. Button(action: {
  320. uploadAssets.previewStore[index].assetType = .photo
  321. }) {
  322. Label(NSLocalizedString("_disable_livephoto_", comment: ""), systemImage: "livephoto.slash")
  323. }
  324. } else if item.data == nil && item.asset.type == .livePhoto && item.assetType == .photo {
  325. Button(action: {
  326. uploadAssets.previewStore[index].assetType = .livePhoto
  327. }) {
  328. Label(NSLocalizedString("_enable_livephoto_", comment: ""), systemImage: "livephoto")
  329. }
  330. }
  331. Button(role: .destructive, action: {
  332. deleteAsset(index: index)
  333. }) {
  334. Label(NSLocalizedString("_remove_", comment: ""), systemImage: "trash")
  335. }
  336. } label: {
  337. ImageAsset(uploadAssets: uploadAssets, index: index)
  338. .alert(NSLocalizedString("_rename_file_", comment: ""), isPresented: $isPresentedAlert) {
  339. TextField(NSLocalizedString("_enter_filename_", comment: ""), text: $renameFileName)
  340. .autocapitalization(.none)
  341. .autocorrectionDisabled()
  342. Button(NSLocalizedString("_rename_", comment: ""), action: {
  343. uploadAssets.previewStore[renameIndex].fileName = renameFileName.trimmingCharacters(in: .whitespacesAndNewlines)
  344. })
  345. Button(NSLocalizedString("_cancel_", comment: ""), role: .cancel, action: {})
  346. }
  347. }
  348. }
  349. }
  350. }
  351. }
  352. .redacted(reason: uploadAssets.previewStore.isEmpty ? .placeholder : [])
  353. Section {
  354. Toggle(isOn: $isMaintainOriginalFilename, label: {
  355. Text(NSLocalizedString("_maintain_original_filename_", comment: ""))
  356. .font(.system(size: 15))
  357. })
  358. .toggleStyle(SwitchToggleStyle(tint: Color(NCBrandColor.shared.brand)))
  359. if !isMaintainOriginalFilename {
  360. Toggle(isOn: $isAddFilenametype, label: {
  361. Text(NSLocalizedString("_add_filenametype_", comment: ""))
  362. .font(.system(size: 15))
  363. })
  364. .toggleStyle(SwitchToggleStyle(tint: Color(NCBrandColor.shared.brand)))
  365. }
  366. }
  367. Section {
  368. Toggle(isOn: $uploadAssets.isUseAutoUploadFolder, label: {
  369. Text(NSLocalizedString("_use_folder_auto_upload_", comment: ""))
  370. .font(.system(size: 15))
  371. })
  372. .toggleStyle(SwitchToggleStyle(tint: Color(NCBrandColor.shared.brand)))
  373. if uploadAssets.isUseAutoUploadFolder {
  374. Toggle(isOn: $uploadAssets.isUseAutoUploadSubFolder, label: {
  375. Text(NSLocalizedString("_autoupload_create_subfolder_", comment: ""))
  376. .font(.system(size: 15))
  377. })
  378. .toggleStyle(SwitchToggleStyle(tint: Color(NCBrandColor.shared.brand)))
  379. }
  380. if !uploadAssets.isUseAutoUploadFolder {
  381. HStack {
  382. Label {
  383. if NCUtilityFileSystem.shared.getHomeServer(urlBase: uploadAssets.userBaseUrl.urlBase, userId: uploadAssets.userBaseUrl.userId) == uploadAssets.serverUrl {
  384. Text("/")
  385. .font(.system(size: 15))
  386. .frame(maxWidth: .infinity, alignment: .trailing)
  387. } else {
  388. Text(self.getTextServerUrl(uploadAssets.serverUrl))
  389. .font(.system(size: 15))
  390. .frame(maxWidth: .infinity, alignment: .trailing)
  391. }
  392. } icon: {
  393. Image("folder")
  394. .renderingMode(.template)
  395. .resizable()
  396. .scaledToFit()
  397. .foregroundColor(Color(NCBrandColor.shared.brand))
  398. }
  399. }
  400. .contentShape(Rectangle())
  401. .onTapGesture {
  402. isPresentedSelect = true
  403. }
  404. }
  405. }
  406. Section {
  407. HStack {
  408. Text(NSLocalizedString("_filename_", comment: ""))
  409. if isMaintainOriginalFilename {
  410. Text(getOriginalFilenameForPreview().deletingPathExtension)
  411. .font(.system(size: 15))
  412. .frame(maxWidth: .infinity, alignment: .trailing)
  413. .foregroundColor(Color.gray)
  414. } else {
  415. TextField(NSLocalizedString("_enter_filename_", comment: ""), text: $fileName)
  416. .font(.system(size: 15))
  417. .modifier(TextFieldClearButton(text: $fileName))
  418. .multilineTextAlignment(.trailing)
  419. }
  420. }
  421. if !isMaintainOriginalFilename {
  422. Text(setFileNameMaskForPreview(fileName: fileName))
  423. .font(.system(size: 11))
  424. .foregroundColor(Color.gray)
  425. }
  426. }
  427. .complexModifier { view in
  428. view.listRowSeparator(.hidden)
  429. }
  430. Button(NSLocalizedString("_save_", comment: "")) {
  431. if uploadAssets.isUseAutoUploadFolder, uploadAssets.isUseAutoUploadSubFolder {
  432. uploadAssets.showHUD = true
  433. }
  434. uploadAssets.uploadInProgress.toggle()
  435. save { metadatasNOConflict, metadatasUploadInConflict in
  436. if metadatasUploadInConflict.isEmpty {
  437. uploadAssets.dismissCreateFormUploadConflict(metadatas: metadatasNOConflict)
  438. } else {
  439. uploadAssets.metadatasNOConflict = metadatasNOConflict
  440. uploadAssets.metadatasUploadInConflict = metadatasUploadInConflict
  441. isPresentedUploadConflict = true
  442. }
  443. }
  444. }
  445. .frame(maxWidth: .infinity)
  446. .buttonStyle(ButtonRounded(disabled: uploadAssets.uploadInProgress))
  447. .listRowBackground(Color(UIColor.systemGroupedBackground))
  448. .disabled(uploadAssets.uploadInProgress)
  449. }
  450. .navigationTitle(NSLocalizedString("_upload_photos_videos_", comment: ""))
  451. .navigationBarTitleDisplayMode(.inline)
  452. HUDView(showHUD: $uploadAssets.showHUD, textLabel: NSLocalizedString("_wait_", comment: ""), image: "doc.badge.arrow.up")
  453. .offset(y: uploadAssets.showHUD ? 5 : -200)
  454. .animation(.easeOut)
  455. }
  456. }
  457. .navigationViewStyle(StackNavigationViewStyle())
  458. .sheet(isPresented: $isPresentedSelect) {
  459. SelectView(serverUrl: $uploadAssets.serverUrl)
  460. }
  461. .sheet(isPresented: $isPresentedUploadConflict) {
  462. UploadConflictView(delegate: uploadAssets, serverUrl: uploadAssets.serverUrl, metadatasUploadInConflict: uploadAssets.metadatasUploadInConflict, metadatasNOConflict: uploadAssets.metadatasNOConflict)
  463. }
  464. .fullScreenCover(isPresented: $isPresentedQuickLook) {
  465. ViewerQuickLook(url: URL(fileURLWithPath: fileNamePath), index: $index, isPresentedQuickLook: $isPresentedQuickLook, uploadAssets: uploadAssets)
  466. .ignoresSafeArea()
  467. }
  468. .onReceive(uploadAssets.$dismiss) { newValue in
  469. if newValue {
  470. presentationMode.wrappedValue.dismiss()
  471. }
  472. }
  473. .onTapGesture {
  474. UIApplication.shared.windows.filter { $0.isKeyWindow }.first?.endEditing(true)
  475. }
  476. .onDisappear {
  477. uploadAssets.dismiss = true
  478. }
  479. }
  480. struct ImageAsset: View {
  481. @ObservedObject var uploadAssets: NCUploadAssets
  482. @State var index: Int
  483. var body: some View {
  484. ZStack(alignment: .bottomTrailing) {
  485. if index < uploadAssets.previewStore.count {
  486. let item = uploadAssets.previewStore[index]
  487. Image(uiImage: item.image)
  488. .resizable()
  489. .aspectRatio(contentMode: .fill)
  490. .frame(width: 80, height: 80, alignment: .center)
  491. .cornerRadius(10)
  492. if item.assetType == .livePhoto && item.data == nil {
  493. Image(systemName: "livephoto")
  494. .resizable()
  495. .scaledToFit()
  496. .frame(width: 15, height: 15)
  497. .foregroundColor(.white)
  498. .padding(.horizontal, 5)
  499. .padding(.vertical, 5)
  500. } else if item.assetType == .video {
  501. Image(systemName: "video.fill")
  502. .resizable()
  503. .scaledToFit()
  504. .frame(width: 15, height: 15)
  505. .foregroundColor(.white)
  506. .padding(.horizontal, 5)
  507. .padding(.vertical, 5)
  508. }
  509. }
  510. }
  511. }
  512. }
  513. }
  514. // MARK: - Preview
  515. struct UploadAssetsView_Previews: PreviewProvider {
  516. static var previews: some View {
  517. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  518. let uploadAssets = NCUploadAssets(assets: [], serverUrl: "/", userBaseUrl: appDelegate)
  519. UploadAssetsView(uploadAssets: uploadAssets)
  520. }
  521. }
  522. }