NCViewerRichDocument.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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 UIKit
  24. @preconcurrency import WebKit
  25. import NextcloudKit
  26. class NCViewerRichDocument: UIViewController, WKNavigationDelegate, WKScriptMessageHandler, NCSelectDelegate {
  27. let utilityFileSystem = NCUtilityFileSystem()
  28. var webView = WKWebView()
  29. var bottomConstraint: NSLayoutConstraint?
  30. var documentController: UIDocumentInteractionController?
  31. var link: String = ""
  32. var metadata: tableMetadata = tableMetadata()
  33. var imageIcon: UIImage?
  34. var session: NCSession.Session {
  35. NCSession.shared.getSession(account: metadata.account)
  36. }
  37. // MARK: - View Life Cycle
  38. required init?(coder: NSCoder) {
  39. super.init(coder: coder)
  40. }
  41. override func viewDidLoad() {
  42. super.viewDidLoad()
  43. if !metadata.ocId.hasPrefix("TEMP") {
  44. navigationItem.rightBarButtonItem = UIBarButtonItem(image: NCImageCache.shared.getImageButtonMore(), style: .plain, target: self, action: #selector(self.openMenuMore))
  45. }
  46. navigationController?.navigationBar.prefersLargeTitles = false
  47. navigationItem.title = metadata.fileNameView
  48. let config = WKWebViewConfiguration()
  49. config.websiteDataStore = WKWebsiteDataStore.nonPersistent()
  50. let contentController = config.userContentController
  51. contentController.add(self, name: "RichDocumentsMobileInterface")
  52. webView = WKWebView(frame: CGRect.zero, configuration: config)
  53. webView.navigationDelegate = self
  54. view.addSubview(webView)
  55. webView.translatesAutoresizingMaskIntoConstraints = false
  56. webView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
  57. webView.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor, constant: 0).isActive = true
  58. webView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
  59. bottomConstraint = webView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 0)
  60. bottomConstraint?.isActive = true
  61. var request = URLRequest(url: URL(string: link)!)
  62. request.addValue("true", forHTTPHeaderField: "OCS-APIRequest")
  63. let language = NSLocale.preferredLanguages[0] as String
  64. request.addValue(language, forHTTPHeaderField: "Accept-Language")
  65. webView.customUserAgent = userAgent
  66. webView.load(request)
  67. }
  68. deinit {
  69. print("dealloc")
  70. }
  71. override func viewWillAppear(_ animated: Bool) {
  72. super.viewWillAppear(animated)
  73. NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterFavoriteFile), object: nil)
  74. NotificationCenter.default.addObserver(self, selector: #selector(viewUnload), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeUser), object: nil)
  75. NotificationCenter.default.addObserver(self, selector: #selector(self.grabFocus), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRichdocumentGrabFocus), object: nil)
  76. NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow), name: UIResponder.keyboardDidShowNotification, object: nil)
  77. NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
  78. }
  79. override func viewDidAppear(_ animated: Bool) {
  80. super.viewDidAppear(animated)
  81. NCActivityIndicator.shared.start(backgroundView: view)
  82. }
  83. override func viewWillDisappear(_ animated: Bool) {
  84. super.viewWillDisappear(animated)
  85. if let navigationController = self.navigationController {
  86. if !navigationController.viewControllers.contains(self) {
  87. let functionJS = "OCA.RichDocuments.documentsMain.onClose()"
  88. webView.evaluateJavaScript(functionJS) { _, _ in
  89. print("close")
  90. }
  91. }
  92. }
  93. webView.configuration.userContentController.removeScriptMessageHandler(forName: "RichDocumentsMobileInterface")
  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: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRichdocumentGrabFocus), object: nil)
  97. NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardDidShowNotification, object: nil)
  98. NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
  99. }
  100. @objc func viewUnload() {
  101. navigationController?.popViewController(animated: true)
  102. }
  103. // MARK: - NotificationCenter
  104. @objc func favoriteFile(_ notification: NSNotification) {
  105. guard let userInfo = notification.userInfo as NSDictionary?,
  106. let ocId = userInfo["ocId"] as? String,
  107. ocId == self.metadata.ocId,
  108. let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId)
  109. else { return }
  110. self.metadata = metadata
  111. }
  112. @objc func keyboardDidShow(notification: Notification) {
  113. guard let info = notification.userInfo else { return }
  114. guard let frameInfo = info[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
  115. let keyboardFrame = frameInfo.cgRectValue
  116. let height = keyboardFrame.size.height
  117. bottomConstraint?.constant = -height
  118. }
  119. @objc func keyboardWillHide(notification: Notification) {
  120. bottomConstraint?.constant = 0
  121. }
  122. // MARK: - Action
  123. @objc func openMenuMore() {
  124. if imageIcon == nil { imageIcon = NCUtility().loadImage(named: "doc.text", colors: [NCBrandColor.shared.iconImageColor]) }
  125. NCViewer().toggleMenu(controller: self.tabBarController as? NCMainTabBarController, metadata: metadata, webView: true, imageIcon: imageIcon)
  126. }
  127. // MARK: -
  128. public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
  129. if message.name == "RichDocumentsMobileInterface" {
  130. if message.body as? String == "close" {
  131. viewUnload()
  132. }
  133. if message.body as? String == "insertGraphic" {
  134. let storyboard = UIStoryboard(name: "NCSelect", bundle: nil)
  135. if let navigationController = storyboard.instantiateInitialViewController() as? UINavigationController,
  136. let viewController = navigationController.topViewController as? NCSelect {
  137. viewController.delegate = self
  138. viewController.typeOfCommandView = .select
  139. viewController.enableSelectFile = true
  140. viewController.includeImages = true
  141. viewController.type = ""
  142. viewController.session = session
  143. self.present(navigationController, animated: true, completion: nil)
  144. }
  145. }
  146. if message.body as? String == "share" {
  147. NCActionCenter.shared.openShare(viewController: self, metadata: metadata, page: .sharing)
  148. }
  149. if let param = message.body as? [AnyHashable: Any] {
  150. if param["MessageName"] as? String == "downloadAs" {
  151. if let values = param["Values"] as? [AnyHashable: Any] {
  152. guard let type = values["Type"] as? String else { return }
  153. guard let urlString = values["URL"] as? String else { return }
  154. guard let url = URL(string: urlString) else { return }
  155. let fileNameLocalPath = utilityFileSystem.directoryUserData + "/" + (metadata.fileName as NSString).deletingPathExtension
  156. if type == "slideshow" {
  157. if let browserWebVC = UIStoryboard(name: "NCBrowserWeb", bundle: nil).instantiateInitialViewController() as? NCBrowserWeb {
  158. browserWebVC.urlBase = urlString
  159. browserWebVC.isHiddenButtonExit = false
  160. self.present(browserWebVC, animated: true)
  161. }
  162. return
  163. } else {
  164. // TYPE PRINT - DOWNLOAD
  165. NCActivityIndicator.shared.start(backgroundView: view)
  166. NextcloudKit.shared.download(serverUrlFileName: url, fileNameLocalPath: fileNameLocalPath, account: self.metadata.account, requestHandler: { _ in
  167. }, taskHandler: { _ in
  168. }, progressHandler: { _ in
  169. }, completionHandler: { account, _, _, _, responseData, _, error in
  170. NCActivityIndicator.shared.stop()
  171. if error == .success && account == self.metadata.account {
  172. var item = fileNameLocalPath
  173. if let allHeaderFields = responseData?.response?.allHeaderFields {
  174. if let disposition = allHeaderFields["Content-Disposition"] as? String {
  175. let components = disposition.components(separatedBy: "filename=")
  176. if let filename = components.last?.replacingOccurrences(of: "\"", with: "") {
  177. item = self.utilityFileSystem.directoryUserData + "/" + filename
  178. _ = self.utilityFileSystem.moveFile(atPath: fileNameLocalPath, toPath: item)
  179. }
  180. }
  181. }
  182. if type == "print" {
  183. let pic = UIPrintInteractionController.shared
  184. let printInfo = UIPrintInfo.printInfo()
  185. printInfo.outputType = UIPrintInfo.OutputType.general
  186. printInfo.orientation = UIPrintInfo.Orientation.portrait
  187. printInfo.jobName = "Document"
  188. pic.printInfo = printInfo
  189. pic.printingItem = URL(fileURLWithPath: item)
  190. pic.present(from: CGRect.zero, in: self.view, animated: true, completionHandler: { _, _, _ in })
  191. } else {
  192. self.documentController = UIDocumentInteractionController()
  193. self.documentController?.url = URL(fileURLWithPath: item)
  194. self.documentController?.presentOptionsMenu(from: CGRect.zero, in: self.view, animated: true)
  195. }
  196. } else {
  197. NCContentPresenter().showError(error: error)
  198. }
  199. })
  200. }
  201. }
  202. } else if param["MessageName"] as? String == "fileRename" {
  203. if let values = param["Values"] as? [AnyHashable: Any] {
  204. guard let newName = values["NewName"] as? String else {
  205. return
  206. }
  207. metadata.fileName = newName
  208. metadata.fileNameView = newName
  209. }
  210. } else if param["MessageName"] as? String == "hyperlink" {
  211. if let values = param["Values"] as? [AnyHashable: Any] {
  212. guard let urlString = values["Url"] as? String else {
  213. return
  214. }
  215. if let url = URL(string: urlString) {
  216. UIApplication.shared.open(url)
  217. }
  218. }
  219. }
  220. }
  221. if message.body as? String == "documentLoaded" {
  222. print("documentLoaded")
  223. }
  224. if message.body as? String == "paste" {
  225. // ?
  226. }
  227. }
  228. }
  229. // MARK: -
  230. @objc func grabFocus() {
  231. let functionJS = "OCA.RichDocuments.documentsMain.postGrabFocus()"
  232. webView.evaluateJavaScript(functionJS) { _, _ in }
  233. }
  234. // MARK: -
  235. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool, session: NCSession.Session) {
  236. if let serverUrl, let metadata {
  237. let path = utilityFileSystem.getFileNamePath(metadata.fileName, serverUrl: serverUrl, session: session)
  238. NextcloudKit.shared.createAssetRichdocuments(path: path, account: metadata.account) { _, url, _, error in
  239. if error == .success, let url {
  240. let functionJS = "OCA.RichDocuments.documentsMain.postAsset('\(metadata.fileNameView)', '\(url)')"
  241. self.webView.evaluateJavaScript(functionJS, completionHandler: { _, _ in })
  242. } else {
  243. NCContentPresenter().showError(error: error)
  244. }
  245. }
  246. }
  247. }
  248. func select(_ metadata: tableMetadata!, serverUrl: String!) {
  249. let path = utilityFileSystem.getFileNamePath(metadata!.fileName, serverUrl: serverUrl!, session: session)
  250. NextcloudKit.shared.createAssetRichdocuments(path: path, account: metadata.account) { _, url, _, error in
  251. if error == .success, let url {
  252. let functionJS = "OCA.RichDocuments.documentsMain.postAsset('\(metadata.fileNameView)', '\(url)')"
  253. self.webView.evaluateJavaScript(functionJS, completionHandler: { _, _ in })
  254. } else {
  255. NCContentPresenter().showError(error: error)
  256. }
  257. }
  258. }
  259. // MARK: -
  260. public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  261. DispatchQueue.global().async {
  262. if let serverTrust = challenge.protectionSpace.serverTrust {
  263. completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
  264. } else {
  265. completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil)
  266. }
  267. }
  268. }
  269. public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
  270. print("didStartProvisionalNavigation")
  271. }
  272. public func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
  273. print("didReceiveServerRedirectForProvisionalNavigation")
  274. }
  275. public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
  276. NCActivityIndicator.shared.stop()
  277. }
  278. }
  279. extension NCViewerRichDocument: UINavigationControllerDelegate {
  280. override func didMove(toParent parent: UIViewController?) {
  281. super.didMove(toParent: parent)
  282. if parent == nil {
  283. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSource, userInfo: ["serverUrl": self.metadata.serverUrl])
  284. }
  285. }
  286. }