NCActionCenter.swift 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  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.selectorLoadOffline:
  108. NCManageDatabase.shared.setLocalFile(ocId: metadata.ocId, offline: true)
  109. case NCGlobal.shared.selectorPrint:
  110. // waiting close menu
  111. // https://github.com/nextcloud/ios/issues/2278
  112. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  113. self.printDocument(metadata: metadata)
  114. }
  115. case NCGlobal.shared.selectorSaveAlbum:
  116. DispatchQueue.main.async {
  117. self.saveAlbum(metadata: metadata)
  118. }
  119. case NCGlobal.shared.selectorSaveAsScan:
  120. DispatchQueue.main.async {
  121. self.saveAsScan(metadata: metadata)
  122. }
  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. NCNetworking.shared.synchronization(account: metadata.account, serverUrl: serverUrl, selector: NCGlobal.shared.selectorSynchronizationOffline)
  142. } else {
  143. guard let metadata = NCManageDatabase.shared.setMetadataSessionInWaitDownload(ocId: metadata.ocId, selector: NCGlobal.shared.selectorLoadOffline) else { return }
  144. NCNetworking.shared.download(metadata: metadata, withNotificationProgressTask: true)
  145. if let metadata = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata), let metadata = NCManageDatabase.shared.setMetadataSessionInWaitDownload(ocId: metadata.ocId, selector: NCGlobal.shared.selectorLoadOffline) {
  146. NCNetworking.shared.download(metadata: metadata, withNotificationProgressTask: true)
  147. }
  148. }
  149. }
  150. func viewerFile(account: String, fileId: String, viewController: UIViewController) {
  151. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate, let hudView = appDelegate.window?.rootViewController?.view else { return }
  152. var downloadRequest: DownloadRequest?
  153. if let metadata = NCManageDatabase.shared.getMetadataFromFileId(fileId) {
  154. do {
  155. let attr = try FileManager.default.attributesOfItem(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  156. let fileSize = attr[FileAttributeKey.size] as? UInt64 ?? 0
  157. if fileSize > 0 {
  158. NCViewer().view(viewController: viewController, metadata: metadata, metadatas: [metadata], imageIcon: nil)
  159. return
  160. }
  161. } catch {
  162. print("Error: \(error)")
  163. }
  164. }
  165. let hud = JGProgressHUD()
  166. hud.indicatorView = JGProgressHUDRingIndicatorView()
  167. if let indicatorView = hud.indicatorView as? JGProgressHUDRingIndicatorView {
  168. indicatorView.ringWidth = 1.5
  169. }
  170. hud.tapOnHUDViewBlock = { _ in
  171. if let request = downloadRequest {
  172. request.cancel()
  173. }
  174. }
  175. hud.show(in: hudView)
  176. NextcloudKit.shared.getFileFromFileId(fileId: fileId) { account, file, _, error in
  177. hud.dismiss()
  178. if error != .success {
  179. NCContentPresenter().showError(error: error)
  180. } else if let file = file {
  181. let isDirectoryE2EE = self.utilityFileSystem.isDirectoryE2EE(file: file)
  182. let metadata = NCManageDatabase.shared.convertFileToMetadata(file, isDirectoryE2EE: isDirectoryE2EE)
  183. NCManageDatabase.shared.addMetadata(metadata)
  184. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  185. let fileNameLocalPath = self.utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  186. if metadata.isAudioOrVideo {
  187. NCViewer().view(viewController: viewController, metadata: metadata, metadatas: [metadata], imageIcon: nil)
  188. } else {
  189. hud.show(in: hudView)
  190. NextcloudKit.shared.download(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, requestHandler: { request in
  191. downloadRequest = request
  192. }, taskHandler: { _ in
  193. }, progressHandler: { progress in
  194. hud.progress = Float(progress.fractionCompleted)
  195. }) { accountDownload, _, _, _, _, _, error in
  196. hud.dismiss()
  197. if account == accountDownload && error == .success {
  198. NCManageDatabase.shared.addLocalFile(metadata: metadata)
  199. NCViewer().view(viewController: viewController, metadata: metadata, metadatas: [metadata], imageIcon: nil)
  200. }
  201. }
  202. }
  203. } else {
  204. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_file_not_found_")
  205. NCContentPresenter().showError(error: error)
  206. }
  207. }
  208. }
  209. // MARK: - Upload
  210. @objc func uploadedFile(_ notification: NSNotification) {
  211. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  212. guard let userInfo = notification.userInfo as NSDictionary?,
  213. let error = userInfo["error"] as? NKError,
  214. let account = userInfo["account"] as? String,
  215. account == appDelegate.account
  216. else { return }
  217. if error != .success, error.errorCode != NSURLErrorCancelled, error.errorCode != NCGlobal.shared.errorRequestExplicityCancelled {
  218. NCContentPresenter().messageNotification("_upload_file_", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  219. }
  220. }
  221. // MARK: -
  222. func openShare(viewController: UIViewController, metadata: tableMetadata, page: NCBrandOptions.NCInfoPagingTab) {
  223. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  224. var page = page
  225. NCActivityIndicator.shared.start(backgroundView: viewController.view)
  226. NCNetworking.shared.readFile(serverUrlFileName: serverUrlFileName, queue: .main) { _, metadata, error in
  227. NCActivityIndicator.shared.stop()
  228. if let metadata = metadata, error == .success {
  229. var pages: [NCBrandOptions.NCInfoPagingTab] = []
  230. let shareNavigationController = UIStoryboard(name: "NCShare", bundle: nil).instantiateInitialViewController() as? UINavigationController
  231. let shareViewController = shareNavigationController?.topViewController as? NCSharePaging
  232. for value in NCBrandOptions.NCInfoPagingTab.allCases {
  233. pages.append(value)
  234. }
  235. if NCGlobal.shared.capabilityActivity.isEmpty, let idx = pages.firstIndex(of: .activity) {
  236. pages.remove(at: idx)
  237. }
  238. if !metadata.isSharable(), let idx = pages.firstIndex(of: .sharing) {
  239. pages.remove(at: idx)
  240. }
  241. (pages, page) = NCApplicationHandle().filterPages(pages: pages, page: page, metadata: metadata)
  242. shareViewController?.pages = pages
  243. shareViewController?.metadata = metadata
  244. if pages.contains(page) {
  245. shareViewController?.page = page
  246. } else if let page = pages.first {
  247. shareViewController?.page = page
  248. } else {
  249. return
  250. }
  251. shareNavigationController?.modalPresentationStyle = .formSheet
  252. if let shareNavigationController = shareNavigationController {
  253. viewController.present(shareNavigationController, animated: true, completion: nil)
  254. }
  255. }
  256. }
  257. }
  258. // MARK: - Open in ...
  259. func openDocumentController(metadata: tableMetadata) {
  260. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate,
  261. let mainTabBar = appDelegate.mainTabBar else { return }
  262. let fileURL = URL(fileURLWithPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  263. documentController = UIDocumentInteractionController(url: fileURL)
  264. documentController?.presentOptionsMenu(from: mainTabBar.menuRect, in: mainTabBar, animated: true)
  265. }
  266. func openActivityViewController(selectedMetadata: [tableMetadata]) {
  267. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  268. let metadatas = selectedMetadata.filter({ !$0.directory })
  269. var items: [URL] = []
  270. var downloadMetadata: [(tableMetadata, URL)] = []
  271. for metadata in metadatas {
  272. let fileURL = URL(fileURLWithPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  273. if utilityFileSystem.fileProviderStorageExists(metadata) {
  274. items.append(fileURL)
  275. } else {
  276. downloadMetadata.append((metadata, fileURL))
  277. }
  278. }
  279. let processor = ParallelWorker(n: 5, titleKey: "_downloading_", totalTasks: downloadMetadata.count, hudView: appDelegate.window?.rootViewController?.view)
  280. for (metadata, url) in downloadMetadata {
  281. processor.execute { completion in
  282. guard let metadata = NCManageDatabase.shared.setMetadataSessionInWaitDownload(ocId: metadata.ocId, selector: "") else { return completion() }
  283. NCNetworking.shared.download(metadata: metadata, withNotificationProgressTask: false) {
  284. } progressHandler: { progress in
  285. processor.hud?.progress = Float(progress.fractionCompleted)
  286. } completion: { _, _ in
  287. if self.utilityFileSystem.fileProviderStorageExists(metadata) { items.append(url) }
  288. completion()
  289. }
  290. }
  291. }
  292. processor.completeWork {
  293. guard !items.isEmpty, let mainTabBar = appDelegate.mainTabBar else { return }
  294. let activityViewController = UIActivityViewController(activityItems: items, applicationActivities: nil)
  295. activityViewController.popoverPresentationController?.permittedArrowDirections = .any
  296. activityViewController.popoverPresentationController?.sourceView = mainTabBar
  297. activityViewController.popoverPresentationController?.sourceRect = mainTabBar.menuRect
  298. appDelegate.window?.rootViewController?.present(activityViewController, animated: true)
  299. }
  300. }
  301. // MARK: - Save as scan
  302. func saveAsScan(metadata: tableMetadata) {
  303. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  304. let fileNamePath = utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  305. 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)!
  306. let fileNamePathDestination = utilityFileSystem.directoryScan + "/" + fileNameDestination
  307. utilityFileSystem.copyFile(atPath: fileNamePath, toPath: fileNamePathDestination)
  308. let storyboard = UIStoryboard(name: "NCScan", bundle: nil)
  309. let navigationController = storyboard.instantiateInitialViewController()!
  310. navigationController.modalPresentationStyle = UIModalPresentationStyle.pageSheet
  311. appDelegate.window?.rootViewController?.present(navigationController, animated: true, completion: nil)
  312. }
  313. // MARK: - Print
  314. func printDocument(metadata: tableMetadata) {
  315. let fileNameURL = URL(fileURLWithPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  316. let printController = UIPrintInteractionController.shared
  317. let printInfo = UIPrintInfo(dictionary: nil)
  318. printInfo.jobName = fileNameURL.lastPathComponent
  319. printInfo.outputType = metadata.isImage ? .photo : .general
  320. printController.printInfo = printInfo
  321. printController.showsNumberOfCopies = true
  322. guard !UIPrintInteractionController.canPrint(fileNameURL) else {
  323. printController.printingItem = fileNameURL
  324. printController.present(animated: true)
  325. return
  326. }
  327. // can't print without data
  328. guard let data = try? Data(contentsOf: fileNameURL) else { return }
  329. if let svg = SVGKImage(data: data) {
  330. printController.printingItem = svg.uiImage
  331. printController.present(animated: true)
  332. return
  333. }
  334. guard let text = String(data: data, encoding: .utf8) else { return }
  335. let formatter = UISimpleTextPrintFormatter(text: text)
  336. formatter.perPageContentInsets.top = 72
  337. formatter.perPageContentInsets.bottom = 72
  338. formatter.perPageContentInsets.left = 72
  339. formatter.perPageContentInsets.right = 72
  340. printController.printFormatter = formatter
  341. printController.present(animated: true)
  342. }
  343. // MARK: - Save photo
  344. func saveAlbum(metadata: tableMetadata) {
  345. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  346. let fileNamePath = utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  347. NCAskAuthorization().askAuthorizationPhotoLibrary(viewController: appDelegate.mainTabBar?.window?.rootViewController) { hasPermission in
  348. guard hasPermission else {
  349. let error = NKError(errorCode: NCGlobal.shared.errorFileNotSaved, errorDescription: "_access_photo_not_enabled_msg_")
  350. return NCContentPresenter().messageNotification("_access_photo_not_enabled_", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error)
  351. }
  352. let errorSave = NKError(errorCode: NCGlobal.shared.errorFileNotSaved, errorDescription: "_file_not_saved_cameraroll_")
  353. do {
  354. if metadata.isImage {
  355. let data = try Data(contentsOf: URL(fileURLWithPath: fileNamePath))
  356. PHPhotoLibrary.shared().performChanges({
  357. let assetRequest = PHAssetCreationRequest.forAsset()
  358. assetRequest.addResource(with: .photo, data: data, options: nil)
  359. }) { success, _ in
  360. if !success {
  361. NCContentPresenter().messageNotification("_save_selected_files_", error: errorSave, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error)
  362. }
  363. }
  364. } else if metadata.isVideo {
  365. PHPhotoLibrary.shared().performChanges({
  366. PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: fileNamePath))
  367. }) { success, _ in
  368. if !success {
  369. NCContentPresenter().messageNotification("_save_selected_files_", error: errorSave, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error)
  370. }
  371. }
  372. } else {
  373. NCContentPresenter().messageNotification("_save_selected_files_", error: errorSave, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error)
  374. return
  375. }
  376. } catch {
  377. NCContentPresenter().messageNotification("_save_selected_files_", error: errorSave, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error)
  378. }
  379. }
  380. }
  381. // MARK: - Copy & Paste
  382. func copyPasteboard(pasteboardOcIds: [String]) {
  383. var items = [[String: Any]]()
  384. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  385. let hudView = appDelegate.window?.rootViewController?.view
  386. var fractionCompleted: Float = 0
  387. // getting file data can take some time and block the main queue
  388. DispatchQueue.global(qos: .userInitiated).async {
  389. var downloadMetadatas: [tableMetadata] = []
  390. for ocid in pasteboardOcIds {
  391. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocid) else { continue }
  392. if let pasteboardItem = metadata.toPasteBoardItem() {
  393. items.append(pasteboardItem)
  394. } else {
  395. downloadMetadatas.append(metadata)
  396. }
  397. }
  398. // do 5 downloads in parallel to optimize efficiency
  399. let processor = ParallelWorker(n: 5, titleKey: "_downloading_", totalTasks: downloadMetadatas.count, hudView: hudView)
  400. for metadata in downloadMetadatas {
  401. processor.execute { completion in
  402. guard let metadata = NCManageDatabase.shared.setMetadataSessionInWaitDownload(ocId: metadata.ocId, selector: "") else { return completion() }
  403. NCNetworking.shared.download(metadata: metadata, withNotificationProgressTask: false) {
  404. } requestHandler: { _ in
  405. } progressHandler: { progress in
  406. if Float(progress.fractionCompleted) > fractionCompleted || fractionCompleted == 0 {
  407. processor.hud?.progress = Float(progress.fractionCompleted)
  408. fractionCompleted = Float(progress.fractionCompleted)
  409. }
  410. } completion: { _, _ in
  411. fractionCompleted = 0
  412. completion()
  413. }
  414. }
  415. }
  416. processor.completeWork {
  417. items.append(contentsOf: downloadMetadatas.compactMap({ $0.toPasteBoardItem() }))
  418. UIPasteboard.general.setItems(items, options: [:])
  419. }
  420. }
  421. }
  422. func pastePasteboard(serverUrl: String) {
  423. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  424. var fractionCompleted: Float = 0
  425. let processor = ParallelWorker(n: 5, titleKey: "_uploading_", totalTasks: nil, hudView: appDelegate.window?.rootViewController?.view)
  426. func uploadPastePasteboard(fileName: String, serverUrlFileName: String, fileNameLocalPath: String, serverUrl: String, completion: @escaping () -> Void) {
  427. NextcloudKit.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath) { request in
  428. NCNetworking.shared.uploadRequest[fileNameLocalPath] = request
  429. } progressHandler: { progress in
  430. if Float(progress.fractionCompleted) > fractionCompleted || fractionCompleted == 0 {
  431. processor.hud?.progress = Float(progress.fractionCompleted)
  432. fractionCompleted = Float(progress.fractionCompleted)
  433. }
  434. } completionHandler: { account, ocId, etag, _, _, _, afError, error in
  435. NCNetworking.shared.uploadRequest.removeValue(forKey: fileNameLocalPath)
  436. if error == .success && etag != nil && ocId != nil {
  437. let toPath = self.utilityFileSystem.getDirectoryProviderStorageOcId(ocId!, fileNameView: fileName)
  438. self.utilityFileSystem.moveFile(atPath: fileNameLocalPath, toPath: toPath)
  439. NCManageDatabase.shared.addLocalFile(account: account, etag: etag!, ocId: ocId!, fileName: fileName)
  440. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSourceNetwork)
  441. } else if afError?.isExplicitlyCancelledError ?? false {
  442. print("cancel")
  443. } else {
  444. NCContentPresenter().showError(error: error)
  445. }
  446. fractionCompleted = 0
  447. completion()
  448. }
  449. }
  450. for (index, items) in UIPasteboard.general.items.enumerated() {
  451. for item in items {
  452. let results = NextcloudKit.shared.nkCommonInstance.getFileProperties(inUTI: item.key as CFString)
  453. guard !results.ext.isEmpty,
  454. let data = UIPasteboard.general.data(forPasteboardType: item.key, inItemSet: IndexSet([index]))?.first
  455. else { continue }
  456. let fileName = results.name + "_" + NCKeychain().incrementalNumber + "." + results.ext
  457. let serverUrlFileName = serverUrl + "/" + fileName
  458. let ocIdUpload = UUID().uuidString
  459. let fileNameLocalPath = utilityFileSystem.getDirectoryProviderStorageOcId(ocIdUpload, fileNameView: fileName)
  460. do { try data.write(to: URL(fileURLWithPath: fileNameLocalPath)) } catch { continue }
  461. processor.execute { completion in
  462. uploadPastePasteboard(fileName: fileName, serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, serverUrl: serverUrl, completion: completion)
  463. }
  464. }
  465. }
  466. processor.completeWork()
  467. }
  468. // MARK: -
  469. func openFileViewInFolder(serverUrl: String, fileNameBlink: String?, fileNameOpen: String?) {
  470. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  471. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  472. var topNavigationController: UINavigationController?
  473. var pushServerUrl = self.utilityFileSystem.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId)
  474. guard var mostViewController = appDelegate.window?.rootViewController?.topMostViewController() else { return }
  475. if mostViewController.isModal {
  476. mostViewController.dismiss(animated: false)
  477. if let viewController = appDelegate.window?.rootViewController?.topMostViewController() {
  478. mostViewController = viewController
  479. }
  480. }
  481. mostViewController.navigationController?.popToRootViewController(animated: false)
  482. if let tabBarController = appDelegate.window?.rootViewController as? UITabBarController {
  483. tabBarController.selectedIndex = 0
  484. if let navigationController = tabBarController.viewControllers?.first as? UINavigationController {
  485. navigationController.popToRootViewController(animated: false)
  486. topNavigationController = navigationController
  487. }
  488. }
  489. if pushServerUrl == serverUrl {
  490. let viewController = topNavigationController?.topViewController as? NCFiles
  491. viewController?.blinkCell(fileName: fileNameBlink)
  492. viewController?.openFile(fileName: fileNameOpen)
  493. return
  494. }
  495. guard let topNavigationController = topNavigationController else { return }
  496. let diffDirectory = serverUrl.replacingOccurrences(of: pushServerUrl, with: "")
  497. var subDirs = diffDirectory.split(separator: "/")
  498. while pushServerUrl != serverUrl, !subDirs.isEmpty {
  499. guard let dir = subDirs.first, let viewController = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles else { return }
  500. pushServerUrl = pushServerUrl + "/" + dir
  501. viewController.serverUrl = pushServerUrl
  502. viewController.isRoot = false
  503. viewController.titleCurrentFolder = String(dir)
  504. if pushServerUrl == serverUrl {
  505. viewController.fileNameBlink = fileNameBlink
  506. viewController.fileNameOpen = fileNameOpen
  507. }
  508. appDelegate.listFilesVC[serverUrl] = viewController
  509. viewController.navigationItem.backButtonTitle = viewController.titleCurrentFolder
  510. topNavigationController.pushViewController(viewController, animated: false)
  511. subDirs.remove(at: 0)
  512. }
  513. }
  514. }
  515. // MARK: - NCSelect + Delegate
  516. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], indexPath: [IndexPath], overwrite: Bool, copy: Bool, move: Bool) {
  517. if let serverUrl, !items.isEmpty {
  518. if copy {
  519. Task {
  520. var error = NKError()
  521. var ocId: [String] = []
  522. for case let metadata as tableMetadata in items where error == .success {
  523. error = await NCNetworking.shared.copyMetadata(metadata, serverUrlTo: serverUrl, overwrite: overwrite)
  524. if error == .success {
  525. ocId.append(metadata.ocId)
  526. }
  527. }
  528. if error != .success {
  529. NCContentPresenter().showError(error: error)
  530. }
  531. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterCopyFile, userInfo: ["ocId": ocId, "indexPath": indexPath, "error": error])
  532. }
  533. } else {
  534. Task {
  535. var error = NKError()
  536. var ocId: [String] = []
  537. for case let metadata as tableMetadata in items where error == .success {
  538. error = await NCNetworking.shared.moveMetadata(metadata, serverUrlTo: serverUrl, overwrite: overwrite)
  539. if error == .success {
  540. ocId.append(metadata.ocId)
  541. }
  542. }
  543. if error != .success {
  544. NCContentPresenter().showError(error: error)
  545. }
  546. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterMoveFile, userInfo: ["ocId": ocId, "indexPath": indexPath, "error": error])
  547. }
  548. }
  549. }
  550. }
  551. func openSelectView(items: [tableMetadata], indexPath: [IndexPath]) {
  552. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  553. let navigationController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateInitialViewController() as? UINavigationController
  554. let topViewController = navigationController?.topViewController as? NCSelect
  555. var listViewController = [NCSelect]()
  556. var copyItems: [tableMetadata] = []
  557. for item in items {
  558. copyItems.append(item)
  559. }
  560. let homeUrl = utilityFileSystem.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId)
  561. var serverUrl = copyItems[0].serverUrl
  562. // Setup view controllers such that the current view is of the same directory the items to be copied are in
  563. while true {
  564. // If not in the topmost directory, create a new view controller and set correct title.
  565. // If in the topmost directory, use the default view controller as the base.
  566. var viewController: NCSelect?
  567. if serverUrl != homeUrl {
  568. viewController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateViewController(withIdentifier: "NCSelect.storyboard") as? NCSelect
  569. if viewController == nil {
  570. return
  571. }
  572. viewController!.titleCurrentFolder = (serverUrl as NSString).lastPathComponent
  573. } else {
  574. viewController = topViewController
  575. }
  576. guard let vc = viewController else { return }
  577. vc.delegate = self
  578. vc.typeOfCommandView = .copyMove
  579. vc.items = copyItems
  580. vc.serverUrl = serverUrl
  581. vc.selectIndexPath = indexPath
  582. vc.navigationItem.backButtonTitle = vc.titleCurrentFolder
  583. listViewController.insert(vc, at: 0)
  584. if serverUrl != homeUrl {
  585. if let path = utilityFileSystem.deleteLastPath(serverUrlPath: serverUrl) {
  586. serverUrl = path
  587. }
  588. } else {
  589. break
  590. }
  591. }
  592. navigationController?.setViewControllers(listViewController, animated: false)
  593. navigationController?.modalPresentationStyle = .formSheet
  594. if let navigationController = navigationController {
  595. appDelegate.window?.rootViewController?.present(navigationController, animated: true, completion: nil)
  596. }
  597. }
  598. }
  599. fileprivate extension tableMetadata {
  600. func toPasteBoardItem() -> [String: Any]? {
  601. // Get Data
  602. let fileUrl = URL(fileURLWithPath: NCUtilityFileSystem().getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView))
  603. guard NCUtilityFileSystem().fileProviderStorageExists(self),
  604. let data = try? Data(contentsOf: fileUrl),
  605. let unmanagedFileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension as CFString, nil)
  606. else { return nil }
  607. // Pasteboard item
  608. let fileUTI = unmanagedFileUTI.takeRetainedValue() as String
  609. return [fileUTI: data]
  610. }
  611. }