NCFunctionCenter.swift 40 KB

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