NCViewerRichdocument.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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 documentInteractionController: 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(deleteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_deleteFile), object: nil)
  39. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_renameFile), object: nil)
  40. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_moveFile), object: nil)
  41. NotificationCenter.default.addObserver(self, selector: #selector(viewUnload), name: NSNotification.Name(rawValue: k_notificationCenter_menuDetailClose), object: nil)
  42. NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow), name: UIResponder.keyboardDidShowNotification, object: nil)
  43. NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
  44. NotificationCenter.default.addObserver(self, selector: #selector(self.grabFocus), name: NSNotification.Name(rawValue: k_notificationCenter_richdocumentGrabFocus), object: nil)
  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.leadingAnchor, constant: 0).isActive = true
  54. webView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
  55. webView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
  56. bottomConstraint = webView.bottomAnchor.constraint(equalTo: view.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 = CCUtility.getUserAgent()
  63. webView.load(request)
  64. }
  65. override func viewWillAppear(_ animated: Bool) {
  66. super.viewWillAppear(animated)
  67. let buttonMore = UIBarButtonItem.init(image: CCGraphics.changeThemingColorImage(UIImage(named: "more"), width: 50, height: 50, color: NCBrandColor.sharedInstance.textView), style: .plain, target: self, action: #selector(self.openMenuMore))
  68. navigationItem.rightBarButtonItem = buttonMore
  69. navigationController?.navigationBar.prefersLargeTitles = true
  70. navigationItem.title = metadata.fileNameView
  71. appDelegate.activeViewController = self
  72. }
  73. @objc func viewUnload() {
  74. navigationController?.popViewController(animated: true)
  75. }
  76. //MARK: - NotificationCenter
  77. @objc func moveFile(_ notification: NSNotification) {
  78. if let userInfo = notification.userInfo as NSDictionary? {
  79. if let metadata = userInfo["metadata"] as? tableMetadata, let metadataNew = userInfo["metadataNew"] as? tableMetadata {
  80. if metadata.ocId == self.metadata.ocId {
  81. self.metadata = metadataNew
  82. }
  83. }
  84. }
  85. }
  86. @objc func deleteFile(_ notification: NSNotification) {
  87. if let userInfo = notification.userInfo as NSDictionary? {
  88. if let metadata = userInfo["metadata"] as? tableMetadata {
  89. if metadata.ocId == self.metadata.ocId {
  90. viewUnload()
  91. }
  92. }
  93. }
  94. }
  95. @objc func renameFile(_ notification: NSNotification) {
  96. if let userInfo = notification.userInfo as NSDictionary? {
  97. if let metadata = userInfo["metadata"] as? tableMetadata {
  98. if metadata.ocId == self.metadata.ocId {
  99. self.metadata = metadata
  100. navigationItem.title = metadata.fileNameView
  101. }
  102. }
  103. }
  104. }
  105. @objc func keyboardDidShow(notification: Notification) {
  106. guard let info = notification.userInfo else { return }
  107. guard let frameInfo = info[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
  108. let keyboardFrame = frameInfo.cgRectValue
  109. let height = keyboardFrame.size.height
  110. bottomConstraint?.constant = -height
  111. }
  112. @objc func keyboardWillHide(notification: Notification) {
  113. bottomConstraint?.constant = 0
  114. }
  115. //MARK: - Action
  116. @objc func openMenuMore() {
  117. NCViewer.shared.toggleMoreMenu(viewController: self, metadata: metadata)
  118. }
  119. //MARK: -
  120. public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
  121. if (message.name == "RichDocumentsMobileInterface") {
  122. if message.body as? String == "close" {
  123. //appDelegate.activeDetail.viewUnload()
  124. appDelegate.activeFiles.reloadDataSourceNetwork()
  125. }
  126. if message.body as? String == "insertGraphic" {
  127. let storyboard = UIStoryboard(name: "NCSelect", bundle: nil)
  128. let navigationController = storyboard.instantiateInitialViewController() as! UINavigationController
  129. let viewController = navigationController.topViewController as! NCSelect
  130. viewController.delegate = self
  131. viewController.hideButtonCreateFolder = true
  132. viewController.selectFile = true
  133. viewController.includeDirectoryE2EEncryption = false
  134. viewController.includeImages = true
  135. viewController.type = ""
  136. navigationController.modalPresentationStyle = UIModalPresentationStyle.fullScreen
  137. self.present(navigationController, animated: true, completion: nil)
  138. }
  139. if message.body as? String == "share" {
  140. NCNetworkingNotificationCenter.shared.openShare(ViewController: self, metadata: metadata, indexPage: 2)
  141. }
  142. if let param = message.body as? Dictionary<AnyHashable,Any> {
  143. if param["MessageName"] as? String == "downloadAs" {
  144. if let values = param["Values"] as? Dictionary<AnyHashable,Any> {
  145. guard let type = values["Type"] as? String else {
  146. return
  147. }
  148. guard let urlString = values["URL"] as? String else {
  149. return
  150. }
  151. guard let url = URL(string: urlString) else {
  152. return
  153. }
  154. guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
  155. return
  156. }
  157. let filename = (components.path as NSString).lastPathComponent
  158. let fileNameLocalPath = CCUtility.getDirectoryUserData() + "/" + filename
  159. if type == "print" {
  160. NCUtility.shared.startActivityIndicator(view: self.view)
  161. }
  162. NCCommunication.shared.download(serverUrlFileName: urlString, fileNameLocalPath: fileNameLocalPath, requestHandler: { (_) in
  163. }, progressHandler: { (_) in
  164. }, completionHandler: { (account, etag, date, lenght, error, errorCode, errorDescription) in
  165. if errorCode == 0 && account == self.metadata.account {
  166. if type == "print" {
  167. NCUtility.shared.stopActivityIndicator()
  168. let pic = UIPrintInteractionController.shared
  169. let printInfo = UIPrintInfo.printInfo()
  170. printInfo.outputType = UIPrintInfo.OutputType.general
  171. printInfo.orientation = UIPrintInfo.Orientation.portrait
  172. printInfo.jobName = "Document"
  173. pic.printInfo = printInfo
  174. pic.printingItem = URL(fileURLWithPath: fileNameLocalPath)
  175. pic.present(from: CGRect.zero, in: self.view, animated: true, completionHandler: { (pci, completed, error) in
  176. // end.
  177. })
  178. } else {
  179. self.documentInteractionController = UIDocumentInteractionController()
  180. self.documentInteractionController.url = URL(fileURLWithPath: fileNameLocalPath)
  181. self.documentInteractionController.presentOptionsMenu(from: self.appDelegate.window.rootViewController!.view.bounds, in: self.appDelegate.window.rootViewController!.view, animated: true)
  182. }
  183. } else {
  184. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  185. }
  186. })
  187. }
  188. } else if param["MessageName"] as? String == "fileRename" {
  189. if let values = param["Values"] as? Dictionary<AnyHashable,Any> {
  190. guard let newName = values["NewName"] as? String else {
  191. return
  192. }
  193. metadata.fileName = newName
  194. metadata.fileNameView = newName
  195. }
  196. } else if param["MessageName"] as? String == "hyperlink" {
  197. if let values = param["Values"] as? Dictionary<AnyHashable,Any> {
  198. guard let urlString = values["Url"] as? String else {
  199. return
  200. }
  201. if let url = URL(string: urlString) {
  202. UIApplication.shared.open(url)
  203. }
  204. }
  205. }
  206. }
  207. if message.body as? String == "documentLoaded" {
  208. print("documentLoaded")
  209. }
  210. if message.body as? String == "paste" {
  211. self.paste(self)
  212. }
  213. }
  214. }
  215. //MARK: -
  216. @objc func grabFocus() {
  217. let functionJS = "OCA.RichDocuments.documentsMain.postGrabFocus()"
  218. webView.evaluateJavaScript(functionJS) { (result, error) in }
  219. }
  220. //MARK: -
  221. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], buttonType: String, overwrite: Bool) {
  222. if serverUrl != nil && metadata != nil {
  223. let path = CCUtility.returnFileNamePath(fromFileName: metadata!.fileName, serverUrl: serverUrl!, urlBase: appDelegate.urlBase, account: metadata!.account)!
  224. NCCommunication.shared.createAssetRichdocuments(path: path) { (account, url, errorCode, errorDescription) in
  225. if errorCode == 0 && account == self.appDelegate.account {
  226. let functionJS = "OCA.RichDocuments.documentsMain.postAsset('\(metadata!.fileNameView)', '\(url!)')"
  227. self.webView.evaluateJavaScript(functionJS, completionHandler: { (result, error) in })
  228. } else if errorCode != 0 {
  229. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorInternalError))
  230. } else {
  231. print("[LOG] It has been changed user during networking process, error.")
  232. }
  233. }
  234. }
  235. }
  236. func select(_ metadata: tableMetadata!, serverUrl: String!) {
  237. let path = CCUtility.returnFileNamePath(fromFileName: metadata!.fileName, serverUrl: serverUrl!, urlBase: appDelegate.urlBase, account: metadata!.account)!
  238. NCCommunication.shared.createAssetRichdocuments(path: path) { (account, url, errorCode, errorDescription) in
  239. if errorCode == 0 && account == self.appDelegate.account {
  240. let functionJS = "OCA.RichDocuments.documentsMain.postAsset('\(metadata.fileNameView)', '\(url!)')"
  241. self.webView.evaluateJavaScript(functionJS, completionHandler: { (result, error) in })
  242. } else if errorCode != 0 {
  243. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorInternalError))
  244. } else {
  245. print("[LOG] It has been changed user during networking process, error.")
  246. }
  247. }
  248. }
  249. //MARK: -
  250. public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  251. if let serverTrust = challenge.protectionSpace.serverTrust {
  252. completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
  253. } else {
  254. completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil);
  255. }
  256. }
  257. public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
  258. print("didStartProvisionalNavigation");
  259. }
  260. public func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
  261. print("didReceiveServerRedirectForProvisionalNavigation");
  262. }
  263. public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
  264. NCUtility.shared.stopActivityIndicator()
  265. }
  266. }