NCViewerNextcloudText.swift 9.5 KB

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