NCViewerRichdocument.swift 12 KB

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