NCViewerNextcloudText.swift 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. //
  2. // NCViewerNextcloudText.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 12/12/19.
  6. // Copyright © 2019 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 UIKit
  24. import WebKit
  25. class NCViewerNextcloudText: UIViewController, WKNavigationDelegate, WKScriptMessageHandler, WKUIDelegate {
  26. // swiftlint:disable force_cast
  27. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  28. // swiftlint:enable force_cast
  29. var webView = WKWebView()
  30. var bottomConstraint: NSLayoutConstraint?
  31. var link: String = ""
  32. var editor: String = ""
  33. var metadata: tableMetadata = tableMetadata()
  34. var imageIcon: UIImage?
  35. // MARK: - View Life Cycle
  36. required init?(coder: NSCoder) {
  37. super.init(coder: coder)
  38. }
  39. override func viewDidLoad() {
  40. super.viewDidLoad()
  41. if !metadata.ocId.hasPrefix("TEMP") {
  42. navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "more")!.image(color: .label, size: 25), style: .plain, target: self, action: #selector(self.openMenuMore))
  43. }
  44. navigationController?.navigationBar.prefersLargeTitles = false
  45. navigationItem.title = metadata.fileNameView
  46. let config = WKWebViewConfiguration()
  47. config.websiteDataStore = WKWebsiteDataStore.nonPersistent()
  48. let contentController = config.userContentController
  49. contentController.add(self, name: "DirectEditingMobileInterface")
  50. // FIXME: ONLYOFFICE Due to the WK Shared Workers issue the editors cannot be opened on the devices with iOS 16.1.
  51. if editor == NCGlobal.shared.editorOnlyoffice {
  52. let dropSharedWorkersScript = WKUserScript(source: "delete window.SharedWorker;", injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: false)
  53. config.userContentController.addUserScript(dropSharedWorkersScript)
  54. }
  55. webView = WKWebView(frame: CGRect.zero, configuration: config)
  56. webView.navigationDelegate = self
  57. webView.uiDelegate = self
  58. view.addSubview(webView)
  59. webView.translatesAutoresizingMaskIntoConstraints = false
  60. webView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
  61. webView.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor, constant: 0).isActive = true
  62. webView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
  63. bottomConstraint = webView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 70)
  64. bottomConstraint?.isActive = true
  65. var request = URLRequest(url: URL(string: link)!)
  66. request.addValue("true", forHTTPHeaderField: "OCS-APIRequest")
  67. let language = NSLocale.preferredLanguages[0] as String
  68. request.addValue(language, forHTTPHeaderField: "Accept-Language")
  69. if editor == NCGlobal.shared.editorOnlyoffice {
  70. webView.customUserAgent = NCUtility.shared.getCustomUserAgentOnlyOffice()
  71. } else if editor == NCGlobal.shared.editorText {
  72. webView.customUserAgent = NCUtility.shared.getCustomUserAgentNCText()
  73. } // else: use default
  74. webView.load(request)
  75. }
  76. override func viewWillAppear(_ animated: Bool) {
  77. super.viewWillAppear(animated)
  78. appDelegate.activeViewController = self
  79. NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterFavoriteFile), object: nil)
  80. NotificationCenter.default.addObserver(self, selector: #selector(viewUnload), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeUser), object: nil)
  81. NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow), name: UIResponder.keyboardDidShowNotification, object: nil)
  82. NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
  83. }
  84. override func viewWillDisappear(_ animated: Bool) {
  85. super.viewWillDisappear(animated)
  86. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterFavoriteFile), object: nil)
  87. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeUser), object: nil)
  88. NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardDidShowNotification, object: nil)
  89. NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
  90. }
  91. @objc func viewUnload() {
  92. navigationController?.popViewController(animated: true)
  93. }
  94. // MARK: - NotificationCenter
  95. @objc func favoriteFile(_ notification: NSNotification) {
  96. guard let userInfo = notification.userInfo as NSDictionary?,
  97. let ocId = userInfo["ocId"] as? String,
  98. ocId == self.metadata.ocId,
  99. let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId)
  100. else { return }
  101. self.metadata = metadata
  102. }
  103. @objc func keyboardDidShow(notification: Notification) {
  104. guard let info = notification.userInfo else { return }
  105. guard let frameInfo = info[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
  106. let keyboardFrame = frameInfo.cgRectValue
  107. let height = keyboardFrame.size.height
  108. bottomConstraint?.constant = -height
  109. }
  110. @objc func keyboardWillHide(notification: Notification) {
  111. bottomConstraint?.constant = 0
  112. }
  113. // MARK: - Action
  114. @objc func openMenuMore() {
  115. if imageIcon == nil { imageIcon = UIImage(named: "file_txt") }
  116. NCViewer.shared.toggleMenu(viewController: self, metadata: metadata, webView: true, imageIcon: imageIcon)
  117. }
  118. // MARK: -
  119. public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
  120. if message.name == "DirectEditingMobileInterface" {
  121. if message.body as? String == "close" {
  122. viewUnload()
  123. }
  124. if message.body as? String == "share" {
  125. NCActionCenter.shared.openShare(viewController: self, metadata: metadata, page: .sharing)
  126. }
  127. if message.body as? String == "loading" {
  128. print("loading")
  129. }
  130. if message.body as? String == "loaded" {
  131. print("loaded")
  132. }
  133. if message.body as? String == "paste" {
  134. self.paste(self)
  135. }
  136. }
  137. }
  138. // MARK: -
  139. public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  140. DispatchQueue.global().async {
  141. if let serverTrust = challenge.protectionSpace.serverTrust {
  142. completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
  143. } else {
  144. completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil)
  145. }
  146. }
  147. }
  148. public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
  149. print("didStartProvisionalNavigation")
  150. }
  151. public func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
  152. print("didReceiveServerRedirectForProvisionalNavigation")
  153. }
  154. public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
  155. NCActivityIndicator.shared.stop()
  156. }
  157. public func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
  158. if navigationAction.targetFrame == nil {
  159. if let url = navigationAction.request.url, UIApplication.shared.canOpenURL(url) {
  160. UIApplication.shared.open(url)
  161. }
  162. }
  163. return nil
  164. }
  165. }
  166. extension NCViewerNextcloudText: UINavigationControllerDelegate {
  167. override func didMove(toParent parent: UIViewController?) {
  168. super.didMove(toParent: parent)
  169. if parent == nil {
  170. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced)
  171. }
  172. }
  173. }