NCActionCenter.swift 31 KB

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