NCViewerRichdocument.swift 13 KB

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