NCViewerRichdocument.swift 16 KB

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