NCFunctionCenter.swift 48 KB

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