NCViewerRichdocument.swift 16 KB

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