NCCreateFormUploadConflict.swift 21 KB

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