NCViewerRichdocument.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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: WKWebView, WKNavigationDelegate, WKScriptMessageHandler, NCSelectDelegate {
  25. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  26. var detail: CCDetail!
  27. @objc var metadata: tableMetadata!
  28. var documentInteractionController: UIDocumentInteractionController!
  29. override init(frame: CGRect, configuration: WKWebViewConfiguration) {
  30. super.init(frame: frame, configuration: configuration)
  31. let contentController = configuration.userContentController
  32. contentController.add(self, name: "RichDocumentsMobileInterface")
  33. autoresizingMask = [.flexibleWidth, .flexibleHeight]
  34. navigationDelegate = self
  35. }
  36. required init?(coder: NSCoder) {
  37. super.init(coder: coder)
  38. }
  39. @objc func viewRichDocumentAt(_ link: String, detail: CCDetail, metadata: tableMetadata) {
  40. self.detail = detail
  41. self.metadata = metadata
  42. NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow), name: UIResponder.keyboardDidShowNotification, object: nil)
  43. NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
  44. if (UIDevice.current.userInterfaceIdiom == .phone) {
  45. detail.navigationController?.setNavigationBarHidden(true, animated: false)
  46. }
  47. var request = URLRequest(url: URL(string: link)!)
  48. request.addValue("true", forHTTPHeaderField: "OCS-APIRequest")
  49. let language = NSLocale.preferredLanguages[0] as String
  50. request.addValue(language, forHTTPHeaderField: "Accept-Language")
  51. let userAgent : String = CCUtility.getUserAgent()
  52. customUserAgent = userAgent
  53. load(request)
  54. }
  55. @objc func keyboardDidShow(notification: Notification) {
  56. guard let info = notification.userInfo else { return }
  57. guard let frameInfo = info[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
  58. let keyboardFrame = frameInfo.cgRectValue
  59. //print("keyboardFrame: \(keyboardFrame)")
  60. frame.size.height = detail.view.bounds.height - keyboardFrame.size.height
  61. }
  62. @objc func keyboardWillHide(notification: Notification) {
  63. frame = detail.view.bounds
  64. }
  65. //MARK: -
  66. public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
  67. if (message.name == "RichDocumentsMobileInterface") {
  68. if message.body as? String == "close" {
  69. removeFromSuperview()
  70. detail.navigationController?.popViewController(animated: true)
  71. detail.navigationController?.navigationBar.topItem?.title = ""
  72. }
  73. if message.body as? String == "insertGraphic" {
  74. let storyboard = UIStoryboard(name: "NCSelect", bundle: nil)
  75. let navigationController = storyboard.instantiateInitialViewController() as! UINavigationController
  76. let viewController = navigationController.topViewController as! NCSelect
  77. viewController.delegate = self
  78. viewController.hideButtonCreateFolder = true
  79. viewController.selectFile = true
  80. viewController.includeDirectoryE2EEncryption = false
  81. viewController.includeImages = true
  82. viewController.type = ""
  83. viewController.layoutViewSelect = k_layout_view_richdocument
  84. navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
  85. self.detail.present(navigationController, animated: true, completion: nil)
  86. }
  87. if message.body as? String == "share" {
  88. appDelegate.activeMain.openShare(with: metadata, indexPage: 2)
  89. }
  90. if let param = message.body as? Dictionary<AnyHashable,Any> {
  91. if param["MessageName"] as? String == "downloadAs" {
  92. if let values = param["Values"] as? Dictionary<AnyHashable,Any> {
  93. guard let urlString = values["URL"] as? String else {
  94. return
  95. }
  96. guard let url = URL(string: urlString) else {
  97. return
  98. }
  99. guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
  100. return
  101. }
  102. let filename = (components.path as NSString).lastPathComponent
  103. let fileNameLocalPath = CCUtility.getDirectoryUserData() + "/" + filename
  104. _ = OCNetworking.sharedManager()?.download(withAccount: metadata.account, url: urlString, fileNameLocalPath: fileNameLocalPath, encode:false, completion: { (account, message, errorCode) in
  105. if errorCode == 0 && account == self.metadata.account {
  106. self.documentInteractionController = UIDocumentInteractionController()
  107. self.documentInteractionController.url = URL(fileURLWithPath: fileNameLocalPath)
  108. self.documentInteractionController.presentOptionsMenu(from: self.appDelegate.window.rootViewController!.view.bounds, in: self.appDelegate.window.rootViewController!.view, animated: true)
  109. } else {
  110. self.appDelegate.messageNotification("_error_", description: message, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  111. }
  112. })
  113. }
  114. } else if param["MessageName"] as? String == "fileRename" {
  115. if let values = param["Values"] as? Dictionary<AnyHashable,Any> {
  116. guard let newName = values["NewName"] as? String else {
  117. return
  118. }
  119. metadata.fileName = newName
  120. metadata.fileNameView = newName
  121. }
  122. }
  123. }
  124. if message.body as? String == "documentLoaded" {
  125. print("documentLoaded")
  126. }
  127. if message.body as? String == "paste" {
  128. self.paste(self)
  129. }
  130. }
  131. }
  132. //MARK: -
  133. @objc func grabFocus() {
  134. let functionJS = "OCA.RichDocuments.documentsMain.postGrabFocus()"
  135. evaluateJavaScript(functionJS) { (result, error) in }
  136. }
  137. //MARK: -
  138. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String) {
  139. if serverUrl != nil && metadata != nil {
  140. OCNetworking.sharedManager().createAssetRichdocuments(withAccount: metadata?.account, fileName: metadata?.fileName, serverUrl: serverUrl, completion: { (account, url, message, errorCode) in
  141. if errorCode == 0 && account == self.appDelegate.activeAccount {
  142. let functionJS = "OCA.RichDocuments.documentsMain.postAsset('\(metadata!.fileNameView)', '\(url!)')"
  143. self.evaluateJavaScript(functionJS, completionHandler: { (result, error) in })
  144. } else if errorCode != 0 {
  145. self.appDelegate.messageNotification("_error_", description: message, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: Int(k_CCErrorInternalError))
  146. } else {
  147. print("[LOG] It has been changed user during networking process, error.")
  148. }
  149. })
  150. }
  151. }
  152. func select(_ metadata: tableMetadata!, serverUrl: String!) {
  153. OCNetworking.sharedManager().createAssetRichdocuments(withAccount: metadata?.account, fileName: metadata?.fileName, serverUrl: serverUrl, completion: { (account, url, message, errorCode) in
  154. if errorCode == 0 && account == self.appDelegate.activeAccount {
  155. let functionJS = "OCA.RichDocuments.documentsMain.postAsset('\(metadata.fileNameView)', '\(url!)')"
  156. self.evaluateJavaScript(functionJS, completionHandler: { (result, error) in })
  157. } else if errorCode != 0 {
  158. self.appDelegate.messageNotification("_error_", description: message, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: Int(k_CCErrorInternalError))
  159. } else {
  160. print("[LOG] It has been changed user during networking process, error.")
  161. }
  162. })
  163. }
  164. //MARK: -
  165. public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  166. if let serverTrust = challenge.protectionSpace.serverTrust {
  167. completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
  168. } else {
  169. completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil);
  170. }
  171. }
  172. public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
  173. print("didStartProvisionalNavigation");
  174. }
  175. public func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
  176. print("didReceiveServerRedirectForProvisionalNavigation");
  177. }
  178. public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
  179. NCUtility.sharedInstance.stopActivityIndicator()
  180. }
  181. }