NCViewerDocumentWeb.swift 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. //
  2. // NCViewerDocumentWeb.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 28/09/2018.
  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 NCViewerDocumentWeb: NSObject {
  25. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  26. var safeAreaBottom: Int = 0
  27. var mimeType: String?
  28. @objc static let sharedInstance: NCViewerDocumentWeb = {
  29. let instance = NCViewerDocumentWeb()
  30. return instance
  31. }()
  32. @objc func viewDocumentWebAt(_ metadata: tableMetadata, detail: CCDetail) {
  33. if !CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) { return }
  34. if #available(iOS 11.0, *) {
  35. safeAreaBottom = Int((UIApplication.shared.keyWindow?.safeAreaInsets.bottom)!)
  36. }
  37. let fileNamePath = NSTemporaryDirectory() + metadata.fileNameView
  38. let fileNameExtension = (metadata.fileNameView as NSString).pathExtension.uppercased()
  39. CCUtility.copyFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView), toPath: fileNamePath)
  40. let url = URL.init(fileURLWithPath: fileNamePath)
  41. let preferences = WKPreferences()
  42. let configuration = WKWebViewConfiguration()
  43. preferences.javaScriptEnabled = false
  44. // Detect file xls, xlss for enable javascript
  45. if fileNameExtension == "XLS" || fileNameExtension == "XLSX" {
  46. if let fileHandle = FileHandle(forReadingAtPath: fileNamePath) {
  47. let data = fileHandle.readData(ofLength: 4)
  48. if data.starts(with: [0x50, 0x4b, 0x03, 0x04]) { // "PK\003\004"
  49. preferences.javaScriptEnabled = true
  50. }
  51. fileHandle.closeFile()
  52. }
  53. }
  54. configuration.preferences = preferences
  55. let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: Int(detail.view.bounds.size.width), height: Int(detail.view.bounds.size.height) - Int(k_detail_Toolbar_Height) - safeAreaBottom - 1), configuration: configuration)
  56. webView.navigationDelegate = self
  57. webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  58. webView.backgroundColor = .white
  59. webView.isOpaque = false
  60. if fileNameExtension == "CSS" || fileNameExtension == "PY" || fileNameExtension == "XML" || fileNameExtension == "JS" {
  61. do {
  62. let dataFile = try String(contentsOf: url, encoding: String.Encoding(rawValue: String.Encoding.ascii.rawValue))
  63. if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.phone {
  64. webView.loadHTMLString("<div style='font-size:40;font-family:Sans-Serif;'><pre>" + dataFile, baseURL: nil)
  65. } else {
  66. webView.loadHTMLString("<div style='font-size:20;font-family:Sans-Serif;'><pre>" + dataFile, baseURL: nil)
  67. }
  68. } catch {
  69. print("error")
  70. }
  71. } else if CCUtility.isDocumentModifiableExtension(fileNameExtension) {
  72. let session = URLSession(configuration: URLSessionConfiguration.default)
  73. var request = URLRequest(url: url)
  74. request.httpMethod = "HEAD"
  75. let task = session.dataTask(with: request) { (data, response, error) in
  76. guard let data = data else {
  77. return
  78. }
  79. guard let response = response else {
  80. return
  81. }
  82. DispatchQueue.main.async {
  83. guard let encodingName = NCUchardet.sharedNUCharDet()?.encodingStringDetect(with: data) else {
  84. return
  85. }
  86. self.mimeType = response.mimeType
  87. webView.load(data, mimeType: response.mimeType!, characterEncodingName: encodingName, baseURL: url)
  88. }
  89. }
  90. task.resume()
  91. } else {
  92. webView.load(URLRequest(url: url))
  93. }
  94. detail.view.addSubview(webView)
  95. }
  96. }
  97. extension NCViewerDocumentWeb: WKNavigationDelegate {
  98. public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  99. if let serverTrust = challenge.protectionSpace.serverTrust {
  100. completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
  101. } else {
  102. completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil);
  103. }
  104. }
  105. public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
  106. decisionHandler(.allow)
  107. }
  108. public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
  109. print("didStartProvisionalNavigation");
  110. }
  111. public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
  112. if self.mimeType != nil && self.mimeType == "text/plain" && CCUtility.getDarkMode() {
  113. let js = "document.getElementsByTagName('body')[0].style.webkitTextFillColor= 'white';DOMReady();"
  114. webView.evaluateJavaScript(js) { (_, _) in }
  115. }
  116. }
  117. public func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
  118. print("didReceiveServerRedirectForProvisionalNavigation");
  119. }
  120. }