NCNetworkingNotificationCenter.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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. import NCCommunication
  25. @objc class NCNetworkingNotificationCenter: NSObject, UIDocumentInteractionControllerDelegate {
  26. @objc public static let shared: NCNetworkingNotificationCenter = {
  27. let instance = NCNetworkingNotificationCenter()
  28. NotificationCenter.default.addObserver(instance, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadedFile), object: nil)
  29. NotificationCenter.default.addObserver(instance, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  30. return instance
  31. }()
  32. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  33. var viewerQuickLook: NCViewerQuickLook?
  34. var documentController: UIDocumentInteractionController?
  35. //MARK: - Download
  36. @objc func downloadedFile(_ notification: NSNotification) {
  37. if let userInfo = notification.userInfo as NSDictionary? {
  38. 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) {
  39. if metadata.account != appDelegate.account { return }
  40. if errorCode == 0 {
  41. let fileURL = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  42. documentController = UIDocumentInteractionController(url: fileURL)
  43. documentController?.delegate = self
  44. switch selector {
  45. case NCGlobal.shared.selectorLoadFileQuickLook:
  46. let fileNamePath = NSTemporaryDirectory() + metadata.fileNameView
  47. CCUtility.copyFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView), toPath: fileNamePath)
  48. viewerQuickLook = NCViewerQuickLook.init()
  49. viewerQuickLook?.quickLook(url: URL(fileURLWithPath: fileNamePath))
  50. case NCGlobal.shared.selectorLoadFileView:
  51. if UIApplication.shared.applicationState == UIApplication.State.active {
  52. if metadata.contentType.contains("opendocument") && !NCUtility.shared.isRichDocument(metadata) {
  53. if let view = appDelegate.window?.rootViewController?.view {
  54. documentController?.presentOptionsMenu(from: CGRect.zero, in: view, animated: true)
  55. }
  56. } else if metadata.typeFile == NCGlobal.shared.metadataTypeFileCompress || metadata.typeFile == NCGlobal.shared.metadataTypeFileUnknown {
  57. if let view = appDelegate.window?.rootViewController?.view {
  58. documentController?.presentOptionsMenu(from: CGRect.zero, in: view, animated: true)
  59. }
  60. } else if metadata.typeFile == NCGlobal.shared.metadataTypeFileImagemeter {
  61. if let view = appDelegate.window?.rootViewController?.view {
  62. documentController?.presentOptionsMenu(from: CGRect.zero, in: view, animated: true)
  63. }
  64. } else {
  65. if let viewController = self.appDelegate.activeViewController {
  66. NCViewer.shared.view(viewController: viewController, metadata: metadata, metadatas: [metadata])
  67. }
  68. }
  69. }
  70. case NCGlobal.shared.selectorOpenIn:
  71. if UIApplication.shared.applicationState == UIApplication.State.active {
  72. if let view = appDelegate.window?.rootViewController?.view {
  73. documentController?.presentOptionsMenu(from: CGRect.zero, in: view, animated: true)
  74. }
  75. }
  76. case NCGlobal.shared.selectorLoadCopy:
  77. copyPasteboard()
  78. case NCGlobal.shared.selectorLoadOffline:
  79. NCManageDatabase.shared.setLocalFile(ocId: metadata.ocId, offline: true)
  80. case NCGlobal.shared.selectorPrint:
  81. printDocument(metadata: metadata)
  82. case NCGlobal.shared.selectorSaveAlbum:
  83. saveAlbum(metadata: metadata)
  84. case NCGlobal.shared.selectorSaveAlbumLivePhotoIMG, NCGlobal.shared.selectorSaveAlbumLivePhotoMOV:
  85. var metadata = metadata
  86. var metadataMOV = metadata
  87. guard let metadataTMP = NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) else { break }
  88. if selector == NCGlobal.shared.selectorSaveAlbumLivePhotoIMG {
  89. metadataMOV = metadataTMP
  90. }
  91. if selector == NCGlobal.shared.selectorSaveAlbumLivePhotoMOV {
  92. metadata = metadataTMP
  93. }
  94. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) && CCUtility.fileProviderStorageExists(metadataMOV.ocId, fileNameView: metadataMOV.fileNameView) {
  95. saveLivePhotoToDisk(metadata: metadata, metadataMov: metadataMOV, progressView: nil, viewActivity: self.appDelegate.window?.rootViewController?.view)
  96. }
  97. default:
  98. break
  99. }
  100. } else {
  101. // File do not exists on server, remove in local
  102. if (errorCode == NCGlobal.shared.ErrorResourceNotFound || errorCode == NCGlobal.shared.ErrorBadServerResponse) {
  103. do {
  104. try FileManager.default.removeItem(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  105. } catch { }
  106. NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  107. NCManageDatabase.shared.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  108. } else {
  109. NCContentPresenter.shared.messageNotification("_download_file_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  110. }
  111. }
  112. }
  113. }
  114. }
  115. //MARK: - Upload
  116. @objc func uploadedFile(_ notification: NSNotification) {
  117. if let userInfo = notification.userInfo as NSDictionary? {
  118. 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) {
  119. if metadata.account == appDelegate.account {
  120. if errorCode != 0 {
  121. if errorCode != -999 && errorCode != 401 && errorDescription != "" {
  122. NCContentPresenter.shared.messageNotification("_upload_file_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  123. }
  124. }
  125. }
  126. }
  127. }
  128. }
  129. // MARK: -
  130. func openShare(ViewController: UIViewController, metadata: tableMetadata, indexPage: Int) {
  131. let shareNavigationController = UIStoryboard(name: "NCShare", bundle: nil).instantiateInitialViewController() as! UINavigationController
  132. let shareViewController = shareNavigationController.topViewController as! NCSharePaging
  133. shareViewController.metadata = metadata
  134. shareViewController.indexPage = indexPage
  135. shareNavigationController.modalPresentationStyle = .formSheet
  136. ViewController.present(shareNavigationController, animated: true, completion: nil)
  137. }
  138. func downloadOpen(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. func printDocument(metadata: tableMetadata) {
  146. let fileNameURL = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!)
  147. if UIPrintInteractionController.canPrint(fileNameURL) {
  148. let printInfo = UIPrintInfo(dictionary: nil)
  149. printInfo.jobName = fileNameURL.lastPathComponent
  150. printInfo.outputType = .photo
  151. let printController = UIPrintInteractionController.shared
  152. printController.printInfo = printInfo
  153. printController.showsNumberOfCopies = true
  154. printController.printingItem = fileNameURL
  155. printController.present(animated: true, completionHandler: nil)
  156. }
  157. }
  158. func saveAlbum(metadata: tableMetadata) {
  159. let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  160. let status = PHPhotoLibrary.authorizationStatus()
  161. if metadata.typeFile == NCGlobal.shared.metadataTypeFileImage && status == PHAuthorizationStatus.authorized {
  162. if let image = UIImage.init(contentsOfFile: fileNamePath) {
  163. UIImageWriteToSavedPhotosAlbum(image, self, #selector(SaveAlbum(_:didFinishSavingWithError:contextInfo:)), nil)
  164. } else {
  165. NCContentPresenter.shared.messageNotification("_save_selected_files_", description: "_file_not_saved_cameraroll_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.ErrorFileNotSaved)
  166. }
  167. } else if metadata.typeFile == NCGlobal.shared.metadataTypeFileVideo && status == PHAuthorizationStatus.authorized {
  168. if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(fileNamePath) {
  169. UISaveVideoAtPathToSavedPhotosAlbum(fileNamePath, self, #selector(SaveAlbum(_:didFinishSavingWithError:contextInfo:)), nil)
  170. } else {
  171. NCContentPresenter.shared.messageNotification("_save_selected_files_", description: "_file_not_saved_cameraroll_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.ErrorFileNotSaved)
  172. }
  173. } else if status != PHAuthorizationStatus.authorized {
  174. 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)
  175. }
  176. }
  177. @objc private func SaveAlbum(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
  178. if error != nil {
  179. NCContentPresenter.shared.messageNotification("_save_selected_files_", description: "_file_not_saved_cameraroll_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.ErrorFileNotSaved)
  180. }
  181. }
  182. func saveLivePhoto(metadata: tableMetadata, metadataMOV: tableMetadata) {
  183. if !CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  184. NCOperationQueue.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorSaveAlbumLivePhotoIMG)
  185. }
  186. if !CCUtility.fileProviderStorageExists(metadataMOV.ocId, fileNameView: metadataMOV.fileNameView) {
  187. NCOperationQueue.shared.download(metadata: metadataMOV, selector: NCGlobal.shared.selectorSaveAlbumLivePhotoMOV)
  188. }
  189. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) && CCUtility.fileProviderStorageExists(metadataMOV.ocId, fileNameView: metadataMOV.fileNameView) {
  190. saveLivePhotoToDisk(metadata: metadata, metadataMov: metadataMOV, progressView: nil, viewActivity: self.appDelegate.window?.rootViewController?.view)
  191. }
  192. }
  193. func saveLivePhotoToDisk(metadata: tableMetadata, metadataMov: tableMetadata, progressView: UIProgressView?, viewActivity: UIView?) {
  194. let fileNameImage = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!)
  195. let fileNameMov = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadataMov.ocId, fileNameView: metadataMov.fileNameView)!)
  196. if let view = viewActivity {
  197. NCUtility.shared.startActivityIndicator(view: view)
  198. }
  199. NCLivePhoto.generate(from: fileNameImage, videoURL: fileNameMov, progress: { progress in
  200. DispatchQueue.main.async {
  201. progressView?.progress = Float(progress)
  202. }
  203. }, completion: { livePhoto, resources in
  204. NCUtility.shared.stopActivityIndicator()
  205. progressView?.progress = 0
  206. if resources != nil {
  207. NCLivePhoto.saveToLibrary(resources!) { (result) in
  208. if !result {
  209. NCContentPresenter.shared.messageNotification("_error_", description: "_livephoto_save_error_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.ErrorInternalError)
  210. }
  211. }
  212. } else {
  213. NCContentPresenter.shared.messageNotification("_error_", description: "_livephoto_save_error_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.ErrorInternalError)
  214. }
  215. })
  216. }
  217. func copyPasteboard() {
  218. var metadatas: [tableMetadata] = []
  219. var items = [[String : Any]]()
  220. for ocId in appDelegate.pasteboardOcIds {
  221. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  222. metadatas.append(metadata)
  223. }
  224. }
  225. for metadata in metadatas {
  226. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  227. do {
  228. // Get Data
  229. let data = try Data.init(contentsOf: URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)))
  230. // Pasteboard item
  231. if let unmanagedFileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (metadata.fileNameView as NSString).pathExtension as CFString, nil) {
  232. let fileUTI = unmanagedFileUTI.takeRetainedValue() as String
  233. items.append([fileUTI:data])
  234. }
  235. } catch {
  236. print("error")
  237. }
  238. } else {
  239. NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorLoadCopy) { (_) in }
  240. }
  241. }
  242. UIPasteboard.general.setItems(items, options: [:])
  243. }
  244. func pastePasteboard(serverUrl: String) {
  245. for (index, items) in UIPasteboard.general.items.enumerated() {
  246. for item in items {
  247. let pasteboardType = item.key
  248. if let data = UIPasteboard.general.data(forPasteboardType: pasteboardType, inItemSet: IndexSet([index]))?.first {
  249. let results = NCCommunicationCommon.shared.getDescriptionFile(inUTI: pasteboardType as CFString)
  250. if results.resultTypeFile != NCCommunicationCommon.typeFile.unknow.rawValue {
  251. uploadPasteFile(fileName: results.resultFilename, ext: results.resultExtension, contentType: pasteboardType, serverUrl: serverUrl, data: data)
  252. }
  253. }
  254. }
  255. }
  256. }
  257. private func uploadPasteFile(fileName: String, ext: String, contentType: String, serverUrl: String, data: Data) {
  258. do {
  259. let fileNameView = fileName + "_" + CCUtility.getIncrementalNumber() + "." + ext
  260. let ocId = UUID().uuidString
  261. let filePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView)!
  262. try data.write(to: URL(fileURLWithPath: filePath))
  263. let metadataForUpload = NCManageDatabase.shared.createMetadata(account: appDelegate.account, fileName: fileNameView, ocId: ocId, serverUrl: serverUrl, urlBase: appDelegate.urlBase, url: "", contentType: contentType, livePhoto: false)
  264. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
  265. metadataForUpload.sessionSelector = NCGlobal.shared.selectorUploadFile
  266. metadataForUpload.size = NCUtilityFileSystem.shared.getFileSize(filePath: filePath)
  267. metadataForUpload.status = NCGlobal.shared.metadataStatusWaitUpload
  268. NCManageDatabase.shared.addMetadata(metadataForUpload)
  269. } catch { }
  270. }
  271. }