NCFunctionCenter.swift 40 KB

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