NCActionCenter.swift 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. //
  2. // NCActionCenter.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 19/04/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 Queuer
  26. import JGProgressHUD
  27. import SVGKit
  28. import Photos
  29. import Alamofire
  30. class NCActionCenter: NSObject, UIDocumentInteractionControllerDelegate, NCSelectDelegate {
  31. public static let shared: NCActionCenter = {
  32. let instance = NCActionCenter()
  33. NotificationCenter.default.addObserver(instance, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadedFile), object: nil)
  34. NotificationCenter.default.addObserver(instance, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  35. return instance
  36. }()
  37. var viewerQuickLook: NCViewerQuickLook?
  38. var documentController: UIDocumentInteractionController?
  39. let utilityFileSystem = NCUtilityFileSystem()
  40. let utility = NCUtility()
  41. let appDelegate = UIApplication.shared.delegate as? AppDelegate
  42. // MARK: - Download
  43. @objc func downloadedFile(_ notification: NSNotification) {
  44. guard let userInfo = notification.userInfo as NSDictionary?,
  45. let ocId = userInfo["ocId"] as? String,
  46. let selector = userInfo["selector"] as? String,
  47. let error = userInfo["error"] as? NKError,
  48. let account = userInfo["account"] as? String,
  49. account == appDelegate?.account
  50. else { return }
  51. guard error == .success else {
  52. // File do not exists on server, remove in local
  53. if error.errorCode == NCGlobal.shared.errorResourceNotFound || error.errorCode == NCGlobal.shared.errorBadServerResponse {
  54. do {
  55. try FileManager.default.removeItem(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(ocId))
  56. } catch { }
  57. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocId))
  58. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", ocId))
  59. } else {
  60. NCContentPresenter().messageNotification("_download_file_", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  61. }
  62. return
  63. }
  64. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) else { return }
  65. DispatchQueue.main.async {
  66. // Select UIWindowScene active in serverUrl
  67. var controller: NCMainTabBarController?
  68. let windowScenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }
  69. if windowScenes.count == 1 {
  70. controller = UIApplication.shared.firstWindow?.rootViewController as? NCMainTabBarController
  71. } else if let sceneIdentifier = metadata.sceneIdentifier,
  72. let tabBarController = SceneManager.shared.getController(sceneIdentifier: sceneIdentifier) {
  73. controller = tabBarController
  74. } else {
  75. for windowScene in windowScenes {
  76. if let rootViewController = windowScene.keyWindow?.rootViewController as? NCMainTabBarController,
  77. rootViewController.currentServerUrl() == metadata.serverUrl {
  78. controller = rootViewController
  79. break
  80. }
  81. }
  82. }
  83. guard let controller else { return }
  84. switch selector {
  85. case NCGlobal.shared.selectorLoadFileQuickLook:
  86. let fileNamePath = self.utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  87. let fileNameTemp = NSTemporaryDirectory() + metadata.fileNameView
  88. let viewerQuickLook = NCViewerQuickLook(with: URL(fileURLWithPath: fileNameTemp), isEditingEnabled: true, metadata: metadata)
  89. if let image = UIImage(contentsOfFile: fileNamePath) {
  90. if let data = image.jpegData(compressionQuality: 1) {
  91. do {
  92. try data.write(to: URL(fileURLWithPath: fileNameTemp))
  93. } catch {
  94. return
  95. }
  96. }
  97. let navigationController = UINavigationController(rootViewController: viewerQuickLook)
  98. navigationController.modalPresentationStyle = .fullScreen
  99. controller.present(navigationController, animated: true)
  100. } else {
  101. self.utilityFileSystem.copyFile(atPath: fileNamePath, toPath: fileNameTemp)
  102. controller.present(viewerQuickLook, animated: true)
  103. }
  104. case NCGlobal.shared.selectorLoadFileView:
  105. guard UIApplication.shared.applicationState == .active else { return }
  106. if metadata.contentType.contains("opendocument") && !self.utility.isTypeFileRichDocument(metadata) {
  107. self.openDocumentController(metadata: metadata, controller: controller)
  108. } else if metadata.classFile == NKCommon.TypeClassFile.compress.rawValue || metadata.classFile == NKCommon.TypeClassFile.unknow.rawValue {
  109. self.openDocumentController(metadata: metadata, controller: controller)
  110. } else {
  111. if let viewController = controller.currentViewController() {
  112. let imageIcon = UIImage(contentsOfFile: self.utilityFileSystem.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  113. NCViewer().view(viewController: viewController, metadata: metadata, metadatas: [metadata], imageIcon: imageIcon)
  114. }
  115. }
  116. case NCGlobal.shared.selectorOpenIn:
  117. if UIApplication.shared.applicationState == .active {
  118. self.openDocumentController(metadata: metadata, controller: controller)
  119. }
  120. case NCGlobal.shared.selectorSaveAlbum:
  121. self.saveAlbum(metadata: metadata, controller: controller)
  122. case NCGlobal.shared.selectorSaveAsScan:
  123. self.saveAsScan(metadata: metadata, controller: controller)
  124. case NCGlobal.shared.selectorOpenDetail:
  125. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterOpenMediaDetail, userInfo: ["ocId": metadata.ocId])
  126. default:
  127. let applicationHandle = NCApplicationHandle()
  128. applicationHandle.downloadedFile(selector: selector, metadata: metadata)
  129. }
  130. }
  131. }
  132. func setMetadataAvalableOffline(_ metadata: tableMetadata, isOffline: Bool) {
  133. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  134. if isOffline {
  135. if metadata.directory {
  136. NCManageDatabase.shared.setDirectory(serverUrl: serverUrl, offline: false, metadata: metadata)
  137. if let metadatas = NCManageDatabase.shared.getResultsMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND sessionSelector == %@ AND status == %d", metadata.account, serverUrl, NCGlobal.shared.selectorSynchronizationOffline, NCGlobal.shared.metadataStatusWaitDownload)) {
  138. NCManageDatabase.shared.clearMetadataSession(metadatas: metadatas)
  139. }
  140. } else {
  141. NCManageDatabase.shared.setOffLocalFile(ocId: metadata.ocId)
  142. }
  143. } else if metadata.directory {
  144. NCManageDatabase.shared.setDirectory(serverUrl: serverUrl, offline: true, metadata: metadata)
  145. NCNetworking.shared.synchronization(account: metadata.account, serverUrl: serverUrl, add: true)
  146. } else {
  147. var metadatasSynchronizationOffline: [tableMetadata] = []
  148. metadatasSynchronizationOffline.append(metadata)
  149. if let metadata = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  150. metadatasSynchronizationOffline.append(metadata)
  151. }
  152. NCManageDatabase.shared.addLocalFile(metadata: metadata, offline: true)
  153. NCManageDatabase.shared.setMetadatasSessionInWaitDownload(metadatas: metadatasSynchronizationOffline,
  154. session: NCNetworking.shared.sessionDownloadBackground,
  155. selector: NCGlobal.shared.selectorSynchronizationOffline)
  156. }
  157. }
  158. func viewerFile(account: String, fileId: String, viewController: UIViewController) {
  159. guard let hudView = viewController.tabBarController?.view else { return }
  160. var downloadRequest: DownloadRequest?
  161. if let metadata = NCManageDatabase.shared.getMetadataFromFileId(fileId) {
  162. do {
  163. let attr = try FileManager.default.attributesOfItem(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  164. let fileSize = attr[FileAttributeKey.size] as? UInt64 ?? 0
  165. if fileSize > 0 {
  166. NCViewer().view(viewController: viewController, metadata: metadata, metadatas: [metadata], imageIcon: nil)
  167. return
  168. }
  169. } catch {
  170. print("Error: \(error)")
  171. }
  172. }
  173. let hud = JGProgressHUD()
  174. hud.indicatorView = JGProgressHUDRingIndicatorView()
  175. if let indicatorView = hud.indicatorView as? JGProgressHUDRingIndicatorView {
  176. indicatorView.ringWidth = 1.5
  177. indicatorView.ringColor = NCBrandColor.shared.brandElement
  178. }
  179. hud.tapOnHUDViewBlock = { _ in
  180. if let request = downloadRequest {
  181. request.cancel()
  182. }
  183. }
  184. hud.show(in: hudView)
  185. NextcloudKit.shared.getFileFromFileId(fileId: fileId, account: account) { account, file, _, error in
  186. hud.dismiss()
  187. if error != .success {
  188. NCContentPresenter().showError(error: error)
  189. } else if let file = file {
  190. let isDirectoryE2EE = self.utilityFileSystem.isDirectoryE2EE(file: file)
  191. let metadata = NCManageDatabase.shared.convertFileToMetadata(file, isDirectoryE2EE: isDirectoryE2EE)
  192. NCManageDatabase.shared.addMetadata(metadata)
  193. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  194. let fileNameLocalPath = self.utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  195. if metadata.isAudioOrVideo {
  196. NCViewer().view(viewController: viewController, metadata: metadata, metadatas: [metadata], imageIcon: nil)
  197. } else {
  198. hud.show(in: hudView)
  199. NextcloudKit.shared.download(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, account: account, requestHandler: { request in
  200. downloadRequest = request
  201. }, taskHandler: { _ in
  202. }, progressHandler: { progress in
  203. hud.progress = Float(progress.fractionCompleted)
  204. }) { accountDownload, _, _, _, _, _, error in
  205. hud.dismiss()
  206. if account == accountDownload && error == .success {
  207. NCManageDatabase.shared.addLocalFile(metadata: metadata)
  208. NCViewer().view(viewController: viewController, metadata: metadata, metadatas: [metadata], imageIcon: nil)
  209. }
  210. }
  211. }
  212. } else {
  213. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_file_not_found_")
  214. NCContentPresenter().showError(error: error)
  215. }
  216. }
  217. }
  218. // MARK: - Upload
  219. @objc func uploadedFile(_ notification: NSNotification) {
  220. guard let userInfo = notification.userInfo as NSDictionary?,
  221. let error = userInfo["error"] as? NKError,
  222. let account = userInfo["account"] as? String,
  223. account == self.appDelegate?.account
  224. else { return }
  225. if error != .success, error.errorCode != NSURLErrorCancelled, error.errorCode != NCGlobal.shared.errorRequestExplicityCancelled {
  226. NCContentPresenter().messageNotification("_upload_file_", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  227. }
  228. }
  229. // MARK: -
  230. func openShare(viewController: UIViewController, metadata: tableMetadata, page: NCBrandOptions.NCInfoPagingTab) {
  231. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  232. var page = page
  233. NCActivityIndicator.shared.start(backgroundView: viewController.view)
  234. NCNetworking.shared.readFile(serverUrlFileName: serverUrlFileName, account: metadata.account, queue: .main) { _, metadata, error in
  235. NCActivityIndicator.shared.stop()
  236. if let metadata = metadata, error == .success {
  237. var pages: [NCBrandOptions.NCInfoPagingTab] = []
  238. let shareNavigationController = UIStoryboard(name: "NCShare", bundle: nil).instantiateInitialViewController() as? UINavigationController
  239. let shareViewController = shareNavigationController?.topViewController as? NCSharePaging
  240. for value in NCBrandOptions.NCInfoPagingTab.allCases {
  241. pages.append(value)
  242. }
  243. if NCGlobal.shared.capabilityActivity.isEmpty, let idx = pages.firstIndex(of: .activity) {
  244. pages.remove(at: idx)
  245. }
  246. if !metadata.isSharable(), let idx = pages.firstIndex(of: .sharing) {
  247. pages.remove(at: idx)
  248. }
  249. (pages, page) = NCApplicationHandle().filterPages(pages: pages, page: page, metadata: metadata)
  250. shareViewController?.pages = pages
  251. shareViewController?.metadata = metadata
  252. if pages.contains(page) {
  253. shareViewController?.page = page
  254. } else if let page = pages.first {
  255. shareViewController?.page = page
  256. } else {
  257. return
  258. }
  259. shareNavigationController?.modalPresentationStyle = .formSheet
  260. if let shareNavigationController = shareNavigationController {
  261. viewController.present(shareNavigationController, animated: true, completion: nil)
  262. }
  263. }
  264. }
  265. }
  266. // MARK: - Open in ...
  267. func openDocumentController(metadata: tableMetadata, controller: NCMainTabBarController?) {
  268. guard let mainTabBarController = controller,
  269. let mainTabBar = mainTabBarController.tabBar as? NCMainTabBar else { return }
  270. let fileURL = URL(fileURLWithPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  271. documentController = UIDocumentInteractionController(url: fileURL)
  272. documentController?.presentOptionsMenu(from: mainTabBar.menuRect, in: mainTabBar, animated: true)
  273. }
  274. func openActivityViewController(selectedMetadata: [tableMetadata], controller: NCMainTabBarController?) {
  275. guard let controller,
  276. let mainTabBar = controller.tabBar as? NCMainTabBar else { return }
  277. let metadatas = selectedMetadata.filter({ !$0.directory })
  278. var items: [URL] = []
  279. var downloadMetadata: [(tableMetadata, URL)] = []
  280. for metadata in metadatas {
  281. let fileURL = URL(fileURLWithPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  282. if utilityFileSystem.fileProviderStorageExists(metadata) {
  283. items.append(fileURL)
  284. } else {
  285. downloadMetadata.append((metadata, fileURL))
  286. }
  287. }
  288. let processor = ParallelWorker(n: 5, titleKey: "_downloading_", totalTasks: downloadMetadata.count, hudView: controller.view)
  289. for (metadata, url) in downloadMetadata {
  290. processor.execute { completion in
  291. guard let metadata = NCManageDatabase.shared.setMetadatasSessionInWaitDownload(metadatas: [metadata],
  292. session: NextcloudKit.shared.nkCommonInstance.sessionIdentifierDownload,
  293. selector: "",
  294. sceneIdentifier: controller.sceneIdentifier) else { return completion() }
  295. NCNetworking.shared.download(metadata: metadata, withNotificationProgressTask: false) {
  296. } progressHandler: { progress in
  297. processor.hud?.progress = Float(progress.fractionCompleted)
  298. } completion: { _, _ in
  299. if self.utilityFileSystem.fileProviderStorageExists(metadata) { items.append(url) }
  300. completion()
  301. }
  302. }
  303. }
  304. processor.completeWork {
  305. guard !items.isEmpty else { return }
  306. let activityViewController = UIActivityViewController(activityItems: items, applicationActivities: nil)
  307. activityViewController.popoverPresentationController?.permittedArrowDirections = .any
  308. activityViewController.popoverPresentationController?.sourceView = mainTabBar
  309. activityViewController.popoverPresentationController?.sourceRect = mainTabBar.menuRect
  310. controller.present(activityViewController, animated: true)
  311. }
  312. }
  313. // MARK: - Save as scan
  314. func saveAsScan(metadata: tableMetadata, controller: NCMainTabBarController?) {
  315. let fileNamePath = utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  316. let fileNameDestination = utilityFileSystem.createFileName("scan.png", fileDate: Date(), fileType: PHAssetMediaType.image, notUseMask: true)
  317. let fileNamePathDestination = utilityFileSystem.directoryScan + "/" + fileNameDestination
  318. utilityFileSystem.copyFile(atPath: fileNamePath, toPath: fileNamePathDestination)
  319. if let navigationController = UIStoryboard(name: "NCScan", bundle: nil).instantiateInitialViewController() {
  320. navigationController.modalPresentationStyle = UIModalPresentationStyle.pageSheet
  321. let viewController = navigationController.presentedViewController as? NCScan
  322. viewController?.serverUrl = controller?.currentServerUrl()
  323. controller?.present(navigationController, animated: true, completion: nil)
  324. }
  325. }
  326. // MARK: - Save photo
  327. func saveAlbum(metadata: tableMetadata, controller: NCMainTabBarController?) {
  328. let fileNamePath = utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  329. NCAskAuthorization().askAuthorizationPhotoLibrary(viewController: controller) { hasPermission in
  330. guard hasPermission else {
  331. let error = NKError(errorCode: NCGlobal.shared.errorFileNotSaved, errorDescription: "_access_photo_not_enabled_msg_")
  332. return NCContentPresenter().messageNotification("_access_photo_not_enabled_", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error)
  333. }
  334. let errorSave = NKError(errorCode: NCGlobal.shared.errorFileNotSaved, errorDescription: "_file_not_saved_cameraroll_")
  335. do {
  336. if metadata.isImage {
  337. let data = try Data(contentsOf: URL(fileURLWithPath: fileNamePath))
  338. PHPhotoLibrary.shared().performChanges({
  339. let assetRequest = PHAssetCreationRequest.forAsset()
  340. assetRequest.addResource(with: .photo, data: data, options: nil)
  341. }) { success, _ in
  342. if !success {
  343. NCContentPresenter().messageNotification("_save_selected_files_", error: errorSave, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error)
  344. }
  345. }
  346. } else if metadata.isVideo {
  347. PHPhotoLibrary.shared().performChanges({
  348. PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: fileNamePath))
  349. }) { success, _ in
  350. if !success {
  351. NCContentPresenter().messageNotification("_save_selected_files_", error: errorSave, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error)
  352. }
  353. }
  354. } else {
  355. NCContentPresenter().messageNotification("_save_selected_files_", error: errorSave, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error)
  356. return
  357. }
  358. } catch {
  359. NCContentPresenter().messageNotification("_save_selected_files_", error: errorSave, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error)
  360. }
  361. }
  362. }
  363. // MARK: - Copy & Paste
  364. func pastePasteboard(serverUrl: String, account: String, hudView: UIView?) {
  365. var fractionCompleted: Float = 0
  366. let processor = ParallelWorker(n: 5, titleKey: "_uploading_", totalTasks: nil, hudView: hudView)
  367. func uploadPastePasteboard(fileName: String, serverUrlFileName: String, fileNameLocalPath: String, serverUrl: String, completion: @escaping () -> Void) {
  368. NextcloudKit.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, account: account) { request in
  369. NCNetworking.shared.uploadRequest[fileNameLocalPath] = request
  370. } progressHandler: { progress in
  371. if Float(progress.fractionCompleted) > fractionCompleted || fractionCompleted == 0 {
  372. processor.hud?.progress = Float(progress.fractionCompleted)
  373. fractionCompleted = Float(progress.fractionCompleted)
  374. }
  375. } completionHandler: { account, ocId, etag, _, _, _, afError, error in
  376. NCNetworking.shared.uploadRequest.removeValue(forKey: fileNameLocalPath)
  377. if error == .success && etag != nil && ocId != nil {
  378. let toPath = self.utilityFileSystem.getDirectoryProviderStorageOcId(ocId!, fileNameView: fileName)
  379. self.utilityFileSystem.moveFile(atPath: fileNameLocalPath, toPath: toPath)
  380. NCManageDatabase.shared.addLocalFile(account: account, etag: etag!, ocId: ocId!, fileName: fileName)
  381. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSourceNetwork)
  382. } else if afError?.isExplicitlyCancelledError ?? false {
  383. print("cancel")
  384. } else {
  385. NCContentPresenter().showError(error: error)
  386. }
  387. fractionCompleted = 0
  388. completion()
  389. }
  390. }
  391. for (index, items) in UIPasteboard.general.items.enumerated() {
  392. for item in items {
  393. let results = NextcloudKit.shared.nkCommonInstance.getFileProperties(inUTI: item.key as CFString)
  394. guard !results.ext.isEmpty,
  395. let data = UIPasteboard.general.data(forPasteboardType: item.key, inItemSet: IndexSet([index]))?.first
  396. else { continue }
  397. let fileName = results.name + "_" + NCKeychain().incrementalNumber + "." + results.ext
  398. let serverUrlFileName = serverUrl + "/" + fileName
  399. let ocIdUpload = UUID().uuidString
  400. let fileNameLocalPath = utilityFileSystem.getDirectoryProviderStorageOcId(ocIdUpload, fileNameView: fileName)
  401. do { try data.write(to: URL(fileURLWithPath: fileNameLocalPath)) } catch { continue }
  402. processor.execute { completion in
  403. uploadPastePasteboard(fileName: fileName, serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, serverUrl: serverUrl, completion: completion)
  404. }
  405. }
  406. }
  407. processor.completeWork()
  408. }
  409. // MARK: -
  410. func openFileViewInFolder(serverUrl: String, fileNameBlink: String?, fileNameOpen: String?, sceneIdentifier: String) {
  411. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate,
  412. let controller = SceneManager.shared.getController(sceneIdentifier: sceneIdentifier),
  413. let navigationController = controller.viewControllers?.first as? UINavigationController
  414. else { return }
  415. var serverUrlPush = self.utilityFileSystem.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId)
  416. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  417. navigationController.popToRootViewController(animated: false)
  418. controller.selectedIndex = 0
  419. if serverUrlPush == serverUrl,
  420. let viewController = navigationController.topViewController as? NCFiles {
  421. viewController.blinkCell(fileName: fileNameBlink)
  422. viewController.openFile(fileName: fileNameOpen)
  423. return
  424. }
  425. let diffDirectory = serverUrl.replacingOccurrences(of: serverUrlPush, with: "")
  426. var subDirs = diffDirectory.split(separator: "/")
  427. while serverUrlPush != serverUrl, !subDirs.isEmpty {
  428. guard let dir = subDirs.first else { return }
  429. serverUrlPush = serverUrlPush + "/" + dir
  430. if let viewController = controller.navigationCollectionViewCommon.first(where: { $0.navigationController == navigationController && $0.serverUrl == serverUrlPush})?.viewController as? NCFiles, viewController.isViewLoaded {
  431. viewController.fileNameBlink = fileNameBlink
  432. viewController.fileNameOpen = fileNameOpen
  433. navigationController.pushViewController(viewController, animated: false)
  434. } else {
  435. if let viewController: NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  436. viewController.isRoot = false
  437. viewController.serverUrl = serverUrlPush
  438. viewController.titleCurrentFolder = String(dir)
  439. viewController.navigationItem.backButtonTitle = viewController.titleCurrentFolder
  440. controller.navigationCollectionViewCommon.append(NavigationCollectionViewCommon(serverUrl: serverUrlPush, navigationController: navigationController, viewController: viewController))
  441. if serverUrlPush == serverUrl {
  442. viewController.fileNameBlink = fileNameBlink
  443. viewController.fileNameOpen = fileNameOpen
  444. }
  445. navigationController.pushViewController(viewController, animated: false)
  446. }
  447. }
  448. subDirs.remove(at: 0)
  449. }
  450. }
  451. }
  452. // MARK: - NCSelect + Delegate
  453. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool) {
  454. if let serverUrl, !items.isEmpty {
  455. if copy {
  456. Task {
  457. var error = NKError()
  458. var ocId: [String] = []
  459. for case let metadata as tableMetadata in items where error == .success {
  460. error = await NCNetworking.shared.copyMetadata(metadata, serverUrlTo: serverUrl, overwrite: overwrite)
  461. if error == .success {
  462. ocId.append(metadata.ocId)
  463. }
  464. }
  465. if error != .success {
  466. NCContentPresenter().showError(error: error)
  467. }
  468. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterCopyFile, userInfo: ["ocId": ocId, "error": error])
  469. }
  470. } else {
  471. Task {
  472. var error = NKError()
  473. var ocId: [String] = []
  474. for case let metadata as tableMetadata in items where error == .success {
  475. error = await NCNetworking.shared.moveMetadata(metadata, serverUrlTo: serverUrl, overwrite: overwrite)
  476. if error == .success {
  477. ocId.append(metadata.ocId)
  478. }
  479. }
  480. if error != .success {
  481. NCContentPresenter().showError(error: error)
  482. }
  483. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterMoveFile, userInfo: ["ocId": ocId, "error": error])
  484. }
  485. }
  486. }
  487. }
  488. func openSelectView(items: [tableMetadata], controller: NCMainTabBarController?) {
  489. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  490. let navigationController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateInitialViewController() as? UINavigationController
  491. let topViewController = navigationController?.topViewController as? NCSelect
  492. var listViewController = [NCSelect]()
  493. var copyItems: [tableMetadata] = []
  494. for item in items {
  495. if let fileNameError = FileNameValidator.shared.checkFileName(item.fileNameView) {
  496. controller?.present(UIAlertController.warning(message: "\(fileNameError.errorDescription) \(NSLocalizedString("_please_rename_file_", comment: ""))"), animated: true)
  497. return
  498. }
  499. copyItems.append(item)
  500. }
  501. let homeUrl = utilityFileSystem.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId)
  502. var serverUrl = copyItems[0].serverUrl
  503. // Setup view controllers such that the current view is of the same directory the items to be copied are in
  504. while true {
  505. // If not in the topmost directory, create a new view controller and set correct title.
  506. // If in the topmost directory, use the default view controller as the base.
  507. var viewController: NCSelect?
  508. if serverUrl != homeUrl {
  509. viewController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateViewController(withIdentifier: "NCSelect.storyboard") as? NCSelect
  510. if viewController == nil {
  511. return
  512. }
  513. viewController!.titleCurrentFolder = (serverUrl as NSString).lastPathComponent
  514. } else {
  515. viewController = topViewController
  516. }
  517. guard let vc = viewController else { return }
  518. vc.delegate = self
  519. vc.typeOfCommandView = .copyMove
  520. vc.items = copyItems
  521. vc.serverUrl = serverUrl
  522. vc.navigationItem.backButtonTitle = vc.titleCurrentFolder
  523. listViewController.insert(vc, at: 0)
  524. if serverUrl != homeUrl {
  525. if let path = utilityFileSystem.deleteLastPath(serverUrlPath: serverUrl) {
  526. serverUrl = path
  527. }
  528. } else {
  529. break
  530. }
  531. }
  532. navigationController?.setViewControllers(listViewController, animated: false)
  533. navigationController?.modalPresentationStyle = .formSheet
  534. if let navigationController = navigationController {
  535. controller?.present(navigationController, animated: true, completion: nil)
  536. }
  537. }
  538. }