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