NCActionCenter.swift 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  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. class NCActionCenter: NSObject, UIDocumentInteractionControllerDelegate, NCSelectDelegate {
  30. public static let shared: NCActionCenter = {
  31. let instance = NCActionCenter()
  32. NotificationCenter.default.addObserver(instance, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadedFile), object: nil)
  33. NotificationCenter.default.addObserver(instance, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  34. return instance
  35. }()
  36. var viewerQuickLook: NCViewerQuickLook?
  37. var documentController: UIDocumentInteractionController?
  38. // MARK: - Download
  39. @objc func downloadedFile(_ notification: NSNotification) {
  40. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  41. guard let userInfo = notification.userInfo as NSDictionary?,
  42. let ocId = userInfo["ocId"] as? String,
  43. let selector = userInfo["selector"] as? String,
  44. let error = userInfo["error"] as? NKError,
  45. let account = userInfo["account"] as? String,
  46. account == appDelegate.account
  47. else { return }
  48. guard error == .success else {
  49. // File do not exists on server, remove in local
  50. if error.errorCode == NCGlobal.shared.errorResourceNotFound || error.errorCode == NCGlobal.shared.errorBadServerResponse {
  51. do {
  52. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(ocId))
  53. } catch { }
  54. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocId))
  55. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", ocId))
  56. } else {
  57. NCContentPresenter.shared.messageNotification("_download_file_", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  58. }
  59. return
  60. }
  61. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) else { return }
  62. switch selector {
  63. case NCGlobal.shared.selectorLoadFileQuickLook:
  64. let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  65. let fileNameTemp = NSTemporaryDirectory() + metadata.fileNameView
  66. guard let image = UIImage(contentsOfFile: fileNamePath) else { return }
  67. if let data = image.jpegData(compressionQuality: 1) {
  68. do {
  69. try data.write(to: URL(fileURLWithPath: fileNameTemp))
  70. } catch {
  71. return
  72. }
  73. }
  74. let viewerQuickLook = NCViewerQuickLook(with: URL(fileURLWithPath: fileNameTemp), isEditingEnabled: true, metadata: metadata)
  75. let navigationController = UINavigationController(rootViewController: viewerQuickLook)
  76. navigationController.modalPresentationStyle = .fullScreen
  77. appDelegate.window?.rootViewController?.present(navigationController, animated: true)
  78. case NCGlobal.shared.selectorLoadFileView:
  79. guard UIApplication.shared.applicationState == .active else { break }
  80. if metadata.contentType.contains("opendocument") && !NCUtility.shared.isRichDocument(metadata) {
  81. self.openDocumentController(metadata: metadata)
  82. } else if metadata.classFile == NKCommon.typeClassFile.compress.rawValue || metadata.classFile == NKCommon.typeClassFile.unknow.rawValue {
  83. self.openDocumentController(metadata: metadata)
  84. } else {
  85. if let viewController = appDelegate.activeViewController {
  86. let imageIcon = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  87. NCViewer.shared.view(viewController: viewController, metadata: metadata, metadatas: [metadata], imageIcon: imageIcon)
  88. }
  89. }
  90. case NCGlobal.shared.selectorOpenIn:
  91. if UIApplication.shared.applicationState == .active {
  92. self.openDocumentController(metadata: metadata)
  93. }
  94. case NCGlobal.shared.selectorLoadOffline:
  95. NCManageDatabase.shared.setLocalFile(ocId: metadata.ocId, offline: true)
  96. case NCGlobal.shared.selectorPrint:
  97. // waiting close menu
  98. // https://github.com/nextcloud/ios/issues/2278
  99. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  100. self.printDocument(metadata: metadata)
  101. }
  102. case NCGlobal.shared.selectorSaveAlbum:
  103. saveAlbum(metadata: metadata)
  104. case NCGlobal.shared.selectorSaveAlbumLivePhotoIMG, NCGlobal.shared.selectorSaveAlbumLivePhotoMOV:
  105. var metadata = metadata
  106. var metadataMOV = metadata
  107. guard let metadataTMP = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) else { break }
  108. if selector == NCGlobal.shared.selectorSaveAlbumLivePhotoIMG {
  109. metadataMOV = metadataTMP
  110. }
  111. if selector == NCGlobal.shared.selectorSaveAlbumLivePhotoMOV {
  112. metadata = metadataTMP
  113. }
  114. if CCUtility.fileProviderStorageExists(metadata) && CCUtility.fileProviderStorageExists(metadataMOV) {
  115. saveLivePhotoToDisk(metadata: metadata, metadataMov: metadataMOV)
  116. }
  117. case NCGlobal.shared.selectorSaveAsScan:
  118. saveAsScan(metadata: metadata)
  119. case NCGlobal.shared.selectorOpenDetail:
  120. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterOpenMediaDetail, userInfo: ["ocId": metadata.ocId])
  121. default:
  122. let applicationHandle = NCApplicationHandle()
  123. applicationHandle.downloadedFile(selector: selector, metadata: metadata)
  124. }
  125. }
  126. func setMetadataAvalableOffline(_ metadata: tableMetadata, isOffline: Bool) {
  127. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  128. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  129. if isOffline {
  130. if metadata.directory {
  131. NCManageDatabase.shared.setDirectory(serverUrl: serverUrl, offline: false, account: appDelegate.account)
  132. } else {
  133. NCManageDatabase.shared.setLocalFile(ocId: metadata.ocId, offline: false)
  134. }
  135. } else if metadata.directory {
  136. NCManageDatabase.shared.setDirectory(serverUrl: serverUrl, offline: true, account: appDelegate.account)
  137. NCOperationQueue.shared.synchronizationMetadata(metadata, selector: NCGlobal.shared.selectorDownloadAllFile)
  138. } else {
  139. NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorLoadOffline) { _, _ in }
  140. if let metadataLivePhoto = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  141. NCNetworking.shared.download(metadata: metadataLivePhoto, selector: NCGlobal.shared.selectorLoadOffline) { _, _ in }
  142. }
  143. }
  144. }
  145. // MARK: - Upload
  146. @objc func uploadedFile(_ notification: NSNotification) {
  147. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  148. guard let userInfo = notification.userInfo as NSDictionary?,
  149. let error = userInfo["error"] as? NKError,
  150. let account = userInfo["account"] as? String,
  151. account == appDelegate.account
  152. else { return }
  153. if error != .success, error.errorCode != NSURLErrorCancelled, error.errorCode != NCGlobal.shared.errorRequestExplicityCancelled {
  154. NCContentPresenter.shared.messageNotification("_upload_file_", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  155. }
  156. }
  157. // MARK: -
  158. func openShare(viewController: UIViewController, metadata: tableMetadata, indexPage: NCGlobal.NCSharePagingIndex) {
  159. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  160. NCActivityIndicator.shared.start(backgroundView: viewController.view)
  161. NCNetworking.shared.readFile(serverUrlFileName: serverUrlFileName, queue: .main) { _, metadata, error in
  162. NCActivityIndicator.shared.stop()
  163. if let metadata = metadata, error == .success {
  164. let shareNavigationController = UIStoryboard(name: "NCShare", bundle: nil).instantiateInitialViewController() as? UINavigationController
  165. let shareViewController = shareNavigationController?.topViewController as? NCSharePaging
  166. shareViewController?.metadata = metadata
  167. shareViewController?.indexPage = indexPage
  168. shareNavigationController?.modalPresentationStyle = .formSheet
  169. if let shareNavigationController = shareNavigationController {
  170. viewController.present(shareNavigationController, animated: true, completion: nil)
  171. }
  172. }
  173. }
  174. }
  175. // MARK: - Open in ...
  176. func openDocumentController(metadata: tableMetadata) {
  177. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate,
  178. let mainTabBar = appDelegate.mainTabBar else { return }
  179. let fileURL = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  180. documentController = UIDocumentInteractionController(url: fileURL)
  181. documentController?.presentOptionsMenu(from: mainTabBar.menuRect, in: mainTabBar, animated: true)
  182. }
  183. func openActivityViewController(selectedMetadata: [tableMetadata]) {
  184. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  185. let metadatas = selectedMetadata.filter({ !$0.directory })
  186. var items: [URL] = []
  187. var downloadMetadata: [(tableMetadata, URL)] = []
  188. for metadata in metadatas {
  189. let fileURL = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  190. if CCUtility.fileProviderStorageExists(metadata) {
  191. items.append(fileURL)
  192. } else {
  193. downloadMetadata.append((metadata, fileURL))
  194. }
  195. }
  196. let processor = ParallelWorker(n: 5, titleKey: "_downloading_", totalTasks: downloadMetadata.count, hudView: appDelegate.window?.rootViewController?.view)
  197. for (metadata, url) in downloadMetadata {
  198. processor.execute { completion in
  199. NCNetworking.shared.download(metadata: metadata, selector: "", completion: { _, _ in
  200. if CCUtility.fileProviderStorageExists(metadata) { items.append(url) }
  201. completion()
  202. })
  203. }
  204. }
  205. processor.completeWork {
  206. guard !items.isEmpty, let mainTabBar = appDelegate.mainTabBar else { return }
  207. let activityViewController = UIActivityViewController(activityItems: items, applicationActivities: nil)
  208. activityViewController.popoverPresentationController?.permittedArrowDirections = .any
  209. activityViewController.popoverPresentationController?.sourceView = mainTabBar
  210. activityViewController.popoverPresentationController?.sourceRect = mainTabBar.menuRect
  211. appDelegate.window?.rootViewController?.present(activityViewController, animated: true)
  212. }
  213. }
  214. // MARK: - Save as scan
  215. func saveAsScan(metadata: tableMetadata) {
  216. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  217. let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  218. let fileNameDestination = CCUtility.createFileName("scan.png", fileDate: Date(), fileType: PHAssetMediaType.image, keyFileName: NCGlobal.shared.keyFileNameMask, keyFileNameType: NCGlobal.shared.keyFileNameType, keyFileNameOriginal: NCGlobal.shared.keyFileNameOriginal, forcedNewFileName: true)!
  219. let fileNamePathDestination = CCUtility.getDirectoryScan() + "/" + fileNameDestination
  220. NCUtilityFileSystem.shared.copyFile(atPath: fileNamePath, toPath: fileNamePathDestination)
  221. let storyboard = UIStoryboard(name: "NCScan", bundle: nil)
  222. let navigationController = storyboard.instantiateInitialViewController()!
  223. navigationController.modalPresentationStyle = UIModalPresentationStyle.pageSheet
  224. appDelegate.window?.rootViewController?.present(navigationController, animated: true, completion: nil)
  225. }
  226. // MARK: - Print
  227. func printDocument(metadata: tableMetadata) {
  228. let fileNameURL = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!)
  229. let printController = UIPrintInteractionController.shared
  230. let printInfo = UIPrintInfo(dictionary: nil)
  231. printInfo.jobName = fileNameURL.lastPathComponent
  232. printInfo.outputType = metadata.classFile == NKCommon.typeClassFile.image.rawValue ? .photo : .general
  233. printController.printInfo = printInfo
  234. printController.showsNumberOfCopies = true
  235. guard !UIPrintInteractionController.canPrint(fileNameURL) else {
  236. printController.printingItem = fileNameURL
  237. printController.present(animated: true)
  238. return
  239. }
  240. // can't print without data
  241. guard let data = try? Data(contentsOf: fileNameURL) else { return }
  242. if let svg = SVGKImage(data: data) {
  243. printController.printingItem = svg.uiImage
  244. printController.present(animated: true)
  245. return
  246. }
  247. guard let text = String(data: data, encoding: .utf8) else { return }
  248. let formatter = UISimpleTextPrintFormatter(text: text)
  249. formatter.perPageContentInsets.top = 72
  250. formatter.perPageContentInsets.bottom = 72
  251. formatter.perPageContentInsets.left = 72
  252. formatter.perPageContentInsets.right = 72
  253. printController.printFormatter = formatter
  254. printController.present(animated: true)
  255. }
  256. // MARK: - Save photo
  257. func saveAlbum(metadata: tableMetadata) {
  258. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  259. let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  260. NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: appDelegate.mainTabBar?.window?.rootViewController) { hasPermission in
  261. guard hasPermission else {
  262. let error = NKError(errorCode: NCGlobal.shared.errorFileNotSaved, errorDescription: "_access_photo_not_enabled_msg_")
  263. return NCContentPresenter.shared.messageNotification("_access_photo_not_enabled_", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error)
  264. }
  265. let errorSave = NKError(errorCode: NCGlobal.shared.errorFileNotSaved, errorDescription: "_file_not_saved_cameraroll_")
  266. do {
  267. if metadata.classFile == NKCommon.typeClassFile.image.rawValue {
  268. let data = try Data(contentsOf: URL(fileURLWithPath: fileNamePath))
  269. PHPhotoLibrary.shared().performChanges({
  270. let assetRequest = PHAssetCreationRequest.forAsset()
  271. assetRequest.addResource(with: .photo, data: data, options: nil)
  272. }) { success, _ in
  273. if !success {
  274. NCContentPresenter.shared.messageNotification("_save_selected_files_", error: errorSave, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error)
  275. }
  276. }
  277. } else if metadata.classFile == NKCommon.typeClassFile.video.rawValue {
  278. PHPhotoLibrary.shared().performChanges({
  279. PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: fileNamePath))
  280. }) { success, _ in
  281. if !success {
  282. NCContentPresenter.shared.messageNotification("_save_selected_files_", error: errorSave, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error)
  283. }
  284. }
  285. } else {
  286. NCContentPresenter.shared.messageNotification("_save_selected_files_", error: errorSave, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error)
  287. return
  288. }
  289. } catch {
  290. NCContentPresenter.shared.messageNotification("_save_selected_files_", error: errorSave, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error)
  291. }
  292. }
  293. }
  294. func saveLivePhoto(metadata: tableMetadata, metadataMOV: tableMetadata) {
  295. if !CCUtility.fileProviderStorageExists(metadata) {
  296. NCOperationQueue.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorSaveAlbumLivePhotoIMG)
  297. }
  298. if !CCUtility.fileProviderStorageExists(metadataMOV) {
  299. NCOperationQueue.shared.download(metadata: metadataMOV, selector: NCGlobal.shared.selectorSaveAlbumLivePhotoMOV)
  300. }
  301. if CCUtility.fileProviderStorageExists(metadata) && CCUtility.fileProviderStorageExists(metadataMOV) {
  302. saveLivePhotoToDisk(metadata: metadata, metadataMov: metadataMOV)
  303. }
  304. }
  305. func saveLivePhotoToDisk(metadata: tableMetadata, metadataMov: tableMetadata) {
  306. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  307. let fileNameImage = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!)
  308. let fileNameMov = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadataMov.ocId, fileNameView: metadataMov.fileNameView)!)
  309. let hud = JGProgressHUD()
  310. hud.indicatorView = JGProgressHUDRingIndicatorView()
  311. if let indicatorView = hud.indicatorView as? JGProgressHUDRingIndicatorView {
  312. indicatorView.ringWidth = 1.5
  313. }
  314. hud.textLabel.text = NSLocalizedString("_saving_", comment: "")
  315. hud.show(in: (appDelegate.window?.rootViewController?.view)!)
  316. NCLivePhoto.generate(from: fileNameImage, videoURL: fileNameMov, progress: { progress in
  317. hud.progress = Float(progress)
  318. }, completion: { _, resources in
  319. if resources != nil {
  320. NCLivePhoto.saveToLibrary(resources!) { result in
  321. DispatchQueue.main.async {
  322. if !result {
  323. hud.indicatorView = JGProgressHUDErrorIndicatorView()
  324. hud.textLabel.text = NSLocalizedString("_livephoto_save_error_", comment: "")
  325. } else {
  326. hud.indicatorView = JGProgressHUDSuccessIndicatorView()
  327. hud.textLabel.text = NSLocalizedString("_success_", comment: "")
  328. }
  329. hud.dismiss(afterDelay: 1)
  330. }
  331. }
  332. } else {
  333. hud.indicatorView = JGProgressHUDErrorIndicatorView()
  334. hud.textLabel.text = NSLocalizedString("_livephoto_save_error_", comment: "")
  335. hud.dismiss(afterDelay: 1)
  336. }
  337. })
  338. }
  339. // MARK: - Copy & Paste
  340. func copyPasteboard(pasteboardOcIds: [String], hudView: UIView) {
  341. var items = [[String: Any]]()
  342. let hud = JGProgressHUD()
  343. hud.textLabel.text = NSLocalizedString("_wait_", comment: "")
  344. hud.show(in: hudView)
  345. // getting file data can take some time and block the main queue
  346. DispatchQueue.global(qos: .userInitiated).async {
  347. var downloadMetadatas: [tableMetadata] = []
  348. for ocid in pasteboardOcIds {
  349. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocid) else { continue }
  350. if let pasteboardItem = metadata.toPasteBoardItem() {
  351. items.append(pasteboardItem)
  352. } else {
  353. downloadMetadatas.append(metadata)
  354. }
  355. }
  356. DispatchQueue.main.async(execute: hud.dismiss)
  357. // do 5 downloads in parallel to optimize efficiency
  358. let parallelizer = ParallelWorker(n: 5, titleKey: "_downloading_", totalTasks: downloadMetadatas.count, hudView: hudView)
  359. for metadata in downloadMetadatas {
  360. parallelizer.execute { completion in
  361. NCNetworking.shared.download(metadata: metadata, selector: "") { _, _ in completion() }
  362. }
  363. }
  364. parallelizer.completeWork {
  365. items.append(contentsOf: downloadMetadatas.compactMap({ $0.toPasteBoardItem() }))
  366. UIPasteboard.general.setItems(items, options: [:])
  367. }
  368. }
  369. }
  370. func pastePasteboard(serverUrl: String) {
  371. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  372. let parallelizer = ParallelWorker(n: 5, titleKey: "_uploading_", totalTasks: nil, hudView: appDelegate.window?.rootViewController?.view)
  373. func uploadPastePasteboard(fileName: String, serverUrlFileName: String, fileNameLocalPath: String, serverUrl: String, completion: @escaping () -> Void) {
  374. NextcloudKit.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath) { request in
  375. NCNetworking.shared.uploadRequest[fileNameLocalPath] = request
  376. } progressHandler: { _ in
  377. } completionHandler: { account, ocId, etag, _, _, _, afError, error in
  378. NCNetworking.shared.uploadRequest.removeValue(forKey: fileNameLocalPath)
  379. if error == .success && etag != nil && ocId != nil {
  380. let toPath = CCUtility.getDirectoryProviderStorageOcId(ocId!, fileNameView: fileName)!
  381. NCUtilityFileSystem.shared.moveFile(atPath: fileNameLocalPath, toPath: toPath)
  382. NCManageDatabase.shared.addLocalFile(account: account, etag: etag!, ocId: ocId!, fileName: fileName)
  383. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced, userInfo: ["serverUrl": serverUrl])
  384. } else if afError?.isExplicitlyCancelledError ?? false {
  385. print("cancel")
  386. } else {
  387. NCContentPresenter.shared.showError(error: error)
  388. }
  389. completion()
  390. }
  391. }
  392. for (index, items) in UIPasteboard.general.items.enumerated() {
  393. for item in items {
  394. let results = NKCommon.shared.getFileProperties(inUTI: item.key as CFString)
  395. guard !results.ext.isEmpty,
  396. let data = UIPasteboard.general.data(forPasteboardType: item.key, inItemSet: IndexSet([index]))?.first
  397. else { continue }
  398. let fileName = results.name + "_" + CCUtility.getIncrementalNumber() + "." + results.ext
  399. let serverUrlFileName = serverUrl + "/" + fileName
  400. let ocIdUpload = UUID().uuidString
  401. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(ocIdUpload, fileNameView: fileName)!
  402. do { try data.write(to: URL(fileURLWithPath: fileNameLocalPath)) } catch { continue }
  403. parallelizer.execute { completion in
  404. uploadPastePasteboard(fileName: fileName, serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, serverUrl: serverUrl, completion: completion)
  405. }
  406. }
  407. }
  408. parallelizer.completeWork()
  409. }
  410. // MARK: -
  411. func openFileViewInFolder(serverUrl: String, fileNameBlink: String?, fileNameOpen: String?) {
  412. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  413. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  414. var topNavigationController: UINavigationController?
  415. var pushServerUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId)
  416. guard var mostViewController = appDelegate.window?.rootViewController?.topMostViewController() else { return }
  417. if mostViewController.isModal {
  418. mostViewController.dismiss(animated: false)
  419. if let viewController = appDelegate.window?.rootViewController?.topMostViewController() {
  420. mostViewController = viewController
  421. }
  422. }
  423. mostViewController.navigationController?.popToRootViewController(animated: false)
  424. if let tabBarController = appDelegate.window?.rootViewController as? UITabBarController {
  425. tabBarController.selectedIndex = 0
  426. if let navigationController = tabBarController.viewControllers?.first as? UINavigationController {
  427. navigationController.popToRootViewController(animated: false)
  428. topNavigationController = navigationController
  429. }
  430. }
  431. if pushServerUrl == serverUrl {
  432. let viewController = topNavigationController?.topViewController as? NCFiles
  433. viewController?.blinkCell(fileName: fileNameBlink)
  434. viewController?.openFile(fileName: fileNameOpen)
  435. return
  436. }
  437. guard let topNavigationController = topNavigationController else { return }
  438. let diffDirectory = serverUrl.replacingOccurrences(of: pushServerUrl, with: "")
  439. var subDirs = diffDirectory.split(separator: "/")
  440. while pushServerUrl != serverUrl, !subDirs.isEmpty {
  441. guard let dir = subDirs.first, let viewController = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles else { return }
  442. pushServerUrl = pushServerUrl + "/" + dir
  443. viewController.serverUrl = pushServerUrl
  444. viewController.isRoot = false
  445. viewController.titleCurrentFolder = String(dir)
  446. if pushServerUrl == serverUrl {
  447. viewController.fileNameBlink = fileNameBlink
  448. viewController.fileNameOpen = fileNameOpen
  449. }
  450. appDelegate.listFilesVC[serverUrl] = viewController
  451. viewController.navigationItem.backButtonTitle = viewController.titleCurrentFolder
  452. topNavigationController.pushViewController(viewController, animated: false)
  453. subDirs.remove(at: 0)
  454. }
  455. }
  456. }
  457. // MARK: - NCSelect + Delegate
  458. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool) {
  459. if serverUrl != nil && !items.isEmpty {
  460. if copy {
  461. for case let metadata as tableMetadata in items {
  462. NCOperationQueue.shared.copyMove(metadata: metadata, serverUrl: serverUrl!, overwrite: overwrite, move: false)
  463. }
  464. } else if move {
  465. for case let metadata as tableMetadata in items {
  466. NCOperationQueue.shared.copyMove(metadata: metadata, serverUrl: serverUrl!, overwrite: overwrite, move: true)
  467. }
  468. }
  469. }
  470. }
  471. func openSelectView(items: [tableMetadata]) {
  472. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  473. let navigationController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateInitialViewController() as? UINavigationController
  474. let topViewController = navigationController?.topViewController as? NCSelect
  475. var listViewController = [NCSelect]()
  476. var copyItems: [tableMetadata] = []
  477. for item in items {
  478. copyItems.append(item)
  479. }
  480. let homeUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId)
  481. var serverUrl = copyItems[0].serverUrl
  482. // Setup view controllers such that the current view is of the same directory the items to be copied are in
  483. while true {
  484. // If not in the topmost directory, create a new view controller and set correct title.
  485. // If in the topmost directory, use the default view controller as the base.
  486. var viewController: NCSelect?
  487. if serverUrl != homeUrl {
  488. viewController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateViewController(withIdentifier: "NCSelect.storyboard") as? NCSelect
  489. if viewController == nil {
  490. return
  491. }
  492. viewController!.titleCurrentFolder = (serverUrl as NSString).lastPathComponent
  493. } else {
  494. viewController = topViewController
  495. }
  496. guard let vc = viewController else { return }
  497. vc.delegate = self
  498. vc.typeOfCommandView = .copyMove
  499. vc.items = copyItems
  500. vc.serverUrl = serverUrl
  501. vc.navigationItem.backButtonTitle = vc.titleCurrentFolder
  502. listViewController.insert(vc, at: 0)
  503. if serverUrl != homeUrl {
  504. if let path = NCUtilityFileSystem.shared.deleteLastPath(serverUrlPath: serverUrl) {
  505. serverUrl = path
  506. }
  507. } else {
  508. break
  509. }
  510. }
  511. navigationController?.setViewControllers(listViewController, animated: false)
  512. navigationController?.modalPresentationStyle = .formSheet
  513. if let navigationController = navigationController {
  514. appDelegate.window?.rootViewController?.present(navigationController, animated: true, completion: nil)
  515. }
  516. }
  517. }
  518. fileprivate extension tableMetadata {
  519. func toPasteBoardItem() -> [String: Any]? {
  520. // Get Data
  521. let fileUrl = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView))
  522. guard CCUtility.fileProviderStorageExists(self),
  523. let data = try? Data(contentsOf: fileUrl),
  524. let unmanagedFileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension as CFString, nil)
  525. else { return nil }
  526. // Pasteboard item
  527. let fileUTI = unmanagedFileUTI.takeRetainedValue() as String
  528. return [fileUTI: data]
  529. }
  530. }