NCNetworkingNotificationCenter.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. //
  2. // NCNetworkingNotificationCenter.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 Foundation
  24. @objc class NCNetworkingNotificationCenter: NSObject, UIDocumentInteractionControllerDelegate {
  25. @objc public static let shared: NCNetworkingNotificationCenter = {
  26. let instance = NCNetworkingNotificationCenter()
  27. NotificationCenter.default.addObserver(instance, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadedFile), object: nil)
  28. NotificationCenter.default.addObserver(instance, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadedFile), object: nil)
  29. return instance
  30. }()
  31. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  32. var viewerQuickLook: NCViewerQuickLook?
  33. var docController: UIDocumentInteractionController?
  34. //MARK: - Download
  35. @objc func downloadedFile(_ notification: NSNotification) {
  36. if let userInfo = notification.userInfo as NSDictionary? {
  37. 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 {
  38. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  39. if metadata.account != appDelegate.account { return }
  40. if errorCode == 0 {
  41. let fileURL = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  42. switch selector {
  43. case selectorLoadFileQuickLook:
  44. let fileNamePath = NSTemporaryDirectory() + metadata.fileNameView
  45. CCUtility.copyFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView), toPath: fileNamePath)
  46. viewerQuickLook = NCViewerQuickLook.init()
  47. viewerQuickLook?.quickLook(url: URL(fileURLWithPath: fileNamePath))
  48. case selectorLoadFileView:
  49. if UIApplication.shared.applicationState == UIApplication.State.active {
  50. if metadata.contentType.contains("opendocument") && !NCUtility.shared.isRichDocument(metadata) {
  51. openIn(fileURL: fileURL, selector: selector)
  52. } else if metadata.typeFile == k_metadataTypeFile_compress || metadata.typeFile == k_metadataTypeFile_unknown {
  53. openIn(fileURL: fileURL, selector: selector)
  54. } else if metadata.typeFile == k_metadataTypeFile_imagemeter {
  55. openIn(fileURL: fileURL, selector: selector)
  56. } else {
  57. segueMetadata(metadata)
  58. }
  59. }
  60. case selectorOpenIn, selectorOpenInDetail:
  61. if UIApplication.shared.applicationState == UIApplication.State.active {
  62. openIn(fileURL: fileURL, selector: selector)
  63. }
  64. case selectorLoadCopy:
  65. var items = UIPasteboard.general.items
  66. do {
  67. let etagPasteboard = try NSKeyedArchiver.archivedData(withRootObject: metadata.ocId, requiringSecureCoding: false)
  68. items.append([k_metadataKeyedUnarchiver:etagPasteboard])
  69. } catch {
  70. print("error")
  71. }
  72. UIPasteboard.general.setItems(items, options: [:])
  73. case selectorLoadOffline:
  74. NCManageDatabase.sharedInstance.setLocalFile(ocId: metadata.ocId, offline: true)
  75. case selectorSaveAlbum:
  76. let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  77. let status = PHPhotoLibrary.authorizationStatus()
  78. if metadata.typeFile == k_metadataTypeFile_image && status == PHAuthorizationStatus.authorized {
  79. if let image = UIImage.init(contentsOfFile: fileNamePath) {
  80. UIImageWriteToSavedPhotosAlbum(image, self, #selector(SaveAlbum(_:didFinishSavingWithError:contextInfo:)), nil)
  81. } else {
  82. NCContentPresenter.shared.messageNotification("_save_selected_files_", description: "_file_not_saved_cameraroll_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorFileNotSaved))
  83. }
  84. } else if metadata.typeFile == k_metadataTypeFile_video && status == PHAuthorizationStatus.authorized {
  85. if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(fileNamePath) {
  86. UISaveVideoAtPathToSavedPhotosAlbum(fileNamePath, self, #selector(SaveAlbum(_:didFinishSavingWithError:contextInfo:)), nil)
  87. } else {
  88. NCContentPresenter.shared.messageNotification("_save_selected_files_", description: "_file_not_saved_cameraroll_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorFileNotSaved))
  89. }
  90. } else if status != PHAuthorizationStatus.authorized {
  91. NCContentPresenter.shared.messageNotification("_access_photo_not_enabled_", description: "_access_photo_not_enabled_msg_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorFileNotSaved))
  92. }
  93. default:
  94. break
  95. }
  96. } else {
  97. // File do not exists on server, remove in local
  98. if (errorCode == k_CCErrorResourceNotFound || errorCode == k_CCErrorBadServerResponse) {
  99. do {
  100. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  101. } catch { }
  102. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  103. NCManageDatabase.sharedInstance.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  104. } else {
  105. NCContentPresenter.shared.messageNotification("_download_file_", description: errorDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  106. }
  107. }
  108. }
  109. }
  110. }
  111. }
  112. func openIn(fileURL: URL, selector: String?) {
  113. docController = UIDocumentInteractionController(url: fileURL)
  114. docController?.delegate = self
  115. if selector == selectorOpenInDetail {
  116. guard let barButtonItem = appDelegate.activeDetail.navigationItem.rightBarButtonItem else { return }
  117. guard let buttonItemView = barButtonItem.value(forKey: "view") as? UIView else { return }
  118. docController?.presentOptionsMenu(from: buttonItemView.frame, in: buttonItemView, animated: true)
  119. } else {
  120. guard let splitViewController = appDelegate.window?.rootViewController as? UISplitViewController, let view = splitViewController.viewControllers.first?.view, let frame = splitViewController.viewControllers.first?.view.frame else {
  121. return }
  122. docController?.presentOptionsMenu(from: frame, in: view, animated: true)
  123. }
  124. }
  125. @objc func openShare(ViewController: UIViewController, metadata: tableMetadata, indexPage: Int) {
  126. let shareNavigationController = UIStoryboard(name: "NCShare", bundle: nil).instantiateInitialViewController() as! UINavigationController
  127. let shareViewController = shareNavigationController.topViewController as! NCSharePaging
  128. shareViewController.metadata = metadata
  129. shareViewController.indexPage = indexPage
  130. shareNavigationController.modalPresentationStyle = .formSheet
  131. ViewController.present(shareNavigationController, animated: true, completion: nil)
  132. }
  133. @objc func downloadOpen(metadata: tableMetadata, selector: String) {
  134. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  135. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_downloadedFile, userInfo: ["ocId": metadata.ocId, "selector": selector, "errorCode": 0, "errorDescription": "" ])
  136. } else {
  137. NCNetworking.shared.download(metadata: metadata, selector: selector) { (_) in }
  138. }
  139. }
  140. @objc func segueMetadata(_ metadata: tableMetadata) {
  141. if self.appDelegate.activeViewController is NCFiles {
  142. (self.appDelegate.activeViewController as! NCFiles).segue(metadata: metadata)
  143. } else if self.appDelegate.activeViewController is NCFavorite {
  144. (self.appDelegate.activeViewController as! NCFavorite).segue(metadata: metadata)
  145. } else if self.appDelegate.activeViewController is NCOffline {
  146. (self.appDelegate.activeViewController as! NCOffline).segue(metadata: metadata)
  147. } else if self.appDelegate.activeViewController is NCRecent {
  148. (self.appDelegate.activeViewController as! NCRecent).segue(metadata: metadata)
  149. } else if self.appDelegate.activeViewController is NCFileViewInFolder {
  150. (self.appDelegate.activeViewController as! NCFileViewInFolder).segue(metadata: metadata)
  151. }
  152. }
  153. @objc func SaveAlbum(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
  154. if error != nil {
  155. NCContentPresenter.shared.messageNotification("_save_selected_files_", description: "_file_not_saved_cameraroll_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorFileNotSaved))
  156. }
  157. }
  158. //MARK: - Upload
  159. @objc func uploadedFile(_ notification: NSNotification) {
  160. if let userInfo = notification.userInfo as NSDictionary? {
  161. if let ocId = userInfo["ocId"] as? String, let errorCode = userInfo["errorCode"] as? Int, let errorDescription = userInfo["errorDescription"] as? String {
  162. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  163. if metadata.account == appDelegate.account {
  164. if errorCode != 0 {
  165. if errorCode != -999 && errorCode != 401 && errorDescription != "" {
  166. NCContentPresenter.shared.messageNotification("_upload_file_", description: errorDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  167. }
  168. }
  169. }
  170. }
  171. }
  172. }
  173. }
  174. }