NCPickerViewController.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. //
  2. // NCPickerViewController.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 11/11/2018.
  6. // Copyright (c) 2018 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 TLPhotoPicker
  25. import MobileCoreServices
  26. import Photos
  27. import NextcloudKit
  28. import SwiftUI
  29. // MARK: - Photo Picker
  30. class NCPhotosPickerViewController: NSObject {
  31. var controller: NCMainTabBarController
  32. var maxSelectedAssets = 1
  33. var singleSelectedMode = false
  34. @discardableResult
  35. init(controller: NCMainTabBarController, maxSelectedAssets: Int, singleSelectedMode: Bool) {
  36. self.controller = controller
  37. super.init()
  38. self.maxSelectedAssets = maxSelectedAssets
  39. self.singleSelectedMode = singleSelectedMode
  40. self.openPhotosPickerViewController { assets in
  41. if !assets.isEmpty {
  42. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  43. let model = NCUploadAssetsModel(assets: assets, serverUrl: controller.currentServerUrl(), controller: controller)
  44. let view = NCUploadAssetsView(model: model)
  45. let viewController = UIHostingController(rootView: view)
  46. controller.present(viewController, animated: true, completion: nil)
  47. }
  48. }
  49. }
  50. }
  51. private func openPhotosPickerViewController(completition: @escaping ([TLPHAsset]) -> Void) {
  52. var configure = TLPhotosPickerConfigure()
  53. configure.cancelTitle = NSLocalizedString("_cancel_", comment: "")
  54. configure.doneTitle = NSLocalizedString("_done_", comment: "")
  55. configure.emptyMessage = NSLocalizedString("_no_albums_", comment: "")
  56. configure.tapHereToChange = NSLocalizedString("_tap_here_to_change_", comment: "")
  57. if maxSelectedAssets > 0 {
  58. configure.maxSelectedAssets = maxSelectedAssets
  59. }
  60. configure.selectedColor = NCBrandColor.shared.getElement(account: controller.account)
  61. configure.singleSelectedMode = singleSelectedMode
  62. configure.allowedAlbumCloudShared = true
  63. let viewController = customPhotoPickerViewController(withTLPHAssets: { assets in
  64. completition(assets)
  65. }, didCancel: nil)
  66. viewController.didExceedMaximumNumberOfSelection = { _ in
  67. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_limited_dimension_")
  68. NCContentPresenter().showError(error: error)
  69. }
  70. viewController.handleNoAlbumPermissions = { _ in
  71. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_denied_album_")
  72. NCContentPresenter().showError(error: error)
  73. }
  74. viewController.handleNoCameraPermissions = { _ in
  75. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_denied_camera_")
  76. NCContentPresenter().showError(error: error)
  77. }
  78. viewController.configure = configure
  79. controller.present(viewController, animated: true, completion: nil)
  80. }
  81. }
  82. class customPhotoPickerViewController: TLPhotosPickerViewController {
  83. override var preferredStatusBarStyle: UIStatusBarStyle {
  84. return .lightContent
  85. }
  86. override func makeUI() {
  87. super.makeUI()
  88. self.customNavItem.leftBarButtonItem?.tintColor = NCBrandColor.shared.iconImageColor
  89. self.customNavItem.rightBarButtonItem?.tintColor = NCBrandColor.shared.iconImageColor
  90. }
  91. }
  92. // MARK: - Document Picker
  93. class NCDocumentPickerViewController: NSObject, UIDocumentPickerDelegate {
  94. let appDelegate = (UIApplication.shared.delegate as? AppDelegate)!
  95. let utilityFileSystem = NCUtilityFileSystem()
  96. let database = NCManageDatabase.shared
  97. var isViewerMedia: Bool
  98. var viewController: UIViewController?
  99. var controller: NCMainTabBarController
  100. @discardableResult
  101. init (controller: NCMainTabBarController, isViewerMedia: Bool, allowsMultipleSelection: Bool, viewController: UIViewController? = nil) {
  102. self.controller = controller
  103. self.isViewerMedia = isViewerMedia
  104. self.viewController = viewController
  105. super.init()
  106. let documentProviderMenu = UIDocumentPickerViewController(forOpeningContentTypes: [UTType.data])
  107. documentProviderMenu.modalPresentationStyle = .formSheet
  108. documentProviderMenu.allowsMultipleSelection = allowsMultipleSelection
  109. documentProviderMenu.popoverPresentationController?.sourceView = controller.tabBar
  110. documentProviderMenu.popoverPresentationController?.sourceRect = controller.tabBar.bounds
  111. documentProviderMenu.delegate = self
  112. controller.present(documentProviderMenu, animated: true, completion: nil)
  113. }
  114. func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
  115. let session = NCSession.shared.getSession(controller: self.controller)
  116. if isViewerMedia,
  117. let urlIn = urls.first,
  118. let url = self.copySecurityScopedResource(url: urlIn, urlOut: FileManager.default.temporaryDirectory.appendingPathComponent(urlIn.lastPathComponent)),
  119. let viewController = self.viewController {
  120. let ocId = NSUUID().uuidString
  121. let fileName = url.lastPathComponent
  122. let metadata = database.createMetadata(fileName: fileName,
  123. fileNameView: fileName,
  124. ocId: ocId,
  125. serverUrl: "",
  126. url: url.path,
  127. contentType: "",
  128. session: session,
  129. sceneIdentifier: self.controller.sceneIdentifier)
  130. if metadata.classFile == NKCommon.TypeClassFile.unknow.rawValue {
  131. metadata.classFile = NKCommon.TypeClassFile.video.rawValue
  132. }
  133. if let fileNameError = FileNameValidator.shared.checkFileName(metadata.fileNameView, account: self.controller.account) {
  134. self.controller.present(UIAlertController.warning(message: "\(fileNameError.errorDescription) \(NSLocalizedString("_please_rename_file_", comment: ""))"), animated: true)
  135. } else {
  136. database.addMetadata(metadata)
  137. NCViewer().view(viewController: viewController, metadata: metadata)
  138. }
  139. } else {
  140. let serverUrl = self.controller.currentServerUrl()
  141. var metadatas = [tableMetadata]()
  142. var metadatasInConflict = [tableMetadata]()
  143. for urlIn in urls {
  144. let ocId = NSUUID().uuidString
  145. let fileName = urlIn.lastPathComponent
  146. let newFileName = FileAutoRenamer.shared.rename(fileName, account: session.account)
  147. let toPath = utilityFileSystem.getDirectoryProviderStorageOcId(ocId, fileNameView: newFileName)
  148. let urlOut = URL(fileURLWithPath: toPath)
  149. guard self.copySecurityScopedResource(url: urlIn, urlOut: urlOut) != nil else { continue }
  150. let metadataForUpload = database.createMetadata(fileName: newFileName,
  151. fileNameView: newFileName,
  152. ocId: ocId,
  153. serverUrl: serverUrl,
  154. url: "",
  155. contentType: "",
  156. session: session,
  157. sceneIdentifier: self.controller.sceneIdentifier)
  158. metadataForUpload.session = NCNetworking.shared.sessionUploadBackground
  159. metadataForUpload.sessionSelector = NCGlobal.shared.selectorUploadFile
  160. metadataForUpload.size = utilityFileSystem.getFileSize(filePath: toPath)
  161. metadataForUpload.status = NCGlobal.shared.metadataStatusWaitUpload
  162. metadataForUpload.sessionDate = Date()
  163. if database.getMetadataConflict(account: session.account, serverUrl: serverUrl, fileNameView: fileName) != nil {
  164. metadatasInConflict.append(metadataForUpload)
  165. } else {
  166. metadatas.append(metadataForUpload)
  167. }
  168. }
  169. var invalidNameIndexes: [Int] = []
  170. for (index, metadata) in metadatas.enumerated() {
  171. if let fileNameError = FileNameValidator.shared.checkFileName(metadata.fileName, account: session.account) {
  172. if metadatas.count == 1 {
  173. let alert = UIAlertController.renameFile(fileName: metadata.fileName, account: session.account) { newFileName in
  174. metadatas[index].fileName = newFileName
  175. metadatas[index].fileNameView = newFileName
  176. NCNetworkingProcess.shared.createProcessUploads(metadatas: metadatas)
  177. }
  178. self.controller.present(alert, animated: true)
  179. return
  180. } else {
  181. self.controller.present(UIAlertController.warning(message: "\(fileNameError.errorDescription) \(NSLocalizedString("_please_rename_file_", comment: ""))"), animated: true)
  182. invalidNameIndexes.append(index)
  183. }
  184. }
  185. }
  186. for index in invalidNameIndexes.reversed() {
  187. metadatas.remove(at: index)
  188. }
  189. NCNetworkingProcess.shared.createProcessUploads(metadatas: metadatas)
  190. if !metadatasInConflict.isEmpty {
  191. if let conflict = UIStoryboard(name: "NCCreateFormUploadConflict", bundle: nil).instantiateInitialViewController() as? NCCreateFormUploadConflict {
  192. conflict.account = self.controller.account
  193. conflict.delegate = appDelegate
  194. conflict.serverUrl = serverUrl
  195. conflict.metadatasUploadInConflict = metadatasInConflict
  196. self.controller.present(conflict, animated: true, completion: nil)
  197. }
  198. }
  199. }
  200. }
  201. func copySecurityScopedResource(url: URL, urlOut: URL) -> URL? {
  202. try? FileManager.default.removeItem(at: urlOut)
  203. if url.startAccessingSecurityScopedResource() {
  204. do {
  205. try FileManager.default.copyItem(at: url, to: urlOut)
  206. url.stopAccessingSecurityScopedResource()
  207. return urlOut
  208. } catch {
  209. }
  210. }
  211. return nil
  212. }
  213. }