NCViewerRichdocument.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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.notificationCenterChangeUser), 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.notificationCenterChangeUser), 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. if 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. }
  135. if message.body as? String == "share" {
  136. NCActionCenter.shared.openShare(viewController: self, metadata: metadata, page: .sharing)
  137. }
  138. if let param = message.body as? [AnyHashable: Any] {
  139. if param["MessageName"] as? String == "downloadAs" {
  140. if let values = param["Values"] as? [AnyHashable: Any] {
  141. guard let type = values["Type"] as? String else { return }
  142. guard let urlString = values["URL"] as? String else { return }
  143. guard let url = URL(string: urlString) else { return }
  144. let fileNameLocalPath = NCUtilityFileSystem.shared.directoryUserData + "/" + (metadata.fileName as NSString).deletingPathExtension
  145. if type == "slideshow" {
  146. if let browserWebVC = UIStoryboard(name: "NCBrowserWeb", bundle: nil).instantiateInitialViewController() as? NCBrowserWeb {
  147. browserWebVC.urlBase = urlString
  148. browserWebVC.isHiddenButtonExit = false
  149. self.present(browserWebVC, animated: true)
  150. }
  151. return
  152. } else {
  153. // TYPE PRINT - DOWNLOAD
  154. NCActivityIndicator.shared.start(backgroundView: view)
  155. NextcloudKit.shared.download(serverUrlFileName: url, fileNameLocalPath: fileNameLocalPath, requestHandler: { _ in
  156. }, taskHandler: { _ in
  157. }, progressHandler: { _ in
  158. }, completionHandler: { account, _, _, _, allHeaderFields, _, error in
  159. NCActivityIndicator.shared.stop()
  160. if error == .success && account == self.metadata.account {
  161. var item = fileNameLocalPath
  162. if let allHeaderFields = allHeaderFields {
  163. if let disposition = allHeaderFields["Content-Disposition"] as? String {
  164. let components = disposition.components(separatedBy: "filename=")
  165. if let filename = components.last?.replacingOccurrences(of: "\"", with: "") {
  166. item = NCUtilityFileSystem.shared.directoryUserData + "/" + filename
  167. _ = NCUtilityFileSystem.shared.moveFile(atPath: fileNameLocalPath, toPath: item)
  168. }
  169. }
  170. }
  171. if type == "print" {
  172. let pic = UIPrintInteractionController.shared
  173. let printInfo = UIPrintInfo.printInfo()
  174. printInfo.outputType = UIPrintInfo.OutputType.general
  175. printInfo.orientation = UIPrintInfo.Orientation.portrait
  176. printInfo.jobName = "Document"
  177. pic.printInfo = printInfo
  178. pic.printingItem = URL(fileURLWithPath: item)
  179. pic.present(from: CGRect.zero, in: self.view, animated: true, completionHandler: { _, _, _ in })
  180. } else {
  181. self.documentController = UIDocumentInteractionController()
  182. self.documentController?.url = URL(fileURLWithPath: item)
  183. self.documentController?.presentOptionsMenu(from: CGRect.zero, in: self.view, animated: true)
  184. }
  185. } else {
  186. NCContentPresenter.shared.showError(error: error)
  187. }
  188. })
  189. }
  190. }
  191. } else if param["MessageName"] as? String == "fileRename" {
  192. if let values = param["Values"] as? [AnyHashable: Any] {
  193. guard let newName = values["NewName"] as? String else {
  194. return
  195. }
  196. metadata.fileName = newName
  197. metadata.fileNameView = newName
  198. }
  199. } else if param["MessageName"] as? String == "hyperlink" {
  200. if let values = param["Values"] as? [AnyHashable: Any] {
  201. guard let urlString = values["Url"] as? String else {
  202. return
  203. }
  204. if let url = URL(string: urlString) {
  205. UIApplication.shared.open(url)
  206. }
  207. }
  208. }
  209. }
  210. if message.body as? String == "documentLoaded" {
  211. print("documentLoaded")
  212. }
  213. if message.body as? String == "paste" {
  214. // ?
  215. }
  216. }
  217. }
  218. // MARK: -
  219. @objc func grabFocus() {
  220. let functionJS = "OCA.RichDocuments.documentsMain.postGrabFocus()"
  221. webView.evaluateJavaScript(functionJS) { _, _ in }
  222. }
  223. // MARK: -
  224. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], indexPath: [IndexPath], overwrite: Bool, copy: Bool, move: Bool) {
  225. if serverUrl != nil && metadata != nil {
  226. let path = CCUtility.returnFileNamePath(fromFileName: metadata!.fileName, serverUrl: serverUrl!, urlBase: appDelegate.urlBase, userId: appDelegate.userId, account: metadata!.account)!
  227. NextcloudKit.shared.createAssetRichdocuments(path: path) { account, url, _, error in
  228. if error == .success && account == self.appDelegate.account {
  229. let functionJS = "OCA.RichDocuments.documentsMain.postAsset('\(metadata!.fileNameView)', '\(url!)')"
  230. self.webView.evaluateJavaScript(functionJS, completionHandler: { _, _ in })
  231. } else if error != .success {
  232. NCContentPresenter.shared.showError(error: error)
  233. } else {
  234. print("[LOG] It has been changed user during networking process, error.")
  235. }
  236. }
  237. }
  238. }
  239. func select(_ metadata: tableMetadata!, serverUrl: String!) {
  240. let path = CCUtility.returnFileNamePath(fromFileName: metadata!.fileName, serverUrl: serverUrl!, urlBase: appDelegate.urlBase, userId: appDelegate.userId, account: metadata!.account)!
  241. NextcloudKit.shared.createAssetRichdocuments(path: path) { account, url, _, error in
  242. if error == .success && account == self.appDelegate.account {
  243. let functionJS = "OCA.RichDocuments.documentsMain.postAsset('\(metadata.fileNameView)', '\(url!)')"
  244. self.webView.evaluateJavaScript(functionJS, completionHandler: { _, _ in })
  245. } else if error != .success {
  246. NCContentPresenter.shared.showError(error: error)
  247. } else {
  248. print("[LOG] It has been changed user during networking process, error.")
  249. }
  250. }
  251. }
  252. // MARK: -
  253. public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  254. DispatchQueue.global().async {
  255. if let serverTrust = challenge.protectionSpace.serverTrust {
  256. completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
  257. } else {
  258. completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil)
  259. }
  260. }
  261. }
  262. public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
  263. print("didStartProvisionalNavigation")
  264. }
  265. public func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
  266. print("didReceiveServerRedirectForProvisionalNavigation")
  267. }
  268. public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
  269. NCActivityIndicator.shared.stop()
  270. }
  271. }
  272. extension NCViewerRichdocument: UINavigationControllerDelegate {
  273. override func didMove(toParent parent: UIViewController?) {
  274. super.didMove(toParent: parent)
  275. if parent == nil {
  276. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced)
  277. }
  278. }
  279. }