NCFunctionCenter.swift 41 KB

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