NCViewerDocumentWeb.swift 6.3 KB

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