NCUploadAssets.swift 25 KB

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