NCViewerRichdocument.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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.activeFiles.reloadDataSourceNetwork()
  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. navigationController.modalPresentationStyle = UIModalPresentationStyle.fullScreen
  90. self.viewController.present(navigationController, animated: true, completion: nil)
  91. }
  92. if message.body as? String == "share" {
  93. NCNetworkingNotificationCenter.shared.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.shared.startActivityIndicator(view: self)
  114. }
  115. NCCommunication.shared.download(serverUrlFileName: urlString, fileNameLocalPath: fileNameLocalPath, requestHandler: { (_) in
  116. }, progressHandler: { (_) in
  117. }, completionHandler: { (account, etag, date, lenght, error, errorCode, errorDescription) in
  118. if errorCode == 0 && account == self.metadata.account {
  119. if type == "print" {
  120. NCUtility.shared.stopActivityIndicator()
  121. let pic = UIPrintInteractionController.shared
  122. let printInfo = UIPrintInfo.printInfo()
  123. printInfo.outputType = UIPrintInfo.OutputType.general
  124. printInfo.orientation = UIPrintInfo.Orientation.portrait
  125. printInfo.jobName = "Document"
  126. pic.printInfo = printInfo
  127. pic.printingItem = URL(fileURLWithPath: fileNameLocalPath)
  128. pic.present(from: CGRect.zero, in: self, animated: true, completionHandler: { (pci, completed, error) in
  129. // end.
  130. })
  131. } else {
  132. self.documentInteractionController = UIDocumentInteractionController()
  133. self.documentInteractionController.url = URL(fileURLWithPath: fileNameLocalPath)
  134. self.documentInteractionController.presentOptionsMenu(from: self.appDelegate.window.rootViewController!.view.bounds, in: self.appDelegate.window.rootViewController!.view, animated: true)
  135. }
  136. } else {
  137. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  138. }
  139. })
  140. }
  141. } else if param["MessageName"] as? String == "fileRename" {
  142. if let values = param["Values"] as? Dictionary<AnyHashable,Any> {
  143. guard let newName = values["NewName"] as? String else {
  144. return
  145. }
  146. metadata.fileName = newName
  147. metadata.fileNameView = newName
  148. }
  149. }
  150. }
  151. if message.body as? String == "documentLoaded" {
  152. print("documentLoaded")
  153. }
  154. if message.body as? String == "paste" {
  155. self.paste(self)
  156. }
  157. if (message.body as? String)?.hasPrefix("HYPERLINK") != nil {
  158. if let messageBodyItem = (message.body as? String)?.components(separatedBy: " ") {
  159. if messageBodyItem.count >= 2 {
  160. let url = URL(fileURLWithPath: messageBodyItem[1])
  161. UIApplication.shared.open(url, options: [:]) { (_) in }
  162. }
  163. }
  164. }
  165. }
  166. }
  167. //MARK: -
  168. @objc func grabFocus() {
  169. let functionJS = "OCA.RichDocuments.documentsMain.postGrabFocus()"
  170. evaluateJavaScript(functionJS) { (result, error) in }
  171. }
  172. //MARK: -
  173. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, array: [Any], buttonType: String, overwrite: Bool) {
  174. if serverUrl != nil && metadata != nil {
  175. let path = CCUtility.returnFileNamePath(fromFileName: metadata!.fileName, serverUrl: serverUrl!, urlBase: appDelegate.urlBase, account: metadata!.account)!
  176. NCCommunication.shared.createAssetRichdocuments(path: path) { (account, url, errorCode, errorDescription) in
  177. if errorCode == 0 && account == self.appDelegate.account {
  178. let functionJS = "OCA.RichDocuments.documentsMain.postAsset('\(metadata!.fileNameView)', '\(url!)')"
  179. self.evaluateJavaScript(functionJS, completionHandler: { (result, error) in })
  180. } else if errorCode != 0 {
  181. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorInternalError))
  182. } else {
  183. print("[LOG] It has been changed user during networking process, error.")
  184. }
  185. }
  186. }
  187. }
  188. func select(_ metadata: tableMetadata!, serverUrl: String!) {
  189. let path = CCUtility.returnFileNamePath(fromFileName: metadata!.fileName, serverUrl: serverUrl!, urlBase: appDelegate.urlBase, account: metadata!.account)!
  190. NCCommunication.shared.createAssetRichdocuments(path: path) { (account, url, errorCode, errorDescription) in
  191. if errorCode == 0 && account == self.appDelegate.account {
  192. let functionJS = "OCA.RichDocuments.documentsMain.postAsset('\(metadata.fileNameView)', '\(url!)')"
  193. self.evaluateJavaScript(functionJS, completionHandler: { (result, error) in })
  194. } else if errorCode != 0 {
  195. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorInternalError))
  196. } else {
  197. print("[LOG] It has been changed user during networking process, error.")
  198. }
  199. }
  200. }
  201. //MARK: -
  202. public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  203. if let serverTrust = challenge.protectionSpace.serverTrust {
  204. completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
  205. } else {
  206. completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil);
  207. }
  208. }
  209. public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
  210. print("didStartProvisionalNavigation");
  211. }
  212. public func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
  213. print("didReceiveServerRedirectForProvisionalNavigation");
  214. }
  215. public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
  216. NCUtility.shared.stopActivityIndicator()
  217. }
  218. }