NCViewerRichDocument.swift 17 KB

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