NCFunctionCenter.swift 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  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. @objc class NCFunctionCenter: NSObject, UIDocumentInteractionControllerDelegate, NCSelectDelegate {
  26. @objc public static let shared: NCFunctionCenter = {
  27. let instance = NCFunctionCenter()
  28. NotificationCenter.default.addObserver(instance, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadedFile), object: nil)
  29. NotificationCenter.default.addObserver(instance, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  30. return instance
  31. }()
  32. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  33. var viewerQuickLook: NCViewerQuickLook?
  34. var documentController: UIDocumentInteractionController?
  35. //MARK: - Download
  36. @objc func downloadedFile(_ notification: NSNotification) {
  37. if let userInfo = notification.userInfo as NSDictionary? {
  38. if let ocId = userInfo["ocId"] as? String, let selector = userInfo["selector"] as? String, let errorCode = userInfo["errorCode"] as? Int, let errorDescription = userInfo["errorDescription"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  39. if metadata.account != appDelegate.account { return }
  40. if errorCode == 0 {
  41. let fileURL = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  42. documentController = UIDocumentInteractionController(url: fileURL)
  43. documentController?.delegate = self
  44. switch selector {
  45. case NCGlobal.shared.selectorLoadFileQuickLook:
  46. let fileNamePath = NSTemporaryDirectory() + metadata.fileNameView
  47. CCUtility.copyFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView), toPath: fileNamePath)
  48. viewerQuickLook = NCViewerQuickLook.init()
  49. viewerQuickLook?.quickLook(url: URL(fileURLWithPath: fileNamePath))
  50. case NCGlobal.shared.selectorLoadFileView:
  51. if UIApplication.shared.applicationState == UIApplication.State.active {
  52. if metadata.contentType.contains("opendocument") && !NCUtility.shared.isRichDocument(metadata) {
  53. if let view = appDelegate.window?.rootViewController?.view {
  54. documentController?.presentOptionsMenu(from: CGRect.zero, in: view, animated: true)
  55. }
  56. } else if metadata.typeFile == NCGlobal.shared.metadataTypeFileCompress || metadata.typeFile == NCGlobal.shared.metadataTypeFileUnknown {
  57. if let view = appDelegate.window?.rootViewController?.view {
  58. documentController?.presentOptionsMenu(from: CGRect.zero, in: view, animated: true)
  59. }
  60. } else if metadata.typeFile == NCGlobal.shared.metadataTypeFileImagemeter {
  61. if let view = appDelegate.window?.rootViewController?.view {
  62. documentController?.presentOptionsMenu(from: CGRect.zero, in: view, animated: true)
  63. }
  64. } else {
  65. if let viewController = self.appDelegate.activeViewController {
  66. let imageIcon = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  67. NCViewer.shared.view(viewController: viewController, metadata: metadata, metadatas: [metadata], imageIcon: imageIcon)
  68. }
  69. }
  70. }
  71. case NCGlobal.shared.selectorOpenIn:
  72. if UIApplication.shared.applicationState == UIApplication.State.active {
  73. if let view = appDelegate.window?.rootViewController?.view {
  74. documentController?.presentOptionsMenu(from: CGRect.zero, in: view, animated: true)
  75. }
  76. }
  77. case NCGlobal.shared.selectorLoadCopy:
  78. copyPasteboard()
  79. case NCGlobal.shared.selectorLoadOffline:
  80. NCManageDatabase.shared.setLocalFile(ocId: metadata.ocId, offline: true)
  81. case NCGlobal.shared.selectorPrint:
  82. printDocument(metadata: metadata)
  83. case NCGlobal.shared.selectorSaveAlbum:
  84. saveAlbum(metadata: metadata)
  85. case NCGlobal.shared.selectorSaveBackground:
  86. saveBackground(metadata: metadata)
  87. case NCGlobal.shared.selectorSaveAlbumLivePhotoIMG, NCGlobal.shared.selectorSaveAlbumLivePhotoMOV:
  88. var metadata = metadata
  89. var metadataMOV = metadata
  90. guard let metadataTMP = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) else { break }
  91. if selector == NCGlobal.shared.selectorSaveAlbumLivePhotoIMG {
  92. metadataMOV = metadataTMP
  93. }
  94. if selector == NCGlobal.shared.selectorSaveAlbumLivePhotoMOV {
  95. metadata = metadataTMP
  96. }
  97. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) && CCUtility.fileProviderStorageExists(metadataMOV.ocId, fileNameView: metadataMOV.fileNameView) {
  98. saveLivePhotoToDisk(metadata: metadata, metadataMov: metadataMOV, progressView: nil, viewActivity: self.appDelegate.window?.rootViewController?.view)
  99. }
  100. default:
  101. break
  102. }
  103. } else {
  104. // File do not exists on server, remove in local
  105. if (errorCode == NCGlobal.shared.errorResourceNotFound || errorCode == NCGlobal.shared.errorBadServerResponse) {
  106. do {
  107. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  108. } catch { }
  109. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  110. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  111. } else {
  112. NCContentPresenter.shared.messageNotification("_download_file_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  113. }
  114. }
  115. }
  116. }
  117. }
  118. //MARK: - Upload
  119. @objc func uploadedFile(_ notification: NSNotification) {
  120. if let userInfo = notification.userInfo as NSDictionary? {
  121. 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) {
  122. if metadata.account == appDelegate.account {
  123. if errorCode != 0 {
  124. if errorCode != -999 && errorDescription != "" {
  125. NCContentPresenter.shared.messageNotification("_upload_file_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  126. }
  127. }
  128. }
  129. }
  130. }
  131. }
  132. // MARK: -
  133. func openShare(ViewController: UIViewController, metadata: tableMetadata, indexPage: Int) {
  134. let shareNavigationController = UIStoryboard(name: "NCShare", bundle: nil).instantiateInitialViewController() as! UINavigationController
  135. let shareViewController = shareNavigationController.topViewController as! NCSharePaging
  136. shareViewController.metadata = metadata
  137. shareViewController.indexPage = indexPage
  138. shareNavigationController.modalPresentationStyle = .formSheet
  139. ViewController.present(shareNavigationController, animated: true, completion: nil)
  140. }
  141. // MARK: -
  142. func openDownload(metadata: tableMetadata, selector: String) {
  143. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  144. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDownloadedFile, userInfo: ["ocId": metadata.ocId, "selector": selector, "errorCode": 0, "errorDescription": "" ])
  145. } else {
  146. NCNetworking.shared.download(metadata: metadata, selector: selector) { (_) in }
  147. }
  148. }
  149. // MARK: - Print
  150. func printDocument(metadata: tableMetadata) {
  151. let fileNameURL = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!)
  152. if UIPrintInteractionController.canPrint(fileNameURL) {
  153. let printInfo = UIPrintInfo(dictionary: nil)
  154. printInfo.jobName = fileNameURL.lastPathComponent
  155. printInfo.outputType = .photo
  156. let printController = UIPrintInteractionController.shared
  157. printController.printInfo = printInfo
  158. printController.showsNumberOfCopies = true
  159. printController.printingItem = fileNameURL
  160. printController.present(animated: true, completionHandler: nil)
  161. }
  162. }
  163. // MARK: - Save photo
  164. func saveAlbum(metadata: tableMetadata) {
  165. let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  166. let status = PHPhotoLibrary.authorizationStatus()
  167. if metadata.typeFile == NCGlobal.shared.metadataTypeFileImage && status == PHAuthorizationStatus.authorized {
  168. if let image = UIImage.init(contentsOfFile: fileNamePath) {
  169. UIImageWriteToSavedPhotosAlbum(image, self, #selector(SaveAlbum(_:didFinishSavingWithError:contextInfo:)), nil)
  170. } else {
  171. NCContentPresenter.shared.messageNotification("_save_selected_files_", description: "_file_not_saved_cameraroll_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorFileNotSaved)
  172. }
  173. } else if metadata.typeFile == NCGlobal.shared.metadataTypeFileVideo && status == PHAuthorizationStatus.authorized {
  174. if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(fileNamePath) {
  175. UISaveVideoAtPathToSavedPhotosAlbum(fileNamePath, self, #selector(SaveAlbum(_:didFinishSavingWithError:contextInfo:)), nil)
  176. } else {
  177. NCContentPresenter.shared.messageNotification("_save_selected_files_", description: "_file_not_saved_cameraroll_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorFileNotSaved)
  178. }
  179. } else if status != PHAuthorizationStatus.authorized {
  180. 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)
  181. }
  182. }
  183. @objc private func SaveAlbum(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
  184. if error != nil {
  185. NCContentPresenter.shared.messageNotification("_save_selected_files_", description: "_file_not_saved_cameraroll_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorFileNotSaved)
  186. }
  187. }
  188. func saveLivePhoto(metadata: tableMetadata, metadataMOV: tableMetadata) {
  189. if !CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  190. NCOperationQueue.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorSaveAlbumLivePhotoIMG)
  191. }
  192. if !CCUtility.fileProviderStorageExists(metadataMOV.ocId, fileNameView: metadataMOV.fileNameView) {
  193. NCOperationQueue.shared.download(metadata: metadataMOV, selector: NCGlobal.shared.selectorSaveAlbumLivePhotoMOV)
  194. }
  195. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) && CCUtility.fileProviderStorageExists(metadataMOV.ocId, fileNameView: metadataMOV.fileNameView) {
  196. saveLivePhotoToDisk(metadata: metadata, metadataMov: metadataMOV, progressView: nil, viewActivity: self.appDelegate.window?.rootViewController?.view)
  197. }
  198. }
  199. func saveLivePhotoToDisk(metadata: tableMetadata, metadataMov: tableMetadata, progressView: UIProgressView?, viewActivity: UIView?) {
  200. let fileNameImage = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!)
  201. let fileNameMov = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadataMov.ocId, fileNameView: metadataMov.fileNameView)!)
  202. if let view = viewActivity {
  203. NCUtility.shared.startActivityIndicator(backgroundView: view, blurEffect: true)
  204. }
  205. NCLivePhoto.generate(from: fileNameImage, videoURL: fileNameMov, progress: { progress in
  206. DispatchQueue.main.async {
  207. progressView?.progress = Float(progress)
  208. }
  209. }, completion: { livePhoto, resources in
  210. NCUtility.shared.stopActivityIndicator()
  211. progressView?.progress = 0
  212. if resources != nil {
  213. NCLivePhoto.saveToLibrary(resources!) { (result) in
  214. if !result {
  215. NCContentPresenter.shared.messageNotification("_error_", description: "_livephoto_save_error_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorInternalError)
  216. }
  217. }
  218. } else {
  219. NCContentPresenter.shared.messageNotification("_error_", description: "_livephoto_save_error_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorInternalError)
  220. }
  221. })
  222. }
  223. func saveBackground(metadata: tableMetadata) {
  224. let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  225. let destination = CCUtility.getDirectoryGroup().appendingPathComponent(NCGlobal.shared.appBackground).path + "/" + metadata.fileNameView
  226. if NCUtilityFileSystem.shared.copyFile(atPath: fileNamePath, toPath: destination) {
  227. if appDelegate.activeViewController is NCCollectionViewCommon {
  228. let viewController: NCCollectionViewCommon = appDelegate.activeViewController as! NCCollectionViewCommon
  229. let layoutKey = viewController.layoutKey
  230. let serverUrl = viewController.serverUrl
  231. if serverUrl == metadata.serverUrl {
  232. NCUtility.shared.setBackgroundImageForView(key: layoutKey, serverUrl: serverUrl, imageBackgroud: metadata.fileNameView, imageBackgroudContentMode: "")
  233. viewController.changeTheming()
  234. }
  235. }
  236. }
  237. }
  238. // MARK: - Copy & Paste
  239. func copyPasteboard() {
  240. var metadatas: [tableMetadata] = []
  241. var items = [[String : Any]]()
  242. for ocId in appDelegate.pasteboardOcIds {
  243. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  244. metadatas.append(metadata)
  245. }
  246. }
  247. for metadata in metadatas {
  248. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  249. do {
  250. // Get Data
  251. let data = try Data.init(contentsOf: URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)))
  252. // Pasteboard item
  253. if let unmanagedFileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (metadata.fileNameView as NSString).pathExtension as CFString, nil) {
  254. let fileUTI = unmanagedFileUTI.takeRetainedValue() as String
  255. items.append([fileUTI:data])
  256. }
  257. } catch {
  258. print("error")
  259. }
  260. } else {
  261. NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorLoadCopy) { (_) in }
  262. }
  263. }
  264. UIPasteboard.general.setItems(items, options: [:])
  265. }
  266. func pastePasteboard(serverUrl: String) {
  267. for (index, items) in UIPasteboard.general.items.enumerated() {
  268. for item in items {
  269. let pasteboardType = item.key
  270. if let data = UIPasteboard.general.data(forPasteboardType: pasteboardType, inItemSet: IndexSet([index]))?.first {
  271. let results = NCCommunicationCommon.shared.getDescriptionFile(inUTI: pasteboardType as CFString)
  272. if results.resultTypeFile != NCCommunicationCommon.typeFile.unknow.rawValue {
  273. uploadPasteFile(fileName: results.resultFilename, ext: results.resultExtension, contentType: pasteboardType, serverUrl: serverUrl, data: data)
  274. }
  275. }
  276. }
  277. }
  278. }
  279. private func uploadPasteFile(fileName: String, ext: String, contentType: String, serverUrl: String, data: Data) {
  280. do {
  281. let fileNameView = fileName + "_" + CCUtility.getIncrementalNumber() + "." + ext
  282. let ocId = UUID().uuidString
  283. let filePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView)!
  284. try data.write(to: URL(fileURLWithPath: filePath))
  285. let metadataForUpload = NCManageDatabase.shared.createMetadata(account: appDelegate.account, fileName: fileNameView, fileNameView: fileNameView, ocId: ocId, serverUrl: serverUrl, urlBase: appDelegate.urlBase, url: "", contentType: contentType, livePhoto: false, chunk: false)
  286. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
  287. metadataForUpload.sessionSelector = NCGlobal.shared.selectorUploadFile
  288. metadataForUpload.size = NCUtilityFileSystem.shared.getFileSize(filePath: filePath)
  289. metadataForUpload.status = NCGlobal.shared.metadataStatusWaitUpload
  290. appDelegate.networkingProcessUpload?.createProcessUploads(metadatas: [metadataForUpload])
  291. } catch { }
  292. }
  293. // MARK: -
  294. func openFileViewInFolder(serverUrl: String, fileName: String) {
  295. let viewController = UIStoryboard(name: "NCFileViewInFolder", bundle: nil).instantiateInitialViewController() as! NCFileViewInFolder
  296. let navigationController = UINavigationController.init(rootViewController: viewController)
  297. let topViewController = viewController
  298. var listViewController = [NCFileViewInFolder]()
  299. var serverUrl = serverUrl
  300. let homeUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account)
  301. while true {
  302. var viewController: NCFileViewInFolder?
  303. if serverUrl != homeUrl {
  304. viewController = UIStoryboard(name: "NCFileViewInFolder", bundle: nil).instantiateInitialViewController() as? NCFileViewInFolder
  305. if viewController == nil {
  306. return
  307. }
  308. viewController!.titleCurrentFolder = (serverUrl as NSString).lastPathComponent
  309. } else {
  310. viewController = topViewController
  311. }
  312. guard let vc = viewController else { return }
  313. vc.serverUrl = serverUrl
  314. vc.fileName = fileName
  315. vc.navigationItem.backButtonTitle = vc.titleCurrentFolder
  316. listViewController.insert(vc, at: 0)
  317. if serverUrl != homeUrl {
  318. serverUrl = NCUtilityFileSystem.shared.deletingLastPathComponent(serverUrl: serverUrl, urlBase: appDelegate.urlBase, account: appDelegate.account)
  319. } else {
  320. break
  321. }
  322. }
  323. navigationController.setViewControllers(listViewController, animated: false)
  324. navigationController.modalPresentationStyle = .formSheet
  325. appDelegate.window?.rootViewController?.present(navigationController, animated: true, completion: nil)
  326. }
  327. // MARK: - NCSelect + Delegate
  328. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool) {
  329. if (serverUrl != nil && items.count > 0) {
  330. if copy {
  331. for metadata in items as! [tableMetadata] {
  332. NCOperationQueue.shared.copyMove(metadata: metadata, serverUrl: serverUrl!, overwrite: overwrite, move: false)
  333. }
  334. } else if move {
  335. for metadata in items as! [tableMetadata] {
  336. NCOperationQueue.shared.copyMove(metadata: metadata, serverUrl: serverUrl!, overwrite: overwrite, move: true)
  337. }
  338. }
  339. }
  340. }
  341. func openSelectView(items: [Any], viewController: UIViewController) {
  342. let navigationController = UIStoryboard.init(name: "NCSelect", bundle: nil).instantiateInitialViewController() as! UINavigationController
  343. let topViewController = navigationController.topViewController as! NCSelect
  344. var listViewController = [NCSelect]()
  345. var copyItems: [Any] = []
  346. for item in items {
  347. copyItems.append(item)
  348. }
  349. let homeUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account)
  350. var serverUrl = (copyItems[0] as! Nextcloud.tableMetadata).serverUrl
  351. // Setup view controllers such that the current view is of the same directory the items to be copied are in
  352. while true {
  353. // If not in the topmost directory, create a new view controller and set correct title.
  354. // If in the topmost directory, use the default view controller as the base.
  355. var viewController: NCSelect?
  356. if serverUrl != homeUrl {
  357. viewController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateViewController(withIdentifier: "NCSelect.storyboard") as? NCSelect
  358. if viewController == nil {
  359. return
  360. }
  361. viewController!.titleCurrentFolder = (serverUrl as NSString).lastPathComponent
  362. } else {
  363. viewController = topViewController
  364. }
  365. guard let vc = viewController else { return }
  366. vc.delegate = self
  367. vc.typeOfCommandView = .copyMove
  368. vc.items = copyItems
  369. vc.serverUrl = serverUrl
  370. vc.navigationItem.backButtonTitle = vc.titleCurrentFolder
  371. listViewController.insert(vc, at: 0)
  372. if serverUrl != homeUrl {
  373. serverUrl = NCUtilityFileSystem.shared.deletingLastPathComponent(serverUrl: serverUrl, urlBase: appDelegate.urlBase, account: appDelegate.account)
  374. } else {
  375. break
  376. }
  377. }
  378. navigationController.setViewControllers(listViewController, animated: false)
  379. navigationController.modalPresentationStyle = .formSheet
  380. viewController.present(navigationController, animated: true, completion: nil)
  381. }
  382. // MARK: - Context Menu Configuration
  383. @available(iOS 13.0, *)
  384. func contextMenuConfiguration(ocId: String, viewController: UIViewController, enableDeleteLocal: Bool, enableViewInFolder: Bool, image: UIImage?) -> UIMenu {
  385. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) else {
  386. return UIMenu()
  387. }
  388. var titleDeleteConfirmFile = NSLocalizedString("_delete_file_", comment: "")
  389. if metadata.directory { titleDeleteConfirmFile = NSLocalizedString("_delete_folder_", comment: "") }
  390. var titleSave: String = NSLocalizedString("_save_selected_files_", comment: "")
  391. let metadataMOV = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata)
  392. if metadataMOV != nil {
  393. titleSave = NSLocalizedString("_livephoto_save_", comment: "")
  394. }
  395. let titleFavorite = metadata.favorite ? NSLocalizedString("_remove_favorites_", comment: "") : NSLocalizedString("_add_favorites_", comment: "")
  396. let serverUrl = metadata.serverUrl + "/" + metadata.fileName
  397. var isOffline = false
  398. if metadata.directory {
  399. if let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, serverUrl)) {
  400. isOffline = directory.offline
  401. }
  402. } else {
  403. if let localFile = NCManageDatabase.shared.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId)) {
  404. isOffline = localFile.offline
  405. }
  406. }
  407. let titleOffline = isOffline ? NSLocalizedString("_remove_available_offline_", comment: "") : NSLocalizedString("_set_available_offline_", comment: "")
  408. let copy = UIAction(title: NSLocalizedString("_copy_file_", comment: ""), image: UIImage(systemName: "doc.on.doc")) { action in
  409. self.appDelegate.pasteboardOcIds = [metadata.ocId]
  410. self.copyPasteboard()
  411. }
  412. let detail = UIAction(title: NSLocalizedString("_details_", comment: ""), image: UIImage(systemName: "info")) { action in
  413. self.openShare(ViewController: viewController, metadata: metadata, indexPage: 0)
  414. }
  415. let offline = UIAction(title: titleOffline, image: UIImage(systemName: "tray.and.arrow.down")) { action in
  416. if isOffline {
  417. if metadata.directory {
  418. NCManageDatabase.shared.setDirectory(serverUrl: serverUrl, offline: false, account: self.appDelegate.account)
  419. } else {
  420. NCManageDatabase.shared.setLocalFile(ocId: metadata.ocId, offline: false)
  421. }
  422. } else {
  423. if metadata.directory {
  424. NCManageDatabase.shared.setDirectory(serverUrl: serverUrl, offline: true, account: self.appDelegate.account)
  425. NCOperationQueue.shared.synchronizationMetadata(metadata, selector: NCGlobal.shared.selectorDownloadAllFile)
  426. } else {
  427. NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorLoadOffline) { (_) in }
  428. if let metadataLivePhoto = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) {
  429. NCNetworking.shared.download(metadata: metadataLivePhoto, selector: NCGlobal.shared.selectorLoadOffline) { (_) in }
  430. }
  431. }
  432. }
  433. if viewController is NCCollectionViewCommon {
  434. (viewController as! NCCollectionViewCommon).reloadDataSource()
  435. }
  436. }
  437. let save = UIAction(title: titleSave, image: UIImage(systemName: "square.and.arrow.down")) { action in
  438. if metadataMOV != nil {
  439. self.saveLivePhoto(metadata: metadata, metadataMOV: metadataMOV!)
  440. } else {
  441. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  442. self.saveAlbum(metadata: metadata)
  443. } else {
  444. NCOperationQueue.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorSaveAlbum)
  445. }
  446. }
  447. }
  448. let saveBackground = UIAction(title: NSLocalizedString("_use_as_background_", comment: ""), image: UIImage(systemName: "text.below.photo")) { action in
  449. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  450. self.saveBackground(metadata: metadata)
  451. } else {
  452. NCOperationQueue.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorSaveBackground)
  453. }
  454. }
  455. let viewInFolder = UIAction(title: NSLocalizedString("_view_in_folder_", comment: ""), image: UIImage(systemName: "arrow.forward.square")) { action in
  456. self.openFileViewInFolder(serverUrl: metadata.serverUrl, fileName: metadata.fileName)
  457. }
  458. let openIn = UIAction(title: NSLocalizedString("_open_in_", comment: ""), image: UIImage(systemName: "square.and.arrow.up") ) { action in
  459. self.openDownload(metadata: metadata, selector: NCGlobal.shared.selectorOpenIn)
  460. }
  461. let print = UIAction(title: NSLocalizedString("_print_", comment: ""), image: UIImage(systemName: "printer") ) { action in
  462. self.openDownload(metadata: metadata, selector: NCGlobal.shared.selectorPrint)
  463. }
  464. let openQuickLook = UIAction(title: NSLocalizedString("_open_quicklook_", comment: ""), image: UIImage(systemName: "eye")) { action in
  465. self.openDownload(metadata: metadata, selector: NCGlobal.shared.selectorLoadFileQuickLook)
  466. }
  467. let open = UIMenu(title: NSLocalizedString("_open_", comment: ""), image: UIImage(systemName: "square.and.arrow.up"), children: [openIn, openQuickLook])
  468. let moveCopy = UIAction(title: NSLocalizedString("_move_or_copy_", comment: ""), image: UIImage(systemName: "arrow.up.right.square")) { action in
  469. self.openSelectView(items: [metadata], viewController: viewController)
  470. }
  471. let rename = UIAction(title: NSLocalizedString("_rename_", comment: ""), image: UIImage(systemName: "pencil")) { action in
  472. if let vcRename = UIStoryboard(name: "NCRenameFile", bundle: nil).instantiateInitialViewController() as? NCRenameFile {
  473. vcRename.metadata = metadata
  474. vcRename.imagePreview = image
  475. let popup = NCPopupViewController(contentController: vcRename, popupWidth: vcRename.width, popupHeight: vcRename.height)
  476. viewController.present(popup, animated: true)
  477. }
  478. }
  479. let favorite = UIAction(title: titleFavorite, image: NCUtility.shared.loadImage(named: "star.fill", color: NCBrandColor.shared.yellowFavorite)) { action in
  480. NCNetworking.shared.favoriteMetadata(metadata, urlBase: self.appDelegate.urlBase) { (errorCode, errorDescription) in
  481. if errorCode != 0 {
  482. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  483. }
  484. }
  485. }
  486. let deleteConfirmFile = UIAction(title: titleDeleteConfirmFile, image: UIImage(systemName: "trash"), attributes: .destructive) { action in
  487. NCNetworking.shared.deleteMetadata(metadata, account: self.appDelegate.account, urlBase: self.appDelegate.urlBase, onlyLocal: false) { (errorCode, errorDescription) in
  488. if errorCode != 0 {
  489. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  490. }
  491. }
  492. }
  493. let deleteConfirmLocal = UIAction(title: NSLocalizedString("_remove_local_file_", comment: ""), image: UIImage(systemName: "trash"), attributes: .destructive) { action in
  494. NCNetworking.shared.deleteMetadata(metadata, account: self.appDelegate.account, urlBase: self.appDelegate.urlBase, onlyLocal: true) { (errorCode, errorDescription) in
  495. }
  496. }
  497. var delete = UIMenu(title: NSLocalizedString("_delete_file_", comment: ""), image: UIImage(systemName: "trash"), options: .destructive, children: [deleteConfirmLocal, deleteConfirmFile])
  498. if !enableDeleteLocal {
  499. delete = UIMenu(title: NSLocalizedString("_delete_file_", comment: ""), image: UIImage(systemName: "trash"), options: .destructive, children: [deleteConfirmFile])
  500. }
  501. if metadata.directory {
  502. delete = UIMenu(title: NSLocalizedString("_delete_folder_", comment: ""), image: UIImage(systemName: "trash"), options: .destructive, children: [deleteConfirmFile])
  503. }
  504. // ------ MENU -----
  505. // DIR
  506. if metadata.directory {
  507. let submenu = UIMenu(title: "", options: .displayInline, children: [favorite, offline, rename, moveCopy, delete])
  508. return UIMenu(title: "", children: [detail, submenu])
  509. }
  510. // FILE
  511. var children: [UIMenuElement] = [favorite, offline, open, rename, moveCopy, copy, delete]
  512. if metadata.typeFile == NCGlobal.shared.metadataTypeFileImage || metadata.typeFile == NCGlobal.shared.metadataTypeFileVideo {
  513. children.insert(save, at: 2)
  514. }
  515. if metadata.typeFile == NCGlobal.shared.metadataTypeFileImage || metadata.contentType == "application/pdf" {
  516. children.insert(print, at: 2)
  517. }
  518. if enableViewInFolder {
  519. children.insert(viewInFolder, at: children.count-1)
  520. }
  521. if metadata.typeFile == NCGlobal.shared.metadataTypeFileImage && viewController is NCCollectionViewCommon && !NCBrandOptions.shared.disable_background_image {
  522. let viewController: NCCollectionViewCommon = viewController as! NCCollectionViewCommon
  523. let layoutKey = viewController.layoutKey
  524. if layoutKey == NCGlobal.shared.layoutViewFiles {
  525. children.insert(saveBackground, at: children.count-1)
  526. }
  527. }
  528. let submenu = UIMenu(title: "", options: .displayInline, children: children)
  529. return UIMenu(title: "", children: [detail, submenu])
  530. }
  531. }