NCUploadAssets.swift 21 KB

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