NCActionCenter.swift 33 KB

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