NCViewerRichdocument.swift 17 KB

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