NCFunctionCenter.swift 39 KB

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