NCActionCenter.swift 35 KB

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