NCUploadAssets.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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. init(assets: [TLPHAsset], serverUrl: String, userBaseUrl: NCUserBaseUrl) {
  52. self.assets = assets
  53. self.serverUrl = serverUrl
  54. self.userBaseUrl = userBaseUrl
  55. }
  56. func loadImages() {
  57. DispatchQueue.global().async {
  58. for asset in self.assets {
  59. guard asset.type == .photo, let image = asset.fullResolutionImage?.resizeImage(size: CGSize(width: 200, height: 200), isAspectRation: true), let localIdentifier = asset.phAsset?.localIdentifier else { continue }
  60. self.previewStore.append(PreviewStore(id: localIdentifier, image: image, asset: asset, hasChanges: false))
  61. }
  62. }
  63. }
  64. func startTimer(navigationItem: UINavigationItem) {
  65. self.timer = Timer.scheduledTimer(withTimeInterval: 0.3, repeats: true, block: { _ in
  66. print("XX")
  67. let numItemsRight = navigationItem.rightBarButtonItems?.count ?? 0
  68. if let buttonCrop = navigationItem.leftBarButtonItems?.first {
  69. if numItemsRight > 1 && buttonCrop.isEnabled {
  70. buttonCrop.isEnabled = false
  71. if let buttonDone = navigationItem.rightBarButtonItems?.last {
  72. buttonDone.isEnabled = false
  73. }
  74. }
  75. if numItemsRight == 1 && !buttonCrop.isEnabled {
  76. buttonCrop.isEnabled = true
  77. if let buttonDone = navigationItem.rightBarButtonItems?.first {
  78. buttonDone.isEnabled = true
  79. }
  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. self.index = index
  221. if let image = uploadAssets.previewStore[index].asset.fullResolutionImage?.resizeImage(size: CGSize(width: size, height: size)) {
  222. if let data = image.jpegData(compressionQuality: 0.5) {
  223. do {
  224. try data.write(to: URL(fileURLWithPath: fileNamePath))
  225. isPresentedQuickLook = true
  226. } catch {
  227. }
  228. }
  229. }
  230. }
  231. var body: some View {
  232. GeometryReader { geo in
  233. NavigationView {
  234. List {
  235. if !uploadAssets.previewStore.isEmpty {
  236. Section(header: Text(NSLocalizedString("_modify_photo_", comment: "")), footer: Text(NSLocalizedString("_modify_photo_desc_", comment: ""))) {
  237. ScrollView(.horizontal) {
  238. LazyHGrid(rows: gridItems, alignment: .center, spacing: 10) {
  239. ForEach(0..<uploadAssets.previewStore.count, id: \.self) { index in
  240. VStack {
  241. Image(uiImage: uploadAssets.previewStore[index].image)
  242. .resizable()
  243. .frame(width: 100, height: 100, alignment: .center)
  244. .cornerRadius(10)
  245. .scaledToFit()
  246. .onTapGesture {
  247. presentedQuickLook(size: max(geo.size.height, geo.size.height), index: index)
  248. }.fullScreenCover(isPresented: $isPresentedQuickLook) {
  249. ViewerQuickLook(url: URL(fileURLWithPath: fileNamePath), index: $index, isPresentedQuickLook: $isPresentedQuickLook, uploadAssets: uploadAssets)
  250. .ignoresSafeArea()
  251. }
  252. }
  253. }
  254. }
  255. }
  256. }
  257. }
  258. Section(header: Text(NSLocalizedString("_mode_filename_", comment: ""))) {
  259. Toggle(NSLocalizedString("_maintain_original_filename_", comment: ""), isOn: $isMaintainOriginalFilename)
  260. .toggleStyle(SwitchToggleStyle(tint: Color(NCBrandColor.shared.brand)))
  261. if !isMaintainOriginalFilename {
  262. Toggle(NSLocalizedString("_add_filenametype_", comment: ""), isOn: $isAddFilenametype)
  263. .toggleStyle(SwitchToggleStyle(tint: Color(NCBrandColor.shared.brand)))
  264. }
  265. }
  266. Section {
  267. HStack {
  268. Label {
  269. if NCUtilityFileSystem.shared.getHomeServer(urlBase: uploadAssets.userBaseUrl.urlBase, userId: uploadAssets.userBaseUrl.userId) == uploadAssets.serverUrl {
  270. Text("/")
  271. .frame(maxWidth: .infinity, alignment: .trailing)
  272. } else {
  273. Text((uploadAssets.serverUrl as NSString).lastPathComponent)
  274. .frame(maxWidth: .infinity, alignment: .trailing)
  275. }
  276. } icon: {
  277. Image("folder")
  278. .renderingMode(.template)
  279. .resizable()
  280. .scaledToFit()
  281. .foregroundColor(Color(NCBrandColor.shared.brand))
  282. }
  283. }
  284. .contentShape(Rectangle())
  285. .onTapGesture {
  286. isPresentedSelect = true
  287. }
  288. HStack {
  289. Text(NSLocalizedString("_filename_", comment: ""))
  290. if isMaintainOriginalFilename {
  291. Text(getOriginalFilename())
  292. .frame(maxWidth: .infinity, alignment: .trailing)
  293. } else {
  294. TextField(NSLocalizedString("_enter_filename_", comment: ""), text: $fileName)
  295. .modifier(TextFieldClearButton(text: $fileName))
  296. .multilineTextAlignment(.trailing)
  297. }
  298. }
  299. if !isMaintainOriginalFilename {
  300. Text(setFileNameMask(fileName: fileName))
  301. .font(.system(size: 12))
  302. .foregroundColor(Color.gray)
  303. }
  304. }
  305. .complexModifier { view in
  306. if #available(iOS 15, *) {
  307. view.listRowSeparator(.hidden)
  308. }
  309. }
  310. Button(NSLocalizedString("_save_", comment: "")) {
  311. save { metadatasNOConflict, metadatasUploadInConflict in
  312. if metadatasUploadInConflict.isEmpty {
  313. uploadAssets.dismiss = true
  314. } else {
  315. uploadAssets.metadatasNOConflict = metadatasNOConflict
  316. uploadAssets.metadatasUploadInConflict = metadatasUploadInConflict
  317. isPresentedUploadConflict = true
  318. }
  319. }
  320. }
  321. .frame(maxWidth: .infinity)
  322. .buttonStyle(ButtonRounded(disabled: false))
  323. .listRowBackground(Color(UIColor.systemGroupedBackground))
  324. }
  325. .navigationTitle(NSLocalizedString("_upload_photos_videos_", comment: ""))
  326. .navigationBarTitleDisplayMode(.inline)
  327. }
  328. .sheet(isPresented: $isPresentedSelect) {
  329. SelectView(serverUrl: $uploadAssets.serverUrl)
  330. }
  331. .sheet(isPresented: $isPresentedUploadConflict) {
  332. UploadConflictView(delegate: uploadAssets, serverUrl: uploadAssets.serverUrl, metadatasUploadInConflict: uploadAssets.metadatasUploadInConflict, metadatasNOConflict: uploadAssets.metadatasNOConflict)
  333. }
  334. .onReceive(uploadAssets.$dismiss) { newValue in
  335. if newValue {
  336. presentationMode.wrappedValue.dismiss()
  337. }
  338. }
  339. }
  340. }
  341. }
  342. // MARK: - Preview
  343. struct UploadAssetsView_Previews: PreviewProvider {
  344. static var previews: some View {
  345. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  346. let uploadAssets = NCUploadAssets(assets: [], serverUrl: "/", userBaseUrl: appDelegate)
  347. UploadAssetsView(uploadAssets: uploadAssets)
  348. }
  349. }
  350. }