NCFunctionCenter.swift 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  1. //
  2. // NCFunctionCenter.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. @objc class NCFunctionCenter: NSObject, UIDocumentInteractionControllerDelegate, NCSelectDelegate {
  30. @objc public static let shared: NCFunctionCenter = {
  31. let instance = NCFunctionCenter()
  32. NotificationCenter.default.addObserver(instance, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadedFile), object: nil)
  33. NotificationCenter.default.addObserver(instance, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  34. return instance
  35. }()
  36. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  37. var viewerQuickLook: NCViewerQuickLook?
  38. var documentController: UIDocumentInteractionController?
  39. // MARK: - Download
  40. @objc func downloadedFile(_ notification: NSNotification) {
  41. guard let userInfo = notification.userInfo as NSDictionary?,
  42. let ocId = userInfo["ocId"] as? String,
  43. let selector = userInfo["selector"] as? String,
  44. let error = userInfo["error"] as? NKError,
  45. let account = userInfo["account"] as? String,
  46. account == appDelegate.account
  47. else { return }
  48. guard error == .success else {
  49. // File do not exists on server, remove in local
  50. if error.errorCode == NCGlobal.shared.errorResourceNotFound || error.errorCode == NCGlobal.shared.errorBadServerResponse {
  51. do {
  52. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(ocId))
  53. } catch { }
  54. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", ocId))
  55. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", ocId))
  56. } else {
  57. NCContentPresenter.shared.messageNotification("_download_file_", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  58. }
  59. return
  60. }
  61. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) else { return }
  62. switch selector {
  63. case NCGlobal.shared.selectorLoadFileQuickLook:
  64. let fileNamePath = NSTemporaryDirectory() + metadata.fileNameView
  65. CCUtility.copyFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView), toPath: fileNamePath)
  66. let viewerQuickLook = NCViewerQuickLook(with: URL(fileURLWithPath: fileNamePath), isEditingEnabled: true, metadata: metadata)
  67. self.appDelegate.window?.rootViewController?.present(viewerQuickLook, animated: true)
  68. case NCGlobal.shared.selectorLoadFileView:
  69. guard UIApplication.shared.applicationState == .active else { break }
  70. if metadata.contentType.contains("opendocument") && !NCUtility.shared.isRichDocument(metadata) {
  71. self.openDocumentController(metadata: metadata)
  72. } else if metadata.classFile == NKCommon.typeClassFile.compress.rawValue || metadata.classFile == NKCommon.typeClassFile.unknow.rawValue {
  73. self.openDocumentController(metadata: metadata)
  74. } else {
  75. if let viewController = self.appDelegate.activeViewController {
  76. let imageIcon = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  77. NCViewer.shared.view(viewController: viewController, metadata: metadata, metadatas: [metadata], imageIcon: imageIcon)
  78. }
  79. }
  80. case NCGlobal.shared.selectorOpenIn:
  81. if UIApplication.shared.applicationState == .active {
  82. self.openDocumentController(metadata: metadata)
  83. }
  84. case NCGlobal.shared.selectorLoadOffline:
  85. NCManageDatabase.shared.setLocalFile(ocId: metadata.ocId, offline: true)
  86. case NCGlobal.shared.selectorPrint:
  87. // waiting close menu
  88. // https://github.com/nextcloud/ios/issues/2278
  89. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  90. self.printDocument(metadata: metadata)
  91. }
  92. case NCGlobal.shared.selectorSaveAlbum:
  93. saveAlbum(metadata: metadata)
  94. case NCGlobal.shared.selectorSaveAlbumLivePhotoIMG, NCGlobal.shared.selectorSaveAlbumLivePhotoMOV:
  95. var metadata = metadata
  96. var metadataMOV = metadata
  97. guard let metadataTMP = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) else { break }
  98. if selector == NCGlobal.shared.selectorSaveAlbumLivePhotoIMG {
  99. metadataMOV = metadataTMP
  100. }
  101. if selector == NCGlobal.shared.selectorSaveAlbumLivePhotoMOV {
  102. metadata = metadataTMP
  103. }
  104. if CCUtility.fileProviderStorageExists(metadata) && CCUtility.fileProviderStorageExists(metadataMOV) {
  105. saveLivePhotoToDisk(metadata: metadata, metadataMov: metadataMOV)
  106. }
  107. case NCGlobal.shared.selectorSaveAsScan:
  108. saveAsScan(metadata: metadata)
  109. case NCGlobal.shared.selectorOpenDetail:
  110. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterOpenMediaDetail, userInfo: ["ocId": metadata.ocId])
  111. default:
  112. let applicationHandle = NCApplicationHandle()
  113. applicationHandle.downloadedFile(selector: selector, metadata: metadata)
  114. }
  115. }
  116. func setMetadataAvalableOffline(_ metadata: tableMetadata, isOffline: Bool) {
  117. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  118. if isOffline {
  119. if metadata.directory {
  120. NCManageDatabase.shared.setDirectory(serverUrl: serverUrl, offline: false, account: self.appDelegate.account)
  121. } else {
  122. NCManageDatabase.shared.setLocalFile(ocId: metadata.ocId, offline: false)
  123. }
  124. } else if metadata.directory {
  125. NCManageDatabase.shared.setDirectory(serverUrl: serverUrl, offline: true, account: self.appDelegate.account)
  126. NCOperationQueue.shared.synchronizationMetadata(metadata, selector: NCGlobal.shared.selectorDownloadAllFile)
  127. } else {
  128. NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorLoadOffline) { _, _ in }
  129. if let metadataLivePhoto = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  130. NCNetworking.shared.download(metadata: metadataLivePhoto, selector: NCGlobal.shared.selectorLoadOffline) { _, _ in }
  131. }
  132. }
  133. }
  134. // MARK: - Upload
  135. @objc func uploadedFile(_ notification: NSNotification) {
  136. guard let userInfo = notification.userInfo as NSDictionary?,
  137. let error = userInfo["error"] as? NKError,
  138. let account = userInfo["account"] as? String,
  139. account == appDelegate.account
  140. else { return }
  141. if error != .success, error.errorCode != NSURLErrorCancelled, error.errorCode != NCGlobal.shared.errorRequestExplicityCancelled {
  142. NCContentPresenter.shared.messageNotification("_upload_file_", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
  143. }
  144. }
  145. // MARK: -
  146. func openShare(viewController: UIViewController, metadata: tableMetadata, indexPage: NCGlobal.NCSharePagingIndex) {
  147. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  148. NCActivityIndicator.shared.start(backgroundView: viewController.view)
  149. NCNetworking.shared.readFile(serverUrlFileName: serverUrlFileName, queue: .main) { account, metadata, error in
  150. NCActivityIndicator.shared.stop()
  151. if let metadata = metadata, error == .success {
  152. let shareNavigationController = UIStoryboard(name: "NCShare", bundle: nil).instantiateInitialViewController() as! UINavigationController
  153. let shareViewController = shareNavigationController.topViewController as! NCSharePaging
  154. shareViewController.metadata = metadata
  155. shareViewController.indexPage = indexPage
  156. shareNavigationController.modalPresentationStyle = .formSheet
  157. viewController.present(shareNavigationController, animated: true, completion: nil)
  158. }
  159. }
  160. }
  161. // MARK: -
  162. func openDownload(metadata: tableMetadata, selector: String) {
  163. if CCUtility.fileProviderStorageExists(metadata) {
  164. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadedFile, userInfo: ["ocId": metadata.ocId, "selector": selector, "error": NKError(), "account": metadata.account])
  165. } else {
  166. NCNetworking.shared.download(metadata: metadata, selector: selector) { _, _ in }
  167. }
  168. }
  169. // MARK: - Open in ...
  170. func openDocumentController(metadata: tableMetadata) {
  171. guard let mainTabBar = self.appDelegate.mainTabBar else { return }
  172. let fileURL = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  173. documentController = UIDocumentInteractionController(url: fileURL)
  174. documentController?.presentOptionsMenu(from: mainTabBar.menuRect, in: mainTabBar, animated: true)
  175. }
  176. func openActivityViewController(selectedMetadata: [tableMetadata]) {
  177. let metadatas = selectedMetadata.filter({ !$0.directory })
  178. var items: [URL] = []
  179. var downloadMetadata: [(tableMetadata, URL)] = []
  180. for metadata in metadatas {
  181. let fileURL = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  182. if CCUtility.fileProviderStorageExists(metadata) { items.append(fileURL) }
  183. else { downloadMetadata.append((metadata, fileURL)) }
  184. }
  185. let processor = ParallelWorker(n: 5, titleKey: "_downloading_", totalTasks: downloadMetadata.count, hudView: self.appDelegate.window?.rootViewController?.view)
  186. for (metadata, url) in downloadMetadata {
  187. processor.execute { completion in
  188. NCNetworking.shared.download(metadata: metadata, selector: "", completion: { _, _ in
  189. if CCUtility.fileProviderStorageExists(metadata) { items.append(url) }
  190. completion()
  191. })
  192. }
  193. }
  194. processor.completeWork {
  195. guard !items.isEmpty, let mainTabBar = self.appDelegate.mainTabBar else { return }
  196. let activityViewController = UIActivityViewController(activityItems: items, applicationActivities: nil)
  197. activityViewController.popoverPresentationController?.permittedArrowDirections = .any
  198. activityViewController.popoverPresentationController?.sourceView = mainTabBar
  199. activityViewController.popoverPresentationController?.sourceRect = mainTabBar.menuRect
  200. self.appDelegate.window?.rootViewController?.present(activityViewController, animated: true)
  201. }
  202. }
  203. // MARK: - Save as scan
  204. func saveAsScan(metadata: tableMetadata) {
  205. let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  206. 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)!
  207. let fileNamePathDestination = CCUtility.getDirectoryScan() + "/" + fileNameDestination
  208. NCUtilityFileSystem.shared.copyFile(atPath: fileNamePath, toPath: fileNamePathDestination)
  209. let storyboard = UIStoryboard(name: "NCScan", bundle: nil)
  210. let navigationController = storyboard.instantiateInitialViewController()!
  211. navigationController.modalPresentationStyle = UIModalPresentationStyle.pageSheet
  212. appDelegate.window?.rootViewController?.present(navigationController, animated: true, completion: nil)
  213. }
  214. // MARK: - Print
  215. func printDocument(metadata: tableMetadata) {
  216. let fileNameURL = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!)
  217. let printController = UIPrintInteractionController.shared
  218. let printInfo = UIPrintInfo(dictionary: nil)
  219. printInfo.jobName = fileNameURL.lastPathComponent
  220. printInfo.outputType = metadata.classFile == NKCommon.typeClassFile.image.rawValue ? .photo : .general
  221. printController.printInfo = printInfo
  222. printController.showsNumberOfCopies = true
  223. guard !UIPrintInteractionController.canPrint(fileNameURL) else {
  224. printController.printingItem = fileNameURL
  225. printController.present(animated: true)
  226. return
  227. }
  228. // can't print without data
  229. guard let data = try? Data(contentsOf: fileNameURL) else { return }
  230. if let svg = SVGKImage(data: data) {
  231. printController.printingItem = svg.uiImage
  232. printController.present(animated: true)
  233. return
  234. }
  235. guard let text = String(data: data, encoding: .utf8) else { return }
  236. let formatter = UISimpleTextPrintFormatter(text: text)
  237. formatter.perPageContentInsets.top = 72
  238. formatter.perPageContentInsets.bottom = 72
  239. formatter.perPageContentInsets.left = 72
  240. formatter.perPageContentInsets.right = 72
  241. printController.printFormatter = formatter
  242. printController.present(animated: true)
  243. }
  244. // MARK: - Save photo
  245. func saveAlbum(metadata: tableMetadata) {
  246. let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  247. NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: appDelegate.mainTabBar?.window?.rootViewController) { hasPermission in
  248. guard hasPermission else {
  249. let error = NKError(errorCode: NCGlobal.shared.errorFileNotSaved, errorDescription: "_access_photo_not_enabled_msg_")
  250. return NCContentPresenter.shared.messageNotification("_access_photo_not_enabled_", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error)
  251. }
  252. let errorSave = NKError(errorCode: NCGlobal.shared.errorFileNotSaved, errorDescription: "_file_not_saved_cameraroll_")
  253. do {
  254. if metadata.classFile == NKCommon.typeClassFile.image.rawValue {
  255. let data = try Data(contentsOf: URL(fileURLWithPath: fileNamePath))
  256. PHPhotoLibrary.shared().performChanges({
  257. let assetRequest = PHAssetCreationRequest.forAsset()
  258. assetRequest.addResource(with: .photo, data: data, options: nil)
  259. }) { (success, error) in
  260. if !success {
  261. NCContentPresenter.shared.messageNotification("_save_selected_files_", error: errorSave, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error)
  262. }
  263. }
  264. } else if metadata.classFile == NKCommon.typeClassFile.video.rawValue {
  265. PHPhotoLibrary.shared().performChanges({
  266. PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: fileNamePath))
  267. }) { (success, error) in
  268. if !success {
  269. NCContentPresenter.shared.messageNotification("_save_selected_files_", error: errorSave, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error)
  270. }
  271. }
  272. } else {
  273. NCContentPresenter.shared.messageNotification("_save_selected_files_", error: errorSave, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error)
  274. return
  275. }
  276. } catch {
  277. NCContentPresenter.shared.messageNotification("_save_selected_files_", error: errorSave, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error)
  278. }
  279. }
  280. }
  281. func saveLivePhoto(metadata: tableMetadata, metadataMOV: tableMetadata) {
  282. if !CCUtility.fileProviderStorageExists(metadata) {
  283. NCOperationQueue.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorSaveAlbumLivePhotoIMG)
  284. }
  285. if !CCUtility.fileProviderStorageExists(metadataMOV) {
  286. NCOperationQueue.shared.download(metadata: metadataMOV, selector: NCGlobal.shared.selectorSaveAlbumLivePhotoMOV)
  287. }
  288. if CCUtility.fileProviderStorageExists(metadata) && CCUtility.fileProviderStorageExists(metadataMOV) {
  289. saveLivePhotoToDisk(metadata: metadata, metadataMov: metadataMOV)
  290. }
  291. }
  292. func saveLivePhotoToDisk(metadata: tableMetadata, metadataMov: tableMetadata) {
  293. let fileNameImage = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!)
  294. let fileNameMov = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadataMov.ocId, fileNameView: metadataMov.fileNameView)!)
  295. let hud = JGProgressHUD()
  296. hud.indicatorView = JGProgressHUDRingIndicatorView()
  297. if let indicatorView = hud.indicatorView as? JGProgressHUDRingIndicatorView {
  298. indicatorView.ringWidth = 1.5
  299. }
  300. hud.textLabel.text = NSLocalizedString("_saving_", comment: "")
  301. hud.show(in: (appDelegate.window?.rootViewController?.view)!)
  302. NCLivePhoto.generate(from: fileNameImage, videoURL: fileNameMov, progress: { progress in
  303. hud.progress = Float(progress)
  304. }, completion: { _, resources in
  305. if resources != nil {
  306. NCLivePhoto.saveToLibrary(resources!) { result in
  307. DispatchQueue.main.async {
  308. if !result {
  309. hud.indicatorView = JGProgressHUDErrorIndicatorView()
  310. hud.textLabel.text = NSLocalizedString("_livephoto_save_error_", comment: "")
  311. } else {
  312. hud.indicatorView = JGProgressHUDSuccessIndicatorView()
  313. hud.textLabel.text = NSLocalizedString("_success_", comment: "")
  314. }
  315. hud.dismiss(afterDelay: 1)
  316. }
  317. }
  318. } else {
  319. hud.indicatorView = JGProgressHUDErrorIndicatorView()
  320. hud.textLabel.text = NSLocalizedString("_livephoto_save_error_", comment: "")
  321. hud.dismiss(afterDelay: 1)
  322. }
  323. })
  324. }
  325. // MARK: - Copy & Paste
  326. func copyPasteboard(pasteboardOcIds: [String], hudView: UIView) {
  327. var items = [[String: Any]]()
  328. let hud = JGProgressHUD()
  329. hud.textLabel.text = NSLocalizedString("_wait_", comment: "")
  330. hud.show(in: hudView)
  331. // getting file data can take some time and block the main queue
  332. DispatchQueue.global(qos: .userInitiated).async {
  333. var downloadMetadatas: [tableMetadata] = []
  334. for ocid in pasteboardOcIds {
  335. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocid) else { continue }
  336. if let pasteboardItem = metadata.toPasteBoardItem() { items.append(pasteboardItem) }
  337. else { downloadMetadatas.append(metadata) }
  338. }
  339. DispatchQueue.main.async(execute: hud.dismiss)
  340. // do 5 downloads in parallel to optimize efficiency
  341. let parallelizer = ParallelWorker(n: 5, titleKey: "_downloading_", totalTasks: downloadMetadatas.count, hudView: hudView)
  342. for metadata in downloadMetadatas {
  343. parallelizer.execute { completion in
  344. NCNetworking.shared.download(metadata: metadata, selector: "") { _, _ in completion() }
  345. }
  346. }
  347. parallelizer.completeWork {
  348. items.append(contentsOf: downloadMetadatas.compactMap({ $0.toPasteBoardItem() }))
  349. UIPasteboard.general.setItems(items, options: [:])
  350. }
  351. }
  352. }
  353. func pastePasteboard(serverUrl: String) {
  354. let parallelizer = ParallelWorker(n: 5, titleKey: "_uploading_", totalTasks: nil, hudView: appDelegate.window?.rootViewController?.view)
  355. func uploadPastePasteboard(fileName: String, serverUrlFileName: String, fileNameLocalPath: String, serverUrl: String, completion: @escaping () -> Void) {
  356. NextcloudKit.shared.upload(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath) { request in
  357. NCNetworking.shared.uploadRequest[fileNameLocalPath] = request
  358. } progressHandler: { progress in
  359. } completionHandler: { account, ocId, etag, _, _, _, afError, error in
  360. NCNetworking.shared.uploadRequest.removeValue(forKey: fileNameLocalPath)
  361. if error == .success && etag != nil && ocId != nil {
  362. let toPath = CCUtility.getDirectoryProviderStorageOcId(ocId!, fileNameView: fileName)!
  363. NCUtilityFileSystem.shared.moveFile(atPath: fileNameLocalPath, toPath: toPath)
  364. NCManageDatabase.shared.addLocalFile(account: account, etag: etag!, ocId: ocId!, fileName: fileName)
  365. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced, userInfo: ["serverUrl": serverUrl])
  366. } else if afError?.isExplicitlyCancelledError ?? false {
  367. print("cancel")
  368. } else {
  369. NCContentPresenter.shared.showError(error: error)
  370. }
  371. completion()
  372. }
  373. }
  374. for (index, items) in UIPasteboard.general.items.enumerated() {
  375. for item in items {
  376. let results = NKCommon.shared.getFileProperties(inUTI: item.key as CFString)
  377. guard !results.ext.isEmpty,
  378. let data = UIPasteboard.general.data(forPasteboardType: item.key, inItemSet: IndexSet([index]))?.first
  379. else { continue }
  380. let fileName = results.name + "_" + CCUtility.getIncrementalNumber() + "." + results.ext
  381. let serverUrlFileName = serverUrl + "/" + fileName
  382. let ocIdUpload = UUID().uuidString
  383. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(ocIdUpload, fileNameView: fileName)!
  384. do { try data.write(to: URL(fileURLWithPath: fileNameLocalPath)) } catch { continue }
  385. parallelizer.execute { completion in
  386. uploadPastePasteboard(fileName: fileName, serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, serverUrl: serverUrl, completion: completion)
  387. }
  388. }
  389. }
  390. parallelizer.completeWork()
  391. }
  392. // MARK: -
  393. func openFileViewInFolder(serverUrl: String, fileNameBlink: String?, fileNameOpen: String?) {
  394. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  395. var topNavigationController: UINavigationController?
  396. var pushServerUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: self.appDelegate.urlBase, userId: self.appDelegate.userId)
  397. guard var mostViewController = self.appDelegate.window?.rootViewController?.topMostViewController() else { return }
  398. if mostViewController.isModal {
  399. mostViewController.dismiss(animated: false)
  400. if let viewController = self.appDelegate.window?.rootViewController?.topMostViewController() {
  401. mostViewController = viewController
  402. }
  403. }
  404. mostViewController.navigationController?.popToRootViewController(animated: false)
  405. if let tabBarController = self.appDelegate.window?.rootViewController as? UITabBarController {
  406. tabBarController.selectedIndex = 0
  407. if let navigationController = tabBarController.viewControllers?.first as? UINavigationController {
  408. navigationController.popToRootViewController(animated: false)
  409. topNavigationController = navigationController
  410. }
  411. }
  412. if pushServerUrl == serverUrl {
  413. let viewController = topNavigationController?.topViewController as? NCFiles
  414. viewController?.blinkCell(fileName: fileNameBlink)
  415. viewController?.openFile(fileName: fileNameOpen)
  416. return
  417. }
  418. guard let topNavigationController = topNavigationController else { return }
  419. let diffDirectory = serverUrl.replacingOccurrences(of: pushServerUrl, with: "")
  420. var subDirs = diffDirectory.split(separator: "/")
  421. while pushServerUrl != serverUrl, subDirs.count > 0 {
  422. guard let dir = subDirs.first, let viewController = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles else { return }
  423. pushServerUrl = pushServerUrl + "/" + dir
  424. viewController.serverUrl = pushServerUrl
  425. viewController.isRoot = false
  426. viewController.titleCurrentFolder = String(dir)
  427. if pushServerUrl == serverUrl {
  428. viewController.fileNameBlink = fileNameBlink
  429. viewController.fileNameOpen = fileNameOpen
  430. }
  431. self.appDelegate.listFilesVC[serverUrl] = viewController
  432. viewController.navigationItem.backButtonTitle = viewController.titleCurrentFolder
  433. topNavigationController.pushViewController(viewController, animated: false)
  434. subDirs.remove(at: 0)
  435. }
  436. }
  437. }
  438. // MARK: - NCSelect + Delegate
  439. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool) {
  440. if serverUrl != nil && items.count > 0 {
  441. if copy {
  442. for metadata in items as! [tableMetadata] {
  443. NCOperationQueue.shared.copyMove(metadata: metadata, serverUrl: serverUrl!, overwrite: overwrite, move: false)
  444. }
  445. } else if move {
  446. for metadata in items as! [tableMetadata] {
  447. NCOperationQueue.shared.copyMove(metadata: metadata, serverUrl: serverUrl!, overwrite: overwrite, move: true)
  448. }
  449. }
  450. }
  451. }
  452. func openSelectView(items: [tableMetadata]) {
  453. let navigationController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateInitialViewController() as! UINavigationController
  454. let topViewController = navigationController.topViewController as! NCSelect
  455. var listViewController = [NCSelect]()
  456. var copyItems: [tableMetadata] = []
  457. for item in items {
  458. copyItems.append(item)
  459. }
  460. let homeUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId)
  461. var serverUrl = copyItems[0].serverUrl
  462. // Setup view controllers such that the current view is of the same directory the items to be copied are in
  463. while true {
  464. // If not in the topmost directory, create a new view controller and set correct title.
  465. // If in the topmost directory, use the default view controller as the base.
  466. var viewController: NCSelect?
  467. if serverUrl != homeUrl {
  468. viewController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateViewController(withIdentifier: "NCSelect.storyboard") as? NCSelect
  469. if viewController == nil {
  470. return
  471. }
  472. viewController!.titleCurrentFolder = (serverUrl as NSString).lastPathComponent
  473. } else {
  474. viewController = topViewController
  475. }
  476. guard let vc = viewController else { return }
  477. vc.delegate = self
  478. vc.typeOfCommandView = .copyMove
  479. vc.items = copyItems
  480. vc.serverUrl = serverUrl
  481. vc.navigationItem.backButtonTitle = vc.titleCurrentFolder
  482. listViewController.insert(vc, at: 0)
  483. if serverUrl != homeUrl {
  484. if let path = NCUtilityFileSystem.shared.deleteLastPath(serverUrlPath: serverUrl) {
  485. serverUrl = path
  486. }
  487. } else {
  488. break
  489. }
  490. }
  491. navigationController.setViewControllers(listViewController, animated: false)
  492. navigationController.modalPresentationStyle = .formSheet
  493. appDelegate.window?.rootViewController?.present(navigationController, animated: true, completion: nil)
  494. }
  495. // MARK: - Context Menu Configuration
  496. func contextMenuConfiguration(ocId: String, viewController: UIViewController, enableDeleteLocal: Bool, enableViewInFolder: Bool, image: UIImage?) -> UIMenu {
  497. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) else {
  498. return UIMenu()
  499. }
  500. let isDirectoryE2EE = NCUtility.shared.isDirectoryE2EE(metadata: metadata)
  501. var titleDeleteConfirmFile = NSLocalizedString("_delete_file_", comment: "")
  502. if metadata.directory { titleDeleteConfirmFile = NSLocalizedString("_delete_folder_", comment: "") }
  503. var titleSave: String = NSLocalizedString("_save_selected_files_", comment: "")
  504. let metadataMOV = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata)
  505. if metadataMOV != nil {
  506. titleSave = NSLocalizedString("_livephoto_save_", comment: "")
  507. }
  508. let titleFavorite = metadata.favorite ? NSLocalizedString("_remove_favorites_", comment: "") : NSLocalizedString("_add_favorites_", comment: "")
  509. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  510. var isOffline = false
  511. if metadata.directory {
  512. if let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, serverUrl)) {
  513. isOffline = directory.offline
  514. }
  515. } else {
  516. if let localFile = NCManageDatabase.shared.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId)) {
  517. isOffline = localFile.offline
  518. }
  519. }
  520. let titleOffline = isOffline ? NSLocalizedString("_remove_available_offline_", comment: "") : NSLocalizedString("_set_available_offline_", comment: "")
  521. let titleLock = metadata.lock ? NSLocalizedString("_unlock_file_", comment: "") : NSLocalizedString("_lock_file_", comment: "")
  522. let iconLock = metadata.lock ? "lock.open" : "lock"
  523. let copy = UIAction(title: NSLocalizedString("_copy_file_", comment: ""), image: UIImage(systemName: "doc.on.doc")) { _ in
  524. self.copyPasteboard(pasteboardOcIds: [metadata.ocId], hudView: viewController.view)
  525. }
  526. let copyPath = UIAction(title: NSLocalizedString("_copy_path_", comment: ""), image: UIImage(systemName: "doc.on.clipboard")) { _ in
  527. let board = UIPasteboard.general
  528. board.string = NCUtilityFileSystem.shared.getPath(path: metadata.path, user: metadata.user, fileName: metadata.fileName)
  529. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_copied_path_")
  530. NCContentPresenter.shared.showInfo(error: error)
  531. }
  532. let detail = UIAction(title: NSLocalizedString("_details_", comment: ""), image: UIImage(systemName: "info")) { _ in
  533. self.openShare(viewController: viewController, metadata: metadata, indexPage: .activity)
  534. }
  535. let offline = UIAction(title: titleOffline, image: UIImage(systemName: "tray.and.arrow.down")) { _ in
  536. self.setMetadataAvalableOffline(metadata, isOffline: isOffline)
  537. if let viewController = viewController as? NCCollectionViewCommon {
  538. viewController.reloadDataSource()
  539. }
  540. }
  541. let lockUnlock = UIAction(title: titleLock, image: UIImage(systemName: iconLock)) { _ in
  542. NCNetworking.shared.lockUnlockFile(metadata, shoulLock: !metadata.lock)
  543. }
  544. let save = UIAction(title: titleSave, image: UIImage(systemName: "square.and.arrow.down")) { _ in
  545. if metadataMOV != nil {
  546. self.saveLivePhoto(metadata: metadata, metadataMOV: metadataMOV!)
  547. } else {
  548. if CCUtility.fileProviderStorageExists(metadata) {
  549. self.saveAlbum(metadata: metadata)
  550. } else {
  551. NCOperationQueue.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorSaveAlbum)
  552. }
  553. }
  554. }
  555. let viewInFolder = UIAction(title: NSLocalizedString("_view_in_folder_", comment: ""), image: UIImage(systemName: "arrow.forward.square")) { _ in
  556. self.openFileViewInFolder(serverUrl: metadata.serverUrl, fileNameBlink: metadata.fileName, fileNameOpen: nil)
  557. }
  558. let openIn = UIAction(title: NSLocalizedString("_open_in_", comment: ""), image: UIImage(systemName: "square.and.arrow.up") ) { _ in
  559. self.openDownload(metadata: metadata, selector: NCGlobal.shared.selectorOpenIn)
  560. }
  561. let print = UIAction(title: NSLocalizedString("_print_", comment: ""), image: UIImage(systemName: "printer") ) { _ in
  562. self.openDownload(metadata: metadata, selector: NCGlobal.shared.selectorPrint)
  563. }
  564. let modify = UIAction(title: NSLocalizedString("_modify_", comment: ""), image: UIImage(systemName: "pencil.tip.crop.circle")) { _ in
  565. self.openDownload(metadata: metadata, selector: NCGlobal.shared.selectorLoadFileQuickLook)
  566. }
  567. let saveAsScan = UIAction(title: NSLocalizedString("_save_as_scan_", comment: ""), image: UIImage(systemName: "viewfinder.circle")) { _ in
  568. self.openDownload(metadata: metadata, selector: NCGlobal.shared.selectorSaveAsScan)
  569. }
  570. // let open = UIMenu(title: NSLocalizedString("_open_", comment: ""), image: UIImage(systemName: "square.and.arrow.up"), children: [openIn, openQuickLook])
  571. let moveCopy = UIAction(title: NSLocalizedString("_move_or_copy_", comment: ""), image: UIImage(systemName: "arrow.up.right.square")) { _ in
  572. self.openSelectView(items: [metadata])
  573. }
  574. let rename = UIAction(title: NSLocalizedString("_rename_", comment: ""), image: UIImage(systemName: "pencil")) { _ in
  575. if let vcRename = UIStoryboard(name: "NCRenameFile", bundle: nil).instantiateInitialViewController() as? NCRenameFile {
  576. vcRename.metadata = metadata
  577. vcRename.imagePreview = image
  578. let popup = NCPopupViewController(contentController: vcRename, popupWidth: vcRename.width, popupHeight: vcRename.height)
  579. viewController.present(popup, animated: true)
  580. }
  581. }
  582. let favorite = UIAction(title: titleFavorite, image: NCUtility.shared.loadImage(named: "star.fill", color: NCBrandColor.shared.yellowFavorite)) { _ in
  583. NCNetworking.shared.favoriteMetadata(metadata) { error in
  584. if error != .success {
  585. NCContentPresenter.shared.showError(error: error)
  586. }
  587. }
  588. }
  589. let deleteConfirmFile = UIAction(title: titleDeleteConfirmFile, image: UIImage(systemName: "trash"), attributes: .destructive) { _ in
  590. NCNetworking.shared.deleteMetadata(metadata, onlyLocalCache: false) { error in
  591. if error != .success {
  592. NCContentPresenter.shared.showError(error: error)
  593. }
  594. }
  595. }
  596. let deleteConfirmLocal = UIAction(title: NSLocalizedString("_remove_local_file_", comment: ""), image: UIImage(systemName: "trash"), attributes: .destructive) { _ in
  597. NCNetworking.shared.deleteMetadata(metadata, onlyLocalCache: true) { _ in
  598. }
  599. }
  600. var delete = UIMenu(title: NSLocalizedString("_delete_file_", comment: ""), image: UIImage(systemName: "trash"), options: .destructive, children: [deleteConfirmLocal, deleteConfirmFile])
  601. if !enableDeleteLocal {
  602. delete = UIMenu(title: NSLocalizedString("_delete_file_", comment: ""), image: UIImage(systemName: "trash"), options: .destructive, children: [deleteConfirmFile])
  603. }
  604. if metadata.directory {
  605. delete = UIMenu(title: NSLocalizedString("_delete_folder_", comment: ""), image: UIImage(systemName: "trash"), options: .destructive, children: [deleteConfirmFile])
  606. }
  607. // ------ MENU -----
  608. // DIR
  609. guard !metadata.directory else {
  610. let submenu = UIMenu(title: "", options: .displayInline, children: [favorite, offline, rename, moveCopy, copyPath, delete])
  611. guard appDelegate.disableSharesView == false else { return submenu }
  612. return UIMenu(title: "", children: [detail, submenu])
  613. }
  614. // FILE
  615. var children: [UIMenuElement] = [offline, openIn, moveCopy, copy, copyPath]
  616. if !metadata.lock {
  617. // Workaround: PROPPATCH doesn't work (favorite)
  618. // https://github.com/nextcloud/files_lock/issues/68
  619. children.insert(favorite, at: 0)
  620. children.append(delete)
  621. children.insert(rename, at: 3)
  622. } else if enableDeleteLocal {
  623. children.append(deleteConfirmLocal)
  624. }
  625. if NCManageDatabase.shared.getCapabilitiesServerInt(account: appDelegate.account, elements: NCElementsJSON.shared.capabilitiesFilesLockVersion) >= 1, metadata.canUnlock(as: appDelegate.userId) {
  626. children.insert(lockUnlock, at: metadata.lock ? 0 : 1)
  627. }
  628. if (metadata.contentType != "image/svg+xml") && (metadata.classFile == NKCommon.typeClassFile.image.rawValue || metadata.classFile == NKCommon.typeClassFile.video.rawValue) {
  629. children.insert(save, at: 2)
  630. }
  631. if (metadata.contentType != "image/svg+xml") && (metadata.classFile == NKCommon.typeClassFile.image.rawValue) {
  632. children.insert(saveAsScan, at: 2)
  633. }
  634. if (metadata.contentType != "image/svg+xml") && (metadata.classFile == NKCommon.typeClassFile.image.rawValue || metadata.contentType == "application/pdf" || metadata.contentType == "com.adobe.pdf") {
  635. children.insert(print, at: 2)
  636. }
  637. if enableViewInFolder {
  638. children.insert(viewInFolder, at: children.count - 1)
  639. }
  640. if (!isDirectoryE2EE && metadata.contentType != "image/gif" && metadata.contentType != "image/svg+xml") && (metadata.contentType == "com.adobe.pdf" || metadata.contentType == "application/pdf" || metadata.classFile == NKCommon.typeClassFile.image.rawValue) {
  641. children.insert(modify, at: children.count - 1)
  642. }
  643. let submenu = UIMenu(title: "", options: .displayInline, children: children)
  644. guard appDelegate.disableSharesView == false else { return submenu }
  645. return UIMenu(title: "", children: [detail, submenu])
  646. }
  647. }
  648. fileprivate extension tableMetadata {
  649. func toPasteBoardItem() -> [String: Any]? {
  650. // Get Data
  651. let fileUrl = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView))
  652. guard CCUtility.fileProviderStorageExists(self),
  653. let data = try? Data(contentsOf: fileUrl),
  654. let unmanagedFileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension as CFString, nil)
  655. else { return nil }
  656. // Pasteboard item
  657. let fileUTI = unmanagedFileUTI.takeRetainedValue() as String
  658. return [fileUTI: data]
  659. }
  660. }