NCViewerRichdocument.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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 { return }
  99. guard let urlString = values["URL"] as? String else { return }
  100. guard let url = URL(string: urlString) else { return }
  101. let fileNameLocalPath = CCUtility.getDirectoryUserData() + "/" + metadata.fileNameWithoutExt
  102. NCUtility.shared.startActivityIndicator(view: self)
  103. NCCommunication.shared.download(serverUrlFileName: url, fileNameLocalPath: fileNameLocalPath, requestHandler: { (_) in
  104. }, progressHandler: { (_) in
  105. }, completionHandler: { (account, etag, date, lenght, allHeaderFields, error, errorCode, errorDescription) in
  106. NCUtility.shared.stopActivityIndicator()
  107. if errorCode == 0 && account == self.metadata.account {
  108. var item = fileNameLocalPath
  109. if let allHeaderFields = allHeaderFields {
  110. if let disposition = allHeaderFields["Content-Disposition"] as? String {
  111. let components = disposition.components(separatedBy: "filename=")
  112. if let filename = components.last?.replacingOccurrences(of: "\"", with: "") {
  113. item = CCUtility.getDirectoryUserData() + "/" + filename
  114. NCUtilityFileSystem.shared.moveFile(atPath: fileNameLocalPath, toPath: item)
  115. }
  116. }
  117. }
  118. if type == "print" {
  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: item)
  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: item)
  132. self.documentInteractionController.presentOptionsMenu(from: CGRect.zero, in: self.appDelegate.window.rootViewController!.view, animated: true)
  133. }
  134. } else {
  135. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, 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. } else if param["MessageName"] as? String == "hyperlink" {
  148. if let values = param["Values"] as? Dictionary<AnyHashable,Any> {
  149. guard let urlString = values["Url"] as? String else {
  150. return
  151. }
  152. if let url = URL(string: urlString) {
  153. UIApplication.shared.open(url)
  154. }
  155. }
  156. }
  157. }
  158. if message.body as? String == "documentLoaded" {
  159. print("documentLoaded")
  160. }
  161. if message.body as? String == "paste" {
  162. self.paste(self)
  163. }
  164. }
  165. }
  166. //MARK: -
  167. @objc func grabFocus() {
  168. let functionJS = "OCA.RichDocuments.documentsMain.postGrabFocus()"
  169. evaluateJavaScript(functionJS) { (result, error) in }
  170. }
  171. //MARK: -
  172. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], buttonType: String, overwrite: Bool) {
  173. if serverUrl != nil && metadata != nil {
  174. let path = CCUtility.returnFileNamePath(fromFileName: metadata!.fileName, serverUrl: serverUrl!, urlBase: appDelegate.urlBase, account: metadata!.account)!
  175. NCCommunication.shared.createAssetRichdocuments(path: path) { (account, url, errorCode, errorDescription) in
  176. if errorCode == 0 && account == self.appDelegate.account {
  177. let functionJS = "OCA.RichDocuments.documentsMain.postAsset('\(metadata!.fileNameView)', '\(url!)')"
  178. self.evaluateJavaScript(functionJS, completionHandler: { (result, error) in })
  179. } else if errorCode != 0 {
  180. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorInternalError))
  181. } else {
  182. print("[LOG] It has been changed user during networking process, error.")
  183. }
  184. }
  185. }
  186. }
  187. func select(_ metadata: tableMetadata!, serverUrl: String!) {
  188. let path = CCUtility.returnFileNamePath(fromFileName: metadata!.fileName, serverUrl: serverUrl!, urlBase: appDelegate.urlBase, account: metadata!.account)!
  189. NCCommunication.shared.createAssetRichdocuments(path: path) { (account, url, errorCode, errorDescription) in
  190. if errorCode == 0 && account == self.appDelegate.account {
  191. let functionJS = "OCA.RichDocuments.documentsMain.postAsset('\(metadata.fileNameView)', '\(url!)')"
  192. self.evaluateJavaScript(functionJS, completionHandler: { (result, error) in })
  193. } else if errorCode != 0 {
  194. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorInternalError))
  195. } else {
  196. print("[LOG] It has been changed user during networking process, error.")
  197. }
  198. }
  199. }
  200. //MARK: -
  201. public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  202. if let serverTrust = challenge.protectionSpace.serverTrust {
  203. completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
  204. } else {
  205. completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil);
  206. }
  207. }
  208. public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
  209. print("didStartProvisionalNavigation");
  210. }
  211. public func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
  212. print("didReceiveServerRedirectForProvisionalNavigation");
  213. }
  214. public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
  215. NCUtility.shared.stopActivityIndicator()
  216. }
  217. }