NCFunctionCenter.swift 39 KB

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