NCViewerRichdocument.swift 9.3 KB

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