NCViewerRichDocument.swift 17 KB

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