NCViewerRichdocument.swift 16 KB

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