NCViewerRichdocument.swift 16 KB

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