NCCreateFormUploadConflict.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. //
  2. // NCCreateFormUploadConflict.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 29/03/2020.
  6. // Copyright © 2020 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 UIKit
  24. import SwiftUI
  25. import NextcloudKit
  26. import Photos
  27. protocol NCCreateFormUploadConflictDelegate: AnyObject {
  28. func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?)
  29. }
  30. class NCCreateFormUploadConflict: UIViewController {
  31. @IBOutlet weak var labelTitle: UILabel!
  32. @IBOutlet weak var labelSubTitle: UILabel!
  33. @IBOutlet weak var viewSwitch: UIView!
  34. @IBOutlet weak var switchNewFiles: UISwitch!
  35. @IBOutlet weak var switchAlreadyExistingFiles: UISwitch!
  36. @IBOutlet weak var labelNewFiles: UILabel!
  37. @IBOutlet weak var labelAlreadyExistingFiles: UILabel!
  38. @IBOutlet weak var tableView: UITableView!
  39. @IBOutlet weak var viewButton: UIView!
  40. @IBOutlet weak var buttonCancel: UIButton!
  41. @IBOutlet weak var buttonContinue: UIButton!
  42. var metadatasNOConflict: [tableMetadata]
  43. var metadatasUploadInConflict: [tableMetadata]
  44. var serverUrl: String?
  45. var delegate: NCCreateFormUploadConflictDelegate?
  46. var alwaysNewFileNameNumber: Bool = false
  47. var textLabelDetailNewFile: String?
  48. var metadatasConflictNewFiles: [String] = []
  49. var metadatasConflictAlreadyExistingFiles: [String] = []
  50. let fileNamesPath = ThreadSafeDictionary<String, String>()
  51. var blurView: UIVisualEffectView!
  52. let utility = NCUtility()
  53. let utilityFileSystem = NCUtilityFileSystem()
  54. // MARK: - View Life Cycle
  55. required init?(coder aDecoder: NSCoder) {
  56. self.metadatasNOConflict = []
  57. self.metadatasUploadInConflict = []
  58. super.init(coder: aDecoder)
  59. }
  60. override func viewDidLoad() {
  61. super.viewDidLoad()
  62. tableView.dataSource = self
  63. tableView.delegate = self
  64. tableView.allowsSelection = false
  65. tableView.tableFooterView = UIView()
  66. view.backgroundColor = .systemGroupedBackground
  67. tableView.backgroundColor = .systemGroupedBackground
  68. viewSwitch.backgroundColor = .systemGroupedBackground
  69. viewButton.backgroundColor = .systemGroupedBackground
  70. tableView.register(UINib(nibName: "NCCreateFormUploadConflictCell", bundle: nil), forCellReuseIdentifier: "Cell")
  71. if metadatasUploadInConflict.count == 1 {
  72. labelTitle.text = String(metadatasUploadInConflict.count) + " " + NSLocalizedString("_file_conflict_num_", comment: "")
  73. labelSubTitle.text = NSLocalizedString("_file_conflict_desc_", comment: "")
  74. labelNewFiles.text = NSLocalizedString("_file_conflict_new_", comment: "")
  75. labelAlreadyExistingFiles.text = NSLocalizedString("_file_conflict_exists_", comment: "")
  76. } else {
  77. labelTitle.text = String(metadatasUploadInConflict.count) + " " + NSLocalizedString("_file_conflicts_num_", comment: "")
  78. labelSubTitle.text = NSLocalizedString("_file_conflict_desc_", comment: "")
  79. labelNewFiles.text = NSLocalizedString("_file_conflict_new_", comment: "")
  80. labelAlreadyExistingFiles.text = NSLocalizedString("_file_conflict_exists_", comment: "")
  81. }
  82. switchNewFiles.onTintColor = NCBrandColor.shared.brand
  83. switchNewFiles.isOn = false
  84. switchAlreadyExistingFiles.onTintColor = NCBrandColor.shared.brand
  85. switchAlreadyExistingFiles.isOn = false
  86. buttonCancel.layer.cornerRadius = 20
  87. buttonCancel.layer.masksToBounds = true
  88. buttonCancel.layer.borderWidth = 0.5
  89. buttonCancel.layer.borderColor = UIColor.darkGray.cgColor
  90. buttonCancel.backgroundColor = .systemGray5
  91. buttonCancel.setTitle(NSLocalizedString("_cancel_", comment: ""), for: .normal)
  92. buttonCancel.setTitleColor(.label, for: .normal)
  93. buttonContinue.layer.cornerRadius = 20
  94. buttonContinue.layer.masksToBounds = true
  95. buttonContinue.backgroundColor = NCBrandColor.shared.brand
  96. buttonContinue.setTitle(NSLocalizedString("_continue_", comment: ""), for: .normal)
  97. buttonContinue.isEnabled = false
  98. buttonContinue.setTitleColor(NCBrandColor.shared.brandText, for: .normal)
  99. let blurEffect = UIBlurEffect(style: .light)
  100. blurView = UIVisualEffectView(effect: blurEffect)
  101. blurView.frame = view.bounds
  102. blurView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  103. view.addSubview(blurView)
  104. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  105. self.conflictDialog(fileCount: self.metadatasUploadInConflict.count)
  106. }
  107. }
  108. // MARK: - ConflictDialog
  109. func conflictDialog(fileCount: Int) {
  110. var tile = ""
  111. var titleReplace = ""
  112. var titleKeep = ""
  113. if fileCount == 1 {
  114. tile = NSLocalizedString("_single_file_conflict_title_", comment: "")
  115. titleReplace = NSLocalizedString("_replace_action_title_", comment: "")
  116. titleKeep = NSLocalizedString("_keep_both_action_title_", comment: "")
  117. } else {
  118. tile = String.localizedStringWithFormat(NSLocalizedString("_multi_file_conflict_title_", comment: ""), String(fileCount))
  119. titleReplace = NSLocalizedString("_replace_all_action_title_", comment: "")
  120. titleKeep = NSLocalizedString("_keep_both_for_all_action_title_", comment: "")
  121. }
  122. let conflictAlert = UIAlertController(title: tile, message: "", preferredStyle: .alert)
  123. // KEEP BOTH
  124. conflictAlert.addAction(UIAlertAction(title: titleKeep, style: .default, handler: { action in
  125. for metadata in self.metadatasUploadInConflict {
  126. self.metadatasConflictNewFiles.append(metadata.ocId)
  127. self.metadatasConflictAlreadyExistingFiles.append(metadata.ocId)
  128. }
  129. self.buttonContinueTouch(action)
  130. }))
  131. // REPLACE
  132. conflictAlert.addAction(UIAlertAction(title: titleReplace, style: .default, handler: { action in
  133. for metadata in self.metadatasUploadInConflict {
  134. self.metadatasNOConflict.append(metadata)
  135. }
  136. self.buttonContinueTouch(action)
  137. }))
  138. // MORE
  139. conflictAlert.addAction(UIAlertAction(title: NSLocalizedString("_more_action_title_", comment: ""), style: .default, handler: { _ in
  140. self.blurView.removeFromSuperview()
  141. }))
  142. // CANCEL
  143. conflictAlert.addAction(UIAlertAction(title: NSLocalizedString("_cancel_keep_existing_action_title_", comment: ""), style: .cancel, handler: { _ in
  144. self.dismiss(animated: true) {
  145. self.delegate?.dismissCreateFormUploadConflict(metadatas: nil)
  146. }
  147. }))
  148. self.present(conflictAlert, animated: true, completion: nil)
  149. }
  150. // MARK: - Action
  151. @IBAction func valueChangedSwitchNewFiles(_ sender: Any) {
  152. metadatasConflictNewFiles.removeAll()
  153. if switchNewFiles.isOn {
  154. for metadata in metadatasUploadInConflict {
  155. metadatasConflictNewFiles.append(metadata.ocId)
  156. }
  157. }
  158. verifySwith()
  159. }
  160. @IBAction func valueChangedSwitchAlreadyExistingFiles(_ sender: Any) {
  161. metadatasConflictAlreadyExistingFiles.removeAll()
  162. if switchAlreadyExistingFiles.isOn {
  163. for metadata in metadatasUploadInConflict {
  164. metadatasConflictAlreadyExistingFiles.append(metadata.ocId)
  165. }
  166. }
  167. verifySwith()
  168. }
  169. func verifySwith() {
  170. if alwaysNewFileNameNumber && switchNewFiles.isOn {
  171. metadatasConflictNewFiles.removeAll()
  172. metadatasConflictAlreadyExistingFiles.removeAll()
  173. for metadata in metadatasUploadInConflict {
  174. metadatasConflictNewFiles.append(metadata.ocId)
  175. }
  176. for metadata in metadatasUploadInConflict {
  177. metadatasConflictAlreadyExistingFiles.append(metadata.ocId)
  178. }
  179. switchAlreadyExistingFiles.isOn = true
  180. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_file_not_rewite_doc_")
  181. NCContentPresenter().showInfo(error: error)
  182. }
  183. tableView.reloadData()
  184. canContinue()
  185. }
  186. @IBAction func buttonCancelTouch(_ sender: Any) {
  187. dismiss(animated: true) {
  188. self.delegate?.dismissCreateFormUploadConflict(metadatas: nil)
  189. }
  190. }
  191. @IBAction func buttonContinueTouch(_ sender: Any) {
  192. for metadata in metadatasUploadInConflict {
  193. // keep both
  194. if metadatasConflictNewFiles.contains(metadata.ocId) && metadatasConflictAlreadyExistingFiles.contains(metadata.ocId) {
  195. var fileName = metadata.fileNameView
  196. let fileNameExtension = (fileName as NSString).pathExtension.lowercased()
  197. let fileNameNoExtension = (fileName as NSString).deletingPathExtension
  198. if fileNameExtension == "heic" && NCKeychain().formatCompatibility {
  199. fileName = fileNameNoExtension + ".jpg"
  200. }
  201. let oldPath = utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  202. let newFileName = utilityFileSystem.createFileName(fileName, serverUrl: metadata.serverUrl, account: metadata.account)
  203. metadata.ocId = UUID().uuidString
  204. metadata.fileName = newFileName
  205. metadata.fileNameView = newFileName
  206. // This is not an asset - [file]
  207. if metadata.assetLocalIdentifier.isEmpty || metadata.isExtractFile {
  208. let newPath = utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: newFileName)
  209. utilityFileSystem.moveFile(atPath: oldPath, toPath: newPath)
  210. }
  211. metadatasNOConflict.append(metadata)
  212. // overwrite
  213. } else if metadatasConflictNewFiles.contains(metadata.ocId) {
  214. metadatasNOConflict.append(metadata)
  215. } else {
  216. // used UIAlert (replace all)
  217. }
  218. }
  219. dismiss(animated: true) {
  220. self.delegate?.dismissCreateFormUploadConflict(metadatas: self.metadatasNOConflict)
  221. }
  222. }
  223. }
  224. // MARK: - UITableViewDelegate
  225. extension NCCreateFormUploadConflict: UITableViewDelegate {
  226. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  227. if metadatasUploadInConflict.count == 1 {
  228. return 250
  229. } else {
  230. return 280
  231. }
  232. }
  233. }
  234. // MARK: - UITableViewDataSource
  235. extension NCCreateFormUploadConflict: UITableViewDataSource {
  236. func numberOfSections(in tableView: UITableView) -> Int {
  237. return 1
  238. }
  239. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  240. return metadatasUploadInConflict.count
  241. }
  242. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  243. if let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? NCCreateFormUploadConflictCell {
  244. cell.backgroundColor = tableView.backgroundColor
  245. cell.switchNewFile.onTintColor = NCBrandColor.shared.brand
  246. cell.switchAlreadyExistingFile.onTintColor = NCBrandColor.shared.brand
  247. let metadataNewFile = tableMetadata.init(value: metadatasUploadInConflict[indexPath.row])
  248. cell.ocId = metadataNewFile.ocId
  249. cell.delegate = self
  250. cell.labelFileName.text = metadataNewFile.fileNameView
  251. cell.labelDetailAlreadyExistingFile.text = ""
  252. cell.labelDetailNewFile.text = ""
  253. // -----> Already Existing File
  254. guard let metadataAlreadyExists = NCManageDatabase.shared.getMetadataConflict(account: metadataNewFile.account, serverUrl: metadataNewFile.serverUrl, fileNameView: metadataNewFile.fileNameView) else { return UITableViewCell() }
  255. if FileManager().fileExists(atPath: utilityFileSystem.getDirectoryProviderStorageIconOcId(metadataAlreadyExists.ocId, etag: metadataAlreadyExists.etag)) {
  256. cell.imageAlreadyExistingFile.image = UIImage(contentsOfFile: utilityFileSystem.getDirectoryProviderStorageIconOcId(metadataAlreadyExists.ocId, etag: metadataAlreadyExists.etag))
  257. } else if FileManager().fileExists(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadataAlreadyExists.ocId, fileNameView: metadataAlreadyExists.fileNameView)) && metadataAlreadyExists.contentType == "application/pdf" {
  258. let url = URL(fileURLWithPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadataAlreadyExists.ocId, fileNameView: metadataAlreadyExists.fileNameView))
  259. if let image = utility.pdfThumbnail(url: url) {
  260. cell.imageAlreadyExistingFile.image = image
  261. } else {
  262. cell.imageAlreadyExistingFile.image = UIImage(named: metadataAlreadyExists.iconName)
  263. }
  264. } else {
  265. if metadataAlreadyExists.iconName.isEmpty {
  266. cell.imageAlreadyExistingFile.image = UIImage(named: "file")
  267. } else {
  268. cell.imageAlreadyExistingFile.image = UIImage(named: metadataAlreadyExists.iconName)
  269. }
  270. }
  271. cell.labelDetailAlreadyExistingFile.text = utility.dateDiff(metadataAlreadyExists.date as Date) + "\n" + utilityFileSystem.transformedSize(metadataAlreadyExists.size)
  272. if metadatasConflictAlreadyExistingFiles.contains(metadataNewFile.ocId) {
  273. cell.switchAlreadyExistingFile.isOn = true
  274. } else {
  275. cell.switchAlreadyExistingFile.isOn = false
  276. }
  277. // -----> New File
  278. if metadataNewFile.iconName.isEmpty {
  279. cell.imageNewFile.image = UIImage(named: "file")
  280. } else {
  281. cell.imageNewFile.image = UIImage(named: metadataNewFile.iconName)
  282. }
  283. let filePathNewFile = utilityFileSystem.getDirectoryProviderStorageOcId(metadataNewFile.ocId, fileNameView: metadataNewFile.fileNameView)
  284. if !metadataNewFile.assetLocalIdentifier.isEmpty {
  285. let result = PHAsset.fetchAssets(withLocalIdentifiers: [metadataNewFile.assetLocalIdentifier], options: nil)
  286. let date = result.firstObject!.modificationDate
  287. let mediaType = result.firstObject!.mediaType
  288. if let fileNamePath = self.fileNamesPath[metadataNewFile.fileNameView] {
  289. do {
  290. if mediaType == PHAssetMediaType.image {
  291. let data = try Data(contentsOf: URL(fileURLWithPath: fileNamePath))
  292. if let image = UIImage(data: data) {
  293. cell.imageNewFile.image = image
  294. }
  295. } else if mediaType == PHAssetMediaType.video {
  296. if let image = utility.imageFromVideo(url: URL(fileURLWithPath: fileNamePath), at: 0) {
  297. cell.imageNewFile.image = image
  298. }
  299. }
  300. let fileDictionary = try FileManager.default.attributesOfItem(atPath: fileNamePath)
  301. let fileSize = fileDictionary[FileAttributeKey.size] as? Int64 ?? 0
  302. cell.labelDetailNewFile.text = utility.dateDiff(date) + "\n" + utilityFileSystem.transformedSize(fileSize)
  303. } catch { print("Error: \(error)") }
  304. } else {
  305. // PREVIEW
  306. let cameraRoll = NCCameraRoll()
  307. cameraRoll.extractImageVideoFromAssetLocalIdentifier(metadata: metadataNewFile, modifyMetadataForUpload: false) { _, fileNamePath, error in
  308. if !error {
  309. self.fileNamesPath[metadataNewFile.fileNameView] = fileNamePath!
  310. do {
  311. let fileDictionary = try FileManager.default.attributesOfItem(atPath: fileNamePath!)
  312. let fileSize = fileDictionary[FileAttributeKey.size] as? Int64 ?? 0
  313. if mediaType == PHAssetMediaType.image {
  314. let data = try Data(contentsOf: URL(fileURLWithPath: fileNamePath!))
  315. if let image = UIImage(data: data) {
  316. DispatchQueue.main.async { cell.imageNewFile.image = image }
  317. }
  318. } else if mediaType == PHAssetMediaType.video {
  319. if let image = self.utility.imageFromVideo(url: URL(fileURLWithPath: fileNamePath!), at: 0) {
  320. DispatchQueue.main.async { cell.imageNewFile.image = image }
  321. }
  322. }
  323. DispatchQueue.main.async { cell.labelDetailNewFile.text = self.utility.dateDiff(date) + "\n" + self.utilityFileSystem.transformedSize(fileSize) }
  324. } catch { print("Error: \(error)") }
  325. }
  326. }
  327. }
  328. } else if FileManager().fileExists(atPath: filePathNewFile) {
  329. do {
  330. if metadataNewFile.classFile == NKCommon.TypeClassFile.image.rawValue {
  331. // preserver memory especially for very large files in Share extension
  332. if let image = UIImage.downsample(imageAt: URL(fileURLWithPath: filePathNewFile), to: cell.imageNewFile.frame.size) {
  333. cell.imageNewFile.image = image
  334. }
  335. }
  336. let fileDictionary = try FileManager.default.attributesOfItem(atPath: filePathNewFile)
  337. let fileSize = fileDictionary[FileAttributeKey.size] as? Int64 ?? 0
  338. cell.labelDetailNewFile.text = utility.dateDiff(metadataNewFile.date as Date) + "\n" + utilityFileSystem.transformedSize(fileSize)
  339. } catch { print("Error: \(error)") }
  340. }
  341. if metadatasConflictNewFiles.contains(metadataNewFile.ocId) {
  342. cell.switchNewFile.isOn = true
  343. } else {
  344. cell.switchNewFile.isOn = false
  345. }
  346. // Hide switch if only one
  347. if metadatasUploadInConflict.count == 1 {
  348. cell.switchAlreadyExistingFile.isHidden = true
  349. cell.switchNewFile.isHidden = true
  350. }
  351. // text label new file
  352. if textLabelDetailNewFile != nil {
  353. cell.labelDetailNewFile.text = textLabelDetailNewFile! + "\n"
  354. }
  355. return cell
  356. }
  357. return UITableViewCell()
  358. }
  359. }
  360. // MARK: - NCCreateFormUploadConflictCellDelegate
  361. extension NCCreateFormUploadConflict: NCCreateFormUploadConflictCellDelegate {
  362. func valueChangedSwitchNewFile(with ocId: String, isOn: Bool) {
  363. if let index = metadatasConflictNewFiles.firstIndex(of: ocId) {
  364. metadatasConflictNewFiles.remove(at: index)
  365. }
  366. if isOn {
  367. metadatasConflictNewFiles.append(ocId)
  368. }
  369. if metadatasConflictNewFiles.count == metadatasUploadInConflict.count {
  370. switchNewFiles.isOn = true
  371. } else {
  372. switchNewFiles.isOn = false
  373. }
  374. canContinue()
  375. }
  376. func valueChangedSwitchAlreadyExistingFile(with ocId: String, isOn: Bool) {
  377. if let index = metadatasConflictAlreadyExistingFiles.firstIndex(of: ocId) {
  378. metadatasConflictAlreadyExistingFiles.remove(at: index)
  379. }
  380. if isOn {
  381. metadatasConflictAlreadyExistingFiles.append(ocId)
  382. }
  383. if metadatasConflictAlreadyExistingFiles.count == metadatasUploadInConflict.count {
  384. switchAlreadyExistingFiles.isOn = true
  385. } else {
  386. switchAlreadyExistingFiles.isOn = false
  387. }
  388. canContinue()
  389. }
  390. func canContinue() {
  391. var result = true
  392. for metadata in metadatasUploadInConflict {
  393. if !metadatasConflictNewFiles.contains(metadata.ocId) && !metadatasConflictAlreadyExistingFiles.contains(metadata.ocId) {
  394. result = false
  395. }
  396. }
  397. if result {
  398. buttonContinue.isEnabled = true
  399. buttonContinue.setTitleColor(.label, for: .normal)
  400. } else {
  401. buttonContinue.isEnabled = false
  402. buttonContinue.setTitleColor(UIColor.systemGray, for: .normal)
  403. }
  404. }
  405. }
  406. // MARK: - UIViewControllerRepresentable
  407. struct UploadConflictView: UIViewControllerRepresentable {
  408. typealias UIViewControllerType = NCCreateFormUploadConflict
  409. var delegate: NCCreateFormUploadConflictDelegate
  410. var serverUrl: String
  411. var metadatasUploadInConflict: [tableMetadata]
  412. var metadatasNOConflict: [tableMetadata]
  413. func makeUIViewController(context: Context) -> UIViewControllerType {
  414. let storyboard = UIStoryboard(name: "NCCreateFormUploadConflict", bundle: nil)
  415. let viewController = storyboard.instantiateInitialViewController() as? NCCreateFormUploadConflict
  416. viewController?.delegate = delegate
  417. viewController?.textLabelDetailNewFile = NSLocalizedString("_now_", comment: "")
  418. viewController?.serverUrl = serverUrl
  419. viewController?.metadatasUploadInConflict = metadatasUploadInConflict
  420. viewController?.metadatasNOConflict = metadatasNOConflict
  421. return viewController!
  422. }
  423. func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) { }
  424. }