NCViewerRichdocument.swift 16 KB

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