NCActionCenter.swift 34 KB

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