NCActionCenter.swift 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. //
  2. // NCActionCenter.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 19/04/2020.
  6. // Copyright © 2020 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import UIKit
  24. import NextcloudKit
  25. import Queuer
  26. import JGProgressHUD
  27. import SVGKit
  28. import Photos
  29. import Alamofire
  30. class NCActionCenter: NSObject, UIDocumentInteractionControllerDelegate, NCSelectDelegate {
  31. public static let shared: NCActionCenter = {
  32. let instance = NCActionCenter()
  33. NotificationCenter.default.addObserver(instance, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadedFile), object: nil)
  34. NotificationCenter.default.addObserver(instance, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  35. return instance
  36. }()
  37. var viewerQuickLook: NCViewerQuickLook?
  38. var documentController: UIDocumentInteractionController?
  39. let utilityFileSystem = NCUtilityFileSystem()
  40. let utility = NCUtility()
  41. let appDelegate = UIApplication.shared.delegate as? AppDelegate
  42. // MARK: - Download
  43. @objc func downloadedFile(_ notification: NSNotification) {
  44. guard let userInfo = notification.userInfo as NSDictionary?,
  45. let ocId = userInfo["ocId"] as? String,
  46. let selector = userInfo["selector"] as? String,
  47. let error = userInfo["error"] as? NKError,
  48. let account = userInfo["account"] as? String,
  49. account == appDelegate?.account
  50. else { return }
  51. guard error == .success else {
  52. // File do not exists on server, remove in local
  53. if error.errorCode == NCGlobal.shared.errorResourceNotFound || error.errorCode == NCGlobal.shared.errorBadServerResponse {
  54. do {
  55. try FileManager.default.removeItem(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(ocId))
  56. } catch { }
  57. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocId))
  58. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", ocId))
  59. } else {
  60. NCContentPresenter().messageNotification("_download_file_", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  61. }
  62. return
  63. }
  64. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) else { return }
  65. switch selector {
  66. case NCGlobal.shared.selectorLoadFileQuickLook:
  67. DispatchQueue.main.async {
  68. let fileNamePath = self.utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  69. let fileNameTemp = NSTemporaryDirectory() + metadata.fileNameView
  70. let viewerQuickLook = NCViewerQuickLook(with: URL(fileURLWithPath: fileNameTemp), isEditingEnabled: true, metadata: metadata)
  71. if let image = UIImage(contentsOfFile: fileNamePath) {
  72. if let data = image.jpegData(compressionQuality: 1) {
  73. do {
  74. try data.write(to: URL(fileURLWithPath: fileNameTemp))
  75. } catch {
  76. return
  77. }
  78. }
  79. let navigationController = UINavigationController(rootViewController: viewerQuickLook)
  80. navigationController.modalPresentationStyle = .fullScreen
  81. self.appDelegate?.window?.rootViewController?.present(navigationController, animated: true)
  82. } else {
  83. self.utilityFileSystem.copyFile(atPath: fileNamePath, toPath: fileNameTemp)
  84. self.appDelegate?.window?.rootViewController?.present(viewerQuickLook, animated: true)
  85. }
  86. }
  87. case NCGlobal.shared.selectorLoadFileView:
  88. DispatchQueue.main.async {
  89. guard UIApplication.shared.applicationState == .active else { return }
  90. if metadata.contentType.contains("opendocument") && !self.utility.isRichDocument(metadata) {
  91. self.openDocumentController(metadata: metadata)
  92. } else if metadata.classFile == NKCommon.TypeClassFile.compress.rawValue || metadata.classFile == NKCommon.TypeClassFile.unknow.rawValue {
  93. self.openDocumentController(metadata: metadata)
  94. } else {
  95. if let viewController = self.appDelegate?.activeViewController {
  96. let imageIcon = UIImage(contentsOfFile: self.utilityFileSystem.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  97. NCViewer().view(viewController: viewController, metadata: metadata, metadatas: [metadata], imageIcon: imageIcon)
  98. }
  99. }
  100. }
  101. case NCGlobal.shared.selectorOpenIn:
  102. DispatchQueue.main.async {
  103. if UIApplication.shared.applicationState == .active {
  104. self.openDocumentController(metadata: metadata)
  105. }
  106. }
  107. case NCGlobal.shared.selectorPrint:
  108. // waiting close menu
  109. // https://github.com/nextcloud/ios/issues/2278
  110. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  111. self.printDocument(metadata: metadata)
  112. }
  113. case NCGlobal.shared.selectorSaveAlbum:
  114. DispatchQueue.main.async {
  115. self.saveAlbum(metadata: metadata)
  116. }
  117. case NCGlobal.shared.selectorSaveAsScan:
  118. DispatchQueue.main.async {
  119. self.saveAsScan(metadata: metadata)
  120. }
  121. case NCGlobal.shared.selectorOpenDetail:
  122. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterOpenMediaDetail, userInfo: ["ocId": metadata.ocId])
  123. default:
  124. let applicationHandle = NCApplicationHandle()
  125. applicationHandle.downloadedFile(selector: selector, metadata: metadata)
  126. }
  127. }
  128. func setMetadataAvalableOffline(_ metadata: tableMetadata, isOffline: Bool) {
  129. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  130. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  131. if isOffline {
  132. if metadata.directory {
  133. NCManageDatabase.shared.setDirectory(serverUrl: serverUrl, offline: false, account: appDelegate.account)
  134. if let metadatas = NCManageDatabase.shared.getResultsMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND sessionSelector == %@ AND status == %d", metadata.account, serverUrl, NCGlobal.shared.selectorSynchronizationOffline, NCGlobal.shared.metadataStatusWaitDownload)) {
  135. NCManageDatabase.shared.clearMetadataSession(metadatas: metadatas)
  136. }
  137. } else {
  138. NCManageDatabase.shared.setOffLocalFile(ocId: metadata.ocId)
  139. }
  140. } else if metadata.directory {
  141. NCManageDatabase.shared.setDirectory(serverUrl: serverUrl, offline: true, account: metadata.account)
  142. NCNetworking.shared.synchronization(account: metadata.account, serverUrl: serverUrl, add: true)
  143. } else {
  144. var metadatasSynchronizationOffline: [tableMetadata] = []
  145. metadatasSynchronizationOffline.append(metadata)
  146. if let metadata = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  147. metadatasSynchronizationOffline.append(metadata)
  148. }
  149. NCManageDatabase.shared.addLocalFile(metadata: metadata, offline: true)
  150. NCManageDatabase.shared.setMetadatasSessionInWaitDownload(metadatas: metadatasSynchronizationOffline,
  151. session: NCNetworking.shared.sessionDownloadBackground,
  152. selector: NCGlobal.shared.selectorSynchronizationOffline)
  153. }
  154. }
  155. func viewerFile(account: String, fileId: String, viewController: UIViewController) {
  156. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate, let hudView = appDelegate.window?.rootViewController?.view else { return }
  157. var downloadRequest: DownloadRequest?
  158. if let metadata = NCManageDatabase.shared.getMetadataFromFileId(fileId) {
  159. do {
  160. let attr = try FileManager.default.attributesOfItem(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  161. let fileSize = attr[FileAttributeKey.size] as? UInt64 ?? 0
  162. if fileSize > 0 {
  163. NCViewer().view(viewController: viewController, metadata: metadata, metadatas: [metadata], imageIcon: nil)
  164. return
  165. }
  166. } catch {
  167. print("Error: \(error)")
  168. }
  169. }
  170. let hud = JGProgressHUD()
  171. hud.indicatorView = JGProgressHUDRingIndicatorView()
  172. if let indicatorView = hud.indicatorView as? JGProgressHUDRingIndicatorView {
  173. indicatorView.ringWidth = 1.5
  174. }
  175. hud.tapOnHUDViewBlock = { _ in
  176. if let request = downloadRequest {
  177. request.cancel()
  178. }
  179. }
  180. hud.show(in: hudView)
  181. NextcloudKit.shared.getFileFromFileId(fileId: fileId) { account, file, _, error in
  182. hud.dismiss()
  183. if error != .success {
  184. NCContentPresenter().showError(error: error)
  185. } else if let file = file {
  186. let isDirectoryE2EE = self.utilityFileSystem.isDirectoryE2EE(file: file)
  187. let metadata = NCManageDatabase.shared.convertFileToMetadata(file, isDirectoryE2EE: isDirectoryE2EE)
  188. NCManageDatabase.shared.addMetadata(metadata)
  189. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  190. let fileNameLocalPath = self.utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  191. if metadata.isAudioOrVideo {
  192. NCViewer().view(viewController: viewController, metadata: metadata, metadatas: [metadata], imageIcon: nil)
  193. } else {
  194. hud.show(in: hudView)
  195. NextcloudKit.shared.download(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, requestHandler: { request in
  196. downloadRequest = request
  197. }, taskHandler: { _ in
  198. }, progressHandler: { progress in
  199. hud.progress = Float(progress.fractionCompleted)
  200. }) { accountDownload, _, _, _, _, _, error in
  201. hud.dismiss()
  202. if account == accountDownload && error == .success {
  203. NCManageDatabase.shared.addLocalFile(metadata: metadata)
  204. NCViewer().view(viewController: viewController, metadata: metadata, metadatas: [metadata], imageIcon: nil)
  205. }
  206. }
  207. }
  208. } else {
  209. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_file_not_found_")
  210. NCContentPresenter().showError(error: error)
  211. }
  212. }
  213. }
  214. // MARK: - Upload
  215. @objc func uploadedFile(_ notification: NSNotification) {
  216. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  217. guard let userInfo = notification.userInfo as NSDictionary?,
  218. let error = userInfo["error"] as? NKError,
  219. let account = userInfo["account"] as? String,
  220. account == appDelegate.account
  221. else { return }
  222. if error != .success, error.errorCode != NSURLErrorCancelled, error.errorCode != NCGlobal.shared.errorRequestExplicityCancelled {
  223. NCContentPresenter().messageNotification("_upload_file_", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  224. }
  225. }
  226. // MARK: -
  227. func openShare(viewController: UIViewController, metadata: tableMetadata, page: NCBrandOptions.NCInfoPagingTab) {
  228. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  229. var page = page
  230. NCActivityIndicator.shared.start(backgroundView: viewController.view)
  231. NCNetworking.shared.readFile(serverUrlFileName: serverUrlFileName, queue: .main) { _, metadata, error in
  232. NCActivityIndicator.shared.stop()
  233. if let metadata = metadata, error == .success {
  234. var pages: [NCBrandOptions.NCInfoPagingTab] = []
  235. let shareNavigationController = UIStoryboard(name: "NCShare", bundle: nil).instantiateInitialViewController() as? UINavigationController
  236. let shareViewController = shareNavigationController?.topViewController as? NCSharePaging
  237. for value in NCBrandOptions.NCInfoPagingTab.allCases {
  238. pages.append(value)
  239. }
  240. if NCGlobal.shared.capabilityActivity.isEmpty, let idx = pages.firstIndex(of: .activity) {
  241. pages.remove(at: idx)
  242. }
  243. if !metadata.isSharable(), let idx = pages.firstIndex(of: .sharing) {
  244. pages.remove(at: idx)
  245. }
  246. (pages, page) = NCApplicationHandle().filterPages(pages: pages, page: page, metadata: metadata)
  247. shareViewController?.pages = pages
  248. shareViewController?.metadata = metadata
  249. if pages.contains(page) {
  250. shareViewController?.page = page
  251. } else if let page = pages.first {
  252. shareViewController?.page = page
  253. } else {
  254. return
  255. }
  256. shareNavigationController?.modalPresentationStyle = .formSheet
  257. if let shareNavigationController = shareNavigationController {
  258. viewController.present(shareNavigationController, animated: true, completion: nil)
  259. }
  260. }
  261. }
  262. }
  263. // MARK: - Open in ...
  264. func openDocumentController(metadata: tableMetadata) {
  265. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate,
  266. let mainTabBar = appDelegate.mainTabBar else { return }
  267. let fileURL = URL(fileURLWithPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  268. documentController = UIDocumentInteractionController(url: fileURL)
  269. documentController?.presentOptionsMenu(from: mainTabBar.menuRect, in: mainTabBar, animated: true)
  270. }
  271. func openActivityViewController(selectedMetadata: [tableMetadata]) {
  272. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  273. let metadatas = selectedMetadata.filter({ !$0.directory })
  274. var items: [URL] = []
  275. var downloadMetadata: [(tableMetadata, URL)] = []
  276. for metadata in metadatas {
  277. let fileURL = URL(fileURLWithPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  278. if utilityFileSystem.fileProviderStorageExists(metadata) {
  279. items.append(fileURL)
  280. } else {
  281. downloadMetadata.append((metadata, fileURL))
  282. }
  283. }
  284. let processor = ParallelWorker(n: 5, titleKey: "_downloading_", totalTasks: downloadMetadata.count, hudView: appDelegate.window?.rootViewController?.view)
  285. for (metadata, url) in downloadMetadata {
  286. processor.execute { completion in
  287. guard let metadata = NCManageDatabase.shared.setMetadatasSessionInWaitDownload(metadatas: [metadata],
  288. session: NextcloudKit.shared.nkCommonInstance.sessionIdentifierDownload,
  289. selector: "") else { return completion() }
  290. NCNetworking.shared.download(metadata: metadata, withNotificationProgressTask: false) {
  291. } progressHandler: { progress in
  292. processor.hud?.progress = Float(progress.fractionCompleted)
  293. } completion: { _, _ in
  294. if self.utilityFileSystem.fileProviderStorageExists(metadata) { items.append(url) }
  295. completion()
  296. }
  297. }
  298. }
  299. processor.completeWork {
  300. guard !items.isEmpty, let mainTabBar = appDelegate.mainTabBar else { return }
  301. let activityViewController = UIActivityViewController(activityItems: items, applicationActivities: nil)
  302. activityViewController.popoverPresentationController?.permittedArrowDirections = .any
  303. activityViewController.popoverPresentationController?.sourceView = mainTabBar
  304. activityViewController.popoverPresentationController?.sourceRect = mainTabBar.menuRect
  305. appDelegate.window?.rootViewController?.present(activityViewController, animated: true)
  306. }
  307. }
  308. // MARK: - Save as scan
  309. func saveAsScan(metadata: tableMetadata) {
  310. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  311. let fileNamePath = utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  312. 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)!
  313. let fileNamePathDestination = utilityFileSystem.directoryScan + "/" + fileNameDestination
  314. utilityFileSystem.copyFile(atPath: fileNamePath, toPath: fileNamePathDestination)
  315. let storyboard = UIStoryboard(name: "NCScan", bundle: nil)
  316. let navigationController = storyboard.instantiateInitialViewController()!
  317. navigationController.modalPresentationStyle = UIModalPresentationStyle.pageSheet
  318. appDelegate.window?.rootViewController?.present(navigationController, animated: true, completion: nil)
  319. }
  320. // MARK: - Print
  321. func printDocument(metadata: tableMetadata) {
  322. let fileNameURL = URL(fileURLWithPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  323. let printController = UIPrintInteractionController.shared
  324. let printInfo = UIPrintInfo(dictionary: nil)
  325. printInfo.jobName = fileNameURL.lastPathComponent
  326. printInfo.outputType = metadata.isImage ? .photo : .general
  327. printController.printInfo = printInfo
  328. printController.showsNumberOfCopies = true
  329. guard !UIPrintInteractionController.canPrint(fileNameURL) else {
  330. printController.printingItem = fileNameURL
  331. printController.present(animated: true)
  332. return
  333. }
  334. // can't print without data
  335. guard let data = try? Data(contentsOf: fileNameURL) else { return }
  336. if let svg = SVGKImage(data: data) {
  337. printController.printingItem = svg.uiImage
  338. printController.present(animated: true)
  339. return
  340. }
  341. guard let text = String(data: data, encoding: .utf8) else { return }
  342. let formatter = UISimpleTextPrintFormatter(text: text)
  343. formatter.perPageContentInsets.top = 72
  344. formatter.perPageContentInsets.bottom = 72
  345. formatter.perPageContentInsets.left = 72
  346. formatter.perPageContentInsets.right = 72
  347. printController.printFormatter = formatter
  348. printController.present(animated: true)
  349. }
  350. // MARK: - Save photo
  351. func saveAlbum(metadata: tableMetadata) {
  352. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  353. let fileNamePath = utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  354. NCAskAuthorization().askAuthorizationPhotoLibrary(viewController: appDelegate.mainTabBar?.window?.rootViewController) { hasPermission in
  355. guard hasPermission else {
  356. let error = NKError(errorCode: NCGlobal.shared.errorFileNotSaved, errorDescription: "_access_photo_not_enabled_msg_")
  357. return NCContentPresenter().messageNotification("_access_photo_not_enabled_", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error)
  358. }
  359. let errorSave = NKError(errorCode: NCGlobal.shared.errorFileNotSaved, errorDescription: "_file_not_saved_cameraroll_")
  360. do {
  361. if metadata.isImage {
  362. let data = try Data(contentsOf: URL(fileURLWithPath: fileNamePath))
  363. PHPhotoLibrary.shared().performChanges({
  364. let assetRequest = PHAssetCreationRequest.forAsset()
  365. assetRequest.addResource(with: .photo, data: data, options: nil)
  366. }) { success, _ in
  367. if !success {
  368. NCContentPresenter().messageNotification("_save_selected_files_", error: errorSave, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error)
  369. }
  370. }
  371. } else if metadata.isVideo {
  372. PHPhotoLibrary.shared().performChanges({
  373. PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: fileNamePath))
  374. }) { success, _ in
  375. if !success {
  376. NCContentPresenter().messageNotification("_save_selected_files_", error: errorSave, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error)
  377. }
  378. }
  379. } else {
  380. NCContentPresenter().messageNotification("_save_selected_files_", error: errorSave, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error)
  381. return
  382. }
  383. } catch {
  384. NCContentPresenter().messageNotification("_save_selected_files_", error: errorSave, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error)
  385. }
  386. }
  387. }
  388. // MARK: - Copy & Paste
  389. func copyPasteboard(pasteboardOcIds: [String]) {
  390. var items = [[String: Any]]()
  391. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  392. let hudView = appDelegate.window?.rootViewController?.view
  393. var fractionCompleted: Float = 0
  394. // getting file data can take some time and block the main queue
  395. DispatchQueue.global(qos: .userInitiated).async {
  396. var downloadMetadatas: [tableMetadata] = []
  397. for ocid in pasteboardOcIds {
  398. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocid) else { continue }
  399. if let pasteboardItem = metadata.toPasteBoardItem() {
  400. items.append(pasteboardItem)
  401. } else {
  402. downloadMetadatas.append(metadata)
  403. }
  404. }
  405. // do 5 downloads in parallel to optimize efficiency
  406. let processor = ParallelWorker(n: 5, titleKey: "_downloading_", totalTasks: downloadMetadatas.count, hudView: hudView)
  407. for metadata in downloadMetadatas {
  408. processor.execute { completion in
  409. guard let metadata = NCManageDatabase.shared.setMetadatasSessionInWaitDownload(metadatas: [metadata],
  410. session: NextcloudKit.shared.nkCommonInstance.sessionIdentifierDownload,
  411. selector: "") else { return completion() }
  412. NCNetworking.shared.download(metadata: metadata, withNotificationProgressTask: false) {
  413. } requestHandler: { _ in
  414. } progressHandler: { progress in
  415. if Float(progress.fractionCompleted) > fractionCompleted || fractionCompleted == 0 {
  416. processor.hud?.progress = Float(progress.fractionCompleted)
  417. fractionCompleted = Float(progress.fractionCompleted)
  418. }
  419. } completion: { _, _ in
  420. fractionCompleted = 0
  421. completion()
  422. }
  423. }
  424. }
  425. processor.completeWork {
  426. items.append(contentsOf: downloadMetadatas.compactMap({ $0.toPasteBoardItem() }))
  427. UIPasteboard.general.setItems(items, options: [:])
  428. }
  429. }
  430. }
  431. func pastePasteboard(serverUrl: String) {
  432. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  433. var fractionCompleted: Float = 0
  434. let processor = ParallelWorker(n: 5, titleKey: "_uploading_", totalTasks: nil, hudView: appDelegate.window?.rootViewController?.view)
  435. func uploadPastePasteboard(fileName: String, serverUrlFileName: String, fileNameLocalPath: String, serverUrl: String, completion: @escaping () -> Void) {
  436. NextcloudKit.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath) { request in
  437. NCNetworking.shared.uploadRequest[fileNameLocalPath] = request
  438. } progressHandler: { progress in
  439. if Float(progress.fractionCompleted) > fractionCompleted || fractionCompleted == 0 {
  440. processor.hud?.progress = Float(progress.fractionCompleted)
  441. fractionCompleted = Float(progress.fractionCompleted)
  442. }
  443. } completionHandler: { account, ocId, etag, _, _, _, afError, error in
  444. NCNetworking.shared.uploadRequest.removeValue(forKey: fileNameLocalPath)
  445. if error == .success && etag != nil && ocId != nil {
  446. let toPath = self.utilityFileSystem.getDirectoryProviderStorageOcId(ocId!, fileNameView: fileName)
  447. self.utilityFileSystem.moveFile(atPath: fileNameLocalPath, toPath: toPath)
  448. NCManageDatabase.shared.addLocalFile(account: account, etag: etag!, ocId: ocId!, fileName: fileName)
  449. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSourceNetwork)
  450. } else if afError?.isExplicitlyCancelledError ?? false {
  451. print("cancel")
  452. } else {
  453. NCContentPresenter().showError(error: error)
  454. }
  455. fractionCompleted = 0
  456. completion()
  457. }
  458. }
  459. for (index, items) in UIPasteboard.general.items.enumerated() {
  460. for item in items {
  461. let results = NextcloudKit.shared.nkCommonInstance.getFileProperties(inUTI: item.key as CFString)
  462. guard !results.ext.isEmpty,
  463. let data = UIPasteboard.general.data(forPasteboardType: item.key, inItemSet: IndexSet([index]))?.first
  464. else { continue }
  465. let fileName = results.name + "_" + NCKeychain().incrementalNumber + "." + results.ext
  466. let serverUrlFileName = serverUrl + "/" + fileName
  467. let ocIdUpload = UUID().uuidString
  468. let fileNameLocalPath = utilityFileSystem.getDirectoryProviderStorageOcId(ocIdUpload, fileNameView: fileName)
  469. do { try data.write(to: URL(fileURLWithPath: fileNameLocalPath)) } catch { continue }
  470. processor.execute { completion in
  471. uploadPastePasteboard(fileName: fileName, serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, serverUrl: serverUrl, completion: completion)
  472. }
  473. }
  474. }
  475. processor.completeWork()
  476. }
  477. // MARK: -
  478. func openFileViewInFolder(serverUrl: String, fileNameBlink: String?, fileNameOpen: String?) {
  479. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  480. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  481. var topNavigationController: UINavigationController?
  482. var pushServerUrl = self.utilityFileSystem.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId)
  483. guard var mostViewController = appDelegate.window?.rootViewController?.topMostViewController() else { return }
  484. if mostViewController.isModal {
  485. mostViewController.dismiss(animated: false)
  486. if let viewController = appDelegate.window?.rootViewController?.topMostViewController() {
  487. mostViewController = viewController
  488. }
  489. }
  490. mostViewController.navigationController?.popToRootViewController(animated: false)
  491. if let tabBarController = appDelegate.window?.rootViewController as? UITabBarController {
  492. tabBarController.selectedIndex = 0
  493. if let navigationController = tabBarController.viewControllers?.first as? UINavigationController {
  494. navigationController.popToRootViewController(animated: false)
  495. topNavigationController = navigationController
  496. }
  497. }
  498. if pushServerUrl == serverUrl {
  499. let viewController = topNavigationController?.topViewController as? NCFiles
  500. viewController?.blinkCell(fileName: fileNameBlink)
  501. viewController?.openFile(fileName: fileNameOpen)
  502. return
  503. }
  504. guard let topNavigationController = topNavigationController else { return }
  505. let diffDirectory = serverUrl.replacingOccurrences(of: pushServerUrl, with: "")
  506. var subDirs = diffDirectory.split(separator: "/")
  507. while pushServerUrl != serverUrl, !subDirs.isEmpty {
  508. guard let dir = subDirs.first, let viewController = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles else { return }
  509. pushServerUrl = pushServerUrl + "/" + dir
  510. viewController.serverUrl = pushServerUrl
  511. viewController.isRoot = false
  512. viewController.titleCurrentFolder = String(dir)
  513. if pushServerUrl == serverUrl {
  514. viewController.fileNameBlink = fileNameBlink
  515. viewController.fileNameOpen = fileNameOpen
  516. }
  517. appDelegate.listFilesVC[serverUrl] = viewController
  518. viewController.navigationItem.backButtonTitle = viewController.titleCurrentFolder
  519. topNavigationController.pushViewController(viewController, animated: false)
  520. subDirs.remove(at: 0)
  521. }
  522. }
  523. }
  524. // MARK: - NCSelect + Delegate
  525. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool) {
  526. if let serverUrl, !items.isEmpty {
  527. if copy {
  528. Task {
  529. var error = NKError()
  530. var ocId: [String] = []
  531. for case let metadata as tableMetadata in items where error == .success {
  532. error = await NCNetworking.shared.copyMetadata(metadata, serverUrlTo: serverUrl, overwrite: overwrite)
  533. if error == .success {
  534. ocId.append(metadata.ocId)
  535. }
  536. }
  537. if error != .success {
  538. NCContentPresenter().showError(error: error)
  539. }
  540. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterCopyFile, userInfo: ["ocId": ocId, "error": error])
  541. }
  542. } else {
  543. Task {
  544. var error = NKError()
  545. var ocId: [String] = []
  546. for case let metadata as tableMetadata in items where error == .success {
  547. error = await NCNetworking.shared.moveMetadata(metadata, serverUrlTo: serverUrl, overwrite: overwrite)
  548. if error == .success {
  549. ocId.append(metadata.ocId)
  550. }
  551. }
  552. if error != .success {
  553. NCContentPresenter().showError(error: error)
  554. }
  555. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterMoveFile, userInfo: ["ocId": ocId, "error": error])
  556. }
  557. }
  558. }
  559. }
  560. func openSelectView(items: [tableMetadata]) {
  561. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  562. let navigationController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateInitialViewController() as? UINavigationController
  563. let topViewController = navigationController?.topViewController as? NCSelect
  564. var listViewController = [NCSelect]()
  565. var copyItems: [tableMetadata] = []
  566. for item in items {
  567. copyItems.append(item)
  568. }
  569. let homeUrl = utilityFileSystem.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId)
  570. var serverUrl = copyItems[0].serverUrl
  571. // Setup view controllers such that the current view is of the same directory the items to be copied are in
  572. while true {
  573. // If not in the topmost directory, create a new view controller and set correct title.
  574. // If in the topmost directory, use the default view controller as the base.
  575. var viewController: NCSelect?
  576. if serverUrl != homeUrl {
  577. viewController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateViewController(withIdentifier: "NCSelect.storyboard") as? NCSelect
  578. if viewController == nil {
  579. return
  580. }
  581. viewController!.titleCurrentFolder = (serverUrl as NSString).lastPathComponent
  582. } else {
  583. viewController = topViewController
  584. }
  585. guard let vc = viewController else { return }
  586. vc.delegate = self
  587. vc.typeOfCommandView = .copyMove
  588. vc.items = copyItems
  589. vc.serverUrl = serverUrl
  590. vc.navigationItem.backButtonTitle = vc.titleCurrentFolder
  591. listViewController.insert(vc, at: 0)
  592. if serverUrl != homeUrl {
  593. if let path = utilityFileSystem.deleteLastPath(serverUrlPath: serverUrl) {
  594. serverUrl = path
  595. }
  596. } else {
  597. break
  598. }
  599. }
  600. navigationController?.setViewControllers(listViewController, animated: false)
  601. navigationController?.modalPresentationStyle = .formSheet
  602. if let navigationController = navigationController {
  603. appDelegate.window?.rootViewController?.present(navigationController, animated: true, completion: nil)
  604. }
  605. }
  606. }
  607. fileprivate extension tableMetadata {
  608. func toPasteBoardItem() -> [String: Any]? {
  609. // Get Data
  610. let fileUrl = URL(fileURLWithPath: NCUtilityFileSystem().getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView))
  611. guard NCUtilityFileSystem().fileProviderStorageExists(self),
  612. let data = try? Data(contentsOf: fileUrl),
  613. let unmanagedFileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension as CFString, nil)
  614. else { return nil }
  615. // Pasteboard item
  616. let fileUTI = unmanagedFileUTI.takeRetainedValue() as String
  617. return [fileUTI: data]
  618. }
  619. }