NCFunctionCenter.swift 47 KB

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