NCActionCenter.swift 35 KB

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