NCFunctionCenter.swift 42 KB

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