NCFunctionCenter.swift 39 KB

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