NCViewerRichdocument.swift 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. //
  2. // NCViewerRichdocument.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 06/09/18.
  6. // Copyright © 2018 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. class NCViewerRichdocument: NSObject, WKNavigationDelegate, WKScriptMessageHandler, NCSelectDelegate {
  25. var detail: CCDetail!
  26. var webView: WKWebView!
  27. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  28. @objc static let sharedInstance: NCViewerRichdocument = {
  29. let instance = NCViewerRichdocument()
  30. return instance
  31. }()
  32. @objc func viewRichDocumentAt(_ link: String, detail: CCDetail) {
  33. self.detail = detail
  34. if (UIDevice.current.userInterfaceIdiom == .phone) {
  35. detail.navigationController?.setNavigationBarHidden(true, animated: false)
  36. }
  37. let contentController = WKUserContentController()
  38. contentController.add(self, name: "RichDocumentsMobileInterface")
  39. let configuration = WKWebViewConfiguration()
  40. configuration.userContentController = contentController
  41. webView = WKWebView(frame: detail.view.bounds, configuration: configuration)
  42. webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  43. // webView.scrollView.showsHorizontalScrollIndicator = true
  44. // webView.scrollView.showsVerticalScrollIndicator = true
  45. webView.navigationDelegate = self
  46. var request = URLRequest(url: URL(string: link)!)
  47. request.addValue("true", forHTTPHeaderField: "OCS-APIRequest")
  48. let language = NSLocale.preferredLanguages[0] as String
  49. request.addValue(language, forHTTPHeaderField: "Accept-Language")
  50. let userAgent : String = CCUtility.getUserAgent()
  51. webView.customUserAgent = userAgent
  52. webView.load(request)
  53. detail.view.addSubview(webView)
  54. }
  55. //MARK: -
  56. public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
  57. if (message.name == "RichDocumentsMobileInterface") {
  58. if message.body as! String == "close" {
  59. self.webView.removeFromSuperview()
  60. self.detail.navigationController?.popViewController(animated: true)
  61. // detail.navigationController?.setNavigationBarHidden(false, animated: false)
  62. self.detail.navigationController?.navigationBar.topItem?.title = ""
  63. }
  64. if message.body as! String == "insertGraphic" {
  65. let storyboard = UIStoryboard(name: "NCSelect", bundle: nil)
  66. let navigationController = storyboard.instantiateInitialViewController() as! UINavigationController
  67. let viewController = navigationController.topViewController as! NCSelect
  68. viewController.delegate = self
  69. viewController.hideButtonCreateFolder = true
  70. viewController.selectFile = true
  71. viewController.includeDirectoryE2EEncryption = false
  72. viewController.includeImages = true
  73. viewController.type = ""
  74. viewController.layoutViewSelect = k_layout_view_richdocument
  75. navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
  76. self.detail.present(navigationController, animated: true, completion: nil)
  77. }
  78. if message.body as! String == "share" {
  79. appDelegate.activeMain.readShare(withAccount: appDelegate.activeAccount, openWindow: true, metadata: self.detail.metadataDetail)
  80. }
  81. }
  82. }
  83. //MARK: -
  84. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String) {
  85. if serverUrl != nil && metadata != nil {
  86. OCNetworking.sharedManager().createAssetRichdocuments(withAccount: metadata?.account, fileName: metadata?.fileName, serverUrl: serverUrl, completion: { (account, url, message, errorCode) in
  87. if errorCode == 0 && account == self.appDelegate.activeAccount {
  88. let functionJS = "OCA.RichDocuments.documentsMain.postAsset('\(metadata!.fileNameView)', '\(url!)')"
  89. self.webView.evaluateJavaScript(functionJS, completionHandler: { (result, error) in })
  90. } else if errorCode != 0 {
  91. self.appDelegate.messageNotification("_error_", description: message, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: Int(k_CCErrorInternalError))
  92. } else {
  93. print("[LOG] It has been changed user during networking process, error.")
  94. }
  95. })
  96. }
  97. }
  98. func select(_ metadata: tableMetadata!, serverUrl: String!) {
  99. OCNetworking.sharedManager().createAssetRichdocuments(withAccount: metadata?.account, fileName: metadata?.fileName, serverUrl: serverUrl, completion: { (account, url, message, errorCode) in
  100. if errorCode == 0 && account == self.appDelegate.activeAccount {
  101. let functionJS = "OCA.RichDocuments.documentsMain.postAsset('\(metadata.fileNameView)', '\(url!)')"
  102. self.webView.evaluateJavaScript(functionJS, completionHandler: { (result, error) in })
  103. } else if errorCode != 0 {
  104. self.appDelegate.messageNotification("_error_", description: message, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: Int(k_CCErrorInternalError))
  105. } else {
  106. print("[LOG] It has been changed user during networking process, error.")
  107. }
  108. })
  109. }
  110. //MARK: -
  111. public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  112. if let serverTrust = challenge.protectionSpace.serverTrust {
  113. completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
  114. } else {
  115. completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil);
  116. }
  117. }
  118. public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
  119. print("didStartProvisionalNavigation");
  120. }
  121. public func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
  122. print("didReceiveServerRedirectForProvisionalNavigation");
  123. }
  124. public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
  125. NCUtility.sharedInstance.stopActivityIndicator()
  126. }
  127. //MARK: -
  128. @objc func isRichDocument(_ metadata: tableMetadata) -> Bool {
  129. if appDelegate.reachability.isReachable() == false {
  130. return false
  131. }
  132. guard let mimeType = CCUtility.getMimeType(metadata.fileNameView) else {
  133. return false
  134. }
  135. guard let richdocumentsMimetypes = NCManageDatabase.sharedInstance.getRichdocumentsMimetypes(account: metadata.account) else {
  136. return false
  137. }
  138. if richdocumentsMimetypes.count > 0 && mimeType.components(separatedBy: ".").count > 2 {
  139. let mimeTypeArray = mimeType.components(separatedBy: ".")
  140. let mimeType = mimeTypeArray[mimeTypeArray.count - 2] + "." + mimeTypeArray[mimeTypeArray.count - 1]
  141. for richdocumentMimetype: String in richdocumentsMimetypes {
  142. if richdocumentMimetype.contains(mimeType) {
  143. return true
  144. }
  145. }
  146. }
  147. return false
  148. }
  149. }