NCViewerRichdocument.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. appDelegate.activeMain.readFileReloadFolder()
  73. }
  74. if message.body as? String == "insertGraphic" {
  75. let storyboard = UIStoryboard(name: "NCSelect", bundle: nil)
  76. let navigationController = storyboard.instantiateInitialViewController() as! UINavigationController
  77. let viewController = navigationController.topViewController as! NCSelect
  78. viewController.delegate = self
  79. viewController.hideButtonCreateFolder = true
  80. viewController.selectFile = true
  81. viewController.includeDirectoryE2EEncryption = false
  82. viewController.includeImages = true
  83. viewController.type = ""
  84. viewController.layoutViewSelect = k_layout_view_richdocument
  85. navigationController.modalPresentationStyle = UIModalPresentationStyle.fullScreen
  86. self.detail.present(navigationController, animated: true, completion: nil)
  87. }
  88. if message.body as? String == "share" {
  89. NCMainCommon.sharedInstance.openShare(ViewController: detail, metadata: metadata, indexPage: 2)
  90. }
  91. if let param = message.body as? Dictionary<AnyHashable,Any> {
  92. if param["MessageName"] as? String == "downloadAs" {
  93. if let values = param["Values"] as? Dictionary<AnyHashable,Any> {
  94. guard let type = values["Type"] as? String else {
  95. return
  96. }
  97. guard let urlString = values["URL"] as? String else {
  98. return
  99. }
  100. guard let url = URL(string: urlString) else {
  101. return
  102. }
  103. guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
  104. return
  105. }
  106. let filename = (components.path as NSString).lastPathComponent
  107. let fileNameLocalPath = CCUtility.getDirectoryUserData() + "/" + filename
  108. if type == "print" {
  109. NCUtility.sharedInstance.startActivityIndicator(view: self, bottom: 0)
  110. }
  111. _ = OCNetworking.sharedManager()?.download(withAccount: metadata.account, url: urlString, fileNameLocalPath: fileNameLocalPath, encode:false, completion: { (account, message, errorCode) in
  112. if errorCode == 0 && account == self.metadata.account {
  113. if type == "print" {
  114. NCUtility.sharedInstance.stopActivityIndicator()
  115. let pic = UIPrintInteractionController.shared
  116. let printInfo = UIPrintInfo.printInfo()
  117. printInfo.outputType = UIPrintInfo.OutputType.general
  118. printInfo.orientation = UIPrintInfo.Orientation.portrait
  119. printInfo.jobName = "Document"
  120. pic.printInfo = printInfo
  121. pic.printingItem = URL(fileURLWithPath: fileNameLocalPath)
  122. pic.present(from: CGRect.zero, in: self, animated: true, completionHandler: { (pci, completed, error) in
  123. // end.
  124. })
  125. } else {
  126. self.documentInteractionController = UIDocumentInteractionController()
  127. self.documentInteractionController.url = URL(fileURLWithPath: fileNameLocalPath)
  128. self.documentInteractionController.presentOptionsMenu(from: self.appDelegate.window.rootViewController!.view.bounds, in: self.appDelegate.window.rootViewController!.view, animated: true)
  129. }
  130. } else {
  131. NCContentPresenter.shared.messageNotification("_error_", description: message, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  132. }
  133. })
  134. }
  135. } else if param["MessageName"] as? String == "fileRename" {
  136. if let values = param["Values"] as? Dictionary<AnyHashable,Any> {
  137. guard let newName = values["NewName"] as? String else {
  138. return
  139. }
  140. metadata.fileName = newName
  141. metadata.fileNameView = newName
  142. }
  143. }
  144. }
  145. if message.body as? String == "documentLoaded" {
  146. print("documentLoaded")
  147. }
  148. if message.body as? String == "paste" {
  149. self.paste(self)
  150. }
  151. }
  152. }
  153. //MARK: -
  154. @objc func grabFocus() {
  155. let functionJS = "OCA.RichDocuments.documentsMain.postGrabFocus()"
  156. evaluateJavaScript(functionJS) { (result, error) in }
  157. }
  158. //MARK: -
  159. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String) {
  160. if serverUrl != nil && metadata != nil {
  161. OCNetworking.sharedManager().createAssetRichdocuments(withAccount: metadata?.account, fileName: metadata?.fileName, serverUrl: serverUrl, completion: { (account, url, message, errorCode) in
  162. if errorCode == 0 && account == self.appDelegate.activeAccount {
  163. let functionJS = "OCA.RichDocuments.documentsMain.postAsset('\(metadata!.fileNameView)', '\(url!)')"
  164. self.evaluateJavaScript(functionJS, completionHandler: { (result, error) in })
  165. } else if errorCode != 0 {
  166. NCContentPresenter.shared.messageNotification("_error_", description: message, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorInternalError))
  167. } else {
  168. print("[LOG] It has been changed user during networking process, error.")
  169. }
  170. })
  171. }
  172. }
  173. func select(_ metadata: tableMetadata!, serverUrl: String!) {
  174. OCNetworking.sharedManager().createAssetRichdocuments(withAccount: metadata?.account, fileName: metadata?.fileName, serverUrl: serverUrl, completion: { (account, url, message, errorCode) in
  175. if errorCode == 0 && account == self.appDelegate.activeAccount {
  176. let functionJS = "OCA.RichDocuments.documentsMain.postAsset('\(metadata.fileNameView)', '\(url!)')"
  177. self.evaluateJavaScript(functionJS, completionHandler: { (result, error) in })
  178. } else if errorCode != 0 {
  179. NCContentPresenter.shared.messageNotification("_error_", description: message, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorInternalError))
  180. } else {
  181. print("[LOG] It has been changed user during networking process, error.")
  182. }
  183. })
  184. }
  185. //MARK: -
  186. public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  187. if let serverTrust = challenge.protectionSpace.serverTrust {
  188. completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
  189. } else {
  190. completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil);
  191. }
  192. }
  193. public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
  194. print("didStartProvisionalNavigation");
  195. }
  196. public func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
  197. print("didReceiveServerRedirectForProvisionalNavigation");
  198. }
  199. public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
  200. NCUtility.sharedInstance.stopActivityIndicator()
  201. }
  202. }