NCDetailViewController.swift 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  1. //
  2. // NCDetailViewController.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 07/02/2020.
  6. // Copyright © 2020 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 NCDetailViewController: UIViewController {
  27. @IBOutlet weak var backgroundView: UIImageView!
  28. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  29. @objc var isNavigationBarHidden = false
  30. @objc var metadata: tableMetadata?
  31. @objc var selector: String?
  32. @objc var favoriteFilterImage: Bool = false
  33. @objc var mediaFilterImage: Bool = false
  34. @objc var offlineFilterImage: Bool = false
  35. @objc var viewerImageViewController: NCViewerImageViewController?
  36. @objc var metadatas = [tableMetadata]()
  37. private let progressHeight: CGFloat = 1.5
  38. private var maxProgress: Float = 0
  39. private var videoLayer: AVPlayerLayer?
  40. private var viewerImageViewControllerLongPressInProgress = false
  41. private var viewerQuickLook: NCViewerQuickLook?
  42. //MARK: -
  43. required init?(coder: NSCoder) {
  44. super.init(coder: coder)
  45. appDelegate.activeDetail = self
  46. }
  47. override func viewDidLoad() {
  48. super.viewDidLoad()
  49. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: k_notificationCenter_changeTheming), object: nil)
  50. NotificationCenter.default.addObserver(self, selector: #selector(changeDisplayMode), name: NSNotification.Name(rawValue: k_notificationCenter_splitViewChangeDisplayMode), object: nil)
  51. NotificationCenter.default.addObserver(self, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadedFile), object: nil)
  52. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadedFile), object: nil)
  53. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_deleteFile), object: nil)
  54. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_renameFile), object: nil)
  55. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_moveFile), object: nil)
  56. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_progressTask), object:nil)
  57. NotificationCenter.default.addObserver(self, selector: #selector(synchronizationMedia(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_synchronizationMedia), object: nil)
  58. NotificationCenter.default.addObserver(self, selector: #selector(downloadImage(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_menuDownloadImage), object: nil)
  59. NotificationCenter.default.addObserver(self, selector: #selector(saveLivePhoto(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_menuSaveLivePhoto), object: nil)
  60. NotificationCenter.default.addObserver(self, selector: #selector(viewUnload), name: NSNotification.Name(rawValue: k_notificationCenter_menuDetailClose), object: nil)
  61. changeTheming()
  62. if metadata != nil {
  63. viewFile(metadata: metadata!, selector: selector)
  64. }
  65. }
  66. override func viewWillAppear(_ animated: Bool) {
  67. super.viewWillAppear(animated)
  68. setProgressBar()
  69. navigateControllerBarHidden(isNavigationBarHidden)
  70. }
  71. override func viewDidDisappear(_ animated: Bool) {
  72. super.viewDidDisappear(animated)
  73. if appDelegate.player != nil && appDelegate.player.rate != 0 {
  74. appDelegate.player.pause()
  75. }
  76. if appDelegate.isMediaObserver {
  77. appDelegate.isMediaObserver = false
  78. NCViewerVideo.sharedInstance.removeObserver()
  79. }
  80. }
  81. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  82. super.viewWillTransition(to: size, with: coordinator)
  83. coordinator.animate(alongsideTransition: nil) { _ in
  84. self.setProgressBar()
  85. }
  86. }
  87. //MARK: - ProgressBar
  88. @objc func setProgressBar() {
  89. appDelegate.progressViewDetail.removeFromSuperview()
  90. guard let navigationController = splitViewController?.viewControllers.last as? UINavigationController else { return }
  91. appDelegate.progressViewDetail.frame = CGRect(x: 0, y: navigationController.navigationBar.frame.height - (progressHeight*2), width: navigationController.navigationBar.frame.width, height: progressHeight)
  92. progress(0)
  93. if NCBrandColor.sharedInstance.brand.isLight() {
  94. appDelegate.progressViewDetail.tintColor = NCBrandColor.sharedInstance.brand.darker(by: 10)
  95. } else {
  96. appDelegate.progressViewDetail.tintColor = NCBrandColor.sharedInstance.brand.lighter(by: 20)
  97. }
  98. appDelegate.progressViewDetail.trackTintColor = .clear
  99. appDelegate.progressViewDetail.transform = CGAffineTransform(scaleX: 1, y: progressHeight)
  100. navigationController.navigationBar.addSubview(appDelegate.progressViewDetail)
  101. }
  102. @objc func progress(_ progress: Float) {
  103. DispatchQueue.main.async {
  104. if progress == 0 {
  105. self.maxProgress = 0
  106. self.appDelegate.progressViewDetail.progress = 0
  107. } else if progress > self.maxProgress {
  108. self.appDelegate.progressViewDetail.progress = progress
  109. self.maxProgress = progress
  110. }
  111. }
  112. }
  113. override var preferredStatusBarStyle: UIStatusBarStyle {
  114. if isNavigationBarHidden {
  115. return .lightContent
  116. } else {
  117. return .default
  118. }
  119. }
  120. //MARK: - Utility
  121. @objc func navigateControllerBarHidden(_ state: Bool) {
  122. if state {
  123. view.backgroundColor = .black
  124. } else {
  125. view.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  126. }
  127. navigationController?.setNavigationBarHidden(state, animated: false)
  128. isNavigationBarHidden = state
  129. self.setNeedsStatusBarAppearanceUpdate()
  130. }
  131. //MARK: - NotificationCenter
  132. @objc func changeTheming() {
  133. appDelegate.changeTheming(self, tableView: nil, collectionView: nil, form: false)
  134. if backgroundView.image != nil {
  135. backgroundView.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "logo"), multiplier: 2, color: NCBrandColor.sharedInstance.brand.withAlphaComponent(0.4))
  136. }
  137. if navigationController?.isNavigationBarHidden == false {
  138. view.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  139. }
  140. }
  141. @objc func changeDisplayMode() {
  142. if self.view?.window == nil { return }
  143. NCViewerImageCommon.shared.imageChangeSizeView(viewerImageViewController: viewerImageViewController, size: self.backgroundView.frame.size, metadata: metadata)
  144. DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) {
  145. self.setProgressBar()
  146. }
  147. }
  148. @objc func triggerProgressTask(_ notification: NSNotification) {
  149. if self.view?.window == nil { return }
  150. guard let metadata = self.metadata else { return }
  151. if let userInfo = notification.userInfo as NSDictionary? {
  152. if let account = userInfo["account"] as? String, let serverUrl = userInfo["serverUrl"] as? String, let progress = userInfo["progress"] as? Float {
  153. if account == metadata.account && serverUrl == metadata.serverUrl {
  154. self.progress(progress)
  155. }
  156. }
  157. }
  158. }
  159. @objc func synchronizationMedia(_ notification: NSNotification) {
  160. if self.view?.window == nil { return }
  161. if let userInfo = notification.userInfo as NSDictionary? {
  162. if let type = userInfo["type"] as? String {
  163. if (self.metadata?.typeFile == k_metadataTypeFile_image || self.metadata?.typeFile == k_metadataTypeFile_video || self.metadata?.typeFile == k_metadataTypeFile_audio) && self.mediaFilterImage {
  164. if let metadatas = appDelegate.activeMedia.sectionDatasource.metadatas as? [tableMetadata] {
  165. self.metadatas = metadatas
  166. }
  167. if type == "delete" {
  168. if metadatas.count > 0 {
  169. var index = viewerImageViewController!.index - 1
  170. if index < 0 { index = 0}
  171. self.metadata = metadatas[index]
  172. viewImage()
  173. } else {
  174. viewUnload()
  175. }
  176. }
  177. if type == "rename" || type == "move" {
  178. viewerImageViewController?.reloadContentViews()
  179. }
  180. }
  181. }
  182. }
  183. }
  184. @objc func moveFile(_ notification: NSNotification) {
  185. if self.view?.window == nil { return }
  186. if let userInfo = notification.userInfo as NSDictionary? {
  187. if let metadata = userInfo["metadata"] as? tableMetadata, let metadataNew = userInfo["metadataNew"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int, let errorDescription = userInfo["errorDescription"] as? String {
  188. if metadata.account != self.metadata?.account { return }
  189. if errorCode == 0 {
  190. // IMAGE
  191. if (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) && !mediaFilterImage {
  192. deleteFile(notification)
  193. }
  194. // OTHER
  195. if (metadata.typeFile == k_metadataTypeFile_document || metadata.typeFile == k_metadataTypeFile_unknown) && metadataNew.ocId == self.metadata?.ocId {
  196. self.metadata = metadataNew
  197. // update subview
  198. for view in backgroundView.subviews {
  199. if view is NCViewerNextcloudText {
  200. (view as! NCViewerNextcloudText).metadata = self.metadata
  201. }
  202. else if view is NCViewerRichdocument {
  203. (view as! NCViewerRichdocument).metadata = self.metadata
  204. }
  205. }
  206. }
  207. } else {
  208. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  209. }
  210. }
  211. }
  212. }
  213. @objc func deleteFile(_ notification: NSNotification) {
  214. if self.view?.window == nil { return }
  215. if let userInfo = notification.userInfo as NSDictionary? {
  216. if let metadata = userInfo["metadata"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int, let errorDescription = userInfo["errorDescription"] as? String{
  217. if metadata.account != self.metadata?.account || metadata.serverUrl != self.metadata?.serverUrl { return }
  218. if errorCode == 0 {
  219. // IMAGE
  220. if (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) && !mediaFilterImage {
  221. if let metadatas = NCViewerImageCommon.shared.getMetadatasDatasource(metadata: self.metadata, metadatas: self.metadatas, favoriteDatasorce: favoriteFilterImage, mediaDatasorce: mediaFilterImage, offLineDatasource: offlineFilterImage) {
  222. var index = viewerImageViewController!.index - 1
  223. if index < 0 { index = 0}
  224. self.metadata = metadatas[index]
  225. viewImage()
  226. } else {
  227. viewUnload()
  228. }
  229. }
  230. // OTHER
  231. if (metadata.typeFile == k_metadataTypeFile_document || metadata.typeFile == k_metadataTypeFile_unknown) && metadata.ocId == self.metadata?.ocId {
  232. viewUnload()
  233. }
  234. } else {
  235. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  236. }
  237. }
  238. }
  239. }
  240. @objc func renameFile(_ notification: NSNotification) {
  241. if self.view?.window == nil { return }
  242. if let userInfo = notification.userInfo as NSDictionary? {
  243. if let metadata = userInfo["metadata"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int, let errorDescription = userInfo["errorDescription"] as? String {
  244. if metadata.account != self.metadata?.account || metadata.serverUrl != self.metadata?.serverUrl { return }
  245. if errorCode == 0 {
  246. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId)) {
  247. self.metadata = metadata
  248. // IMAGE
  249. if (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) && !mediaFilterImage {
  250. viewImage()
  251. }
  252. // OTHER
  253. if (metadata.typeFile == k_metadataTypeFile_document || metadata.typeFile == k_metadataTypeFile_unknown) && metadata.ocId == self.metadata?.ocId {
  254. self.navigationController?.navigationBar.topItem?.title = metadata.fileNameView
  255. }
  256. }
  257. } else {
  258. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  259. }
  260. }
  261. }
  262. }
  263. @objc func downloadedFile(_ notification: NSNotification) {
  264. if self.view?.window == nil { return }
  265. if let userInfo = notification.userInfo as NSDictionary? {
  266. if let metadata = userInfo["metadata"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int {
  267. if metadata.account != self.metadata?.account || metadata.serverUrl != self.metadata?.serverUrl { return }
  268. // IMAGE
  269. if metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio && errorCode != 0 {
  270. viewerImageViewController?.reloadContentViews()
  271. }
  272. progress(0)
  273. }
  274. }
  275. }
  276. @objc func uploadedFile(_ notification: NSNotification) {
  277. if self.view?.window == nil { return }
  278. if let userInfo = notification.userInfo as NSDictionary? {
  279. if let metadata = userInfo["metadata"] as? tableMetadata, let _ = userInfo["errorCode"] as? Int {
  280. if metadata.serverUrl != self.metadata?.serverUrl { return }
  281. progress(0)
  282. }
  283. }
  284. }
  285. @objc func downloadImage(_ notification: NSNotification) {
  286. if self.view?.window == nil { return }
  287. if let userInfo = notification.userInfo as NSDictionary? {
  288. if let metadata = userInfo["metadata"] as? tableMetadata {
  289. metadata.session = k_download_session
  290. metadata.sessionError = ""
  291. metadata.sessionSelector = ""
  292. metadata.status = Int(k_metadataStatusWaitDownload)
  293. self.metadata = NCManageDatabase.sharedInstance.addMetadata(metadata)
  294. if let index = metadatas.firstIndex(where: { $0.ocId == metadata.ocId }) {
  295. metadatas[index] = self.metadata!
  296. }
  297. appDelegate.startLoadAutoDownloadUpload()
  298. }
  299. }
  300. }
  301. @objc func saveLivePhoto(_ notification: NSNotification) {
  302. if self.view?.window == nil { return }
  303. if let userInfo = notification.userInfo as NSDictionary? {
  304. if let metadata = userInfo["metadata"] as? tableMetadata, let metadataMov = userInfo["metadataMov"] as? tableMetadata {
  305. let fileNameImage = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!)
  306. let fileNameMov = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadataMov.ocId, fileNameView: metadataMov.fileNameView)!)
  307. NCLivePhoto.generate(from: fileNameImage, videoURL: fileNameMov, progress: { progress in
  308. self.progress(Float(progress))
  309. }, completion: { livePhoto, resources in
  310. self.progress(0)
  311. if resources != nil {
  312. NCLivePhoto.saveToLibrary(resources!) { (result) in
  313. if !result {
  314. NCContentPresenter.shared.messageNotification("_error_", description: "_livephoto_save_error_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorInternalError))
  315. }
  316. }
  317. } else {
  318. NCContentPresenter.shared.messageNotification("_error_", description: "_livephoto_save_error_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorInternalError))
  319. }
  320. })
  321. }
  322. }
  323. }
  324. @objc func viewUnload() {
  325. self.unload(checkWindow: true)
  326. }
  327. private func unload(checkWindow: Bool) {
  328. if checkWindow && self.view?.window == nil { return }
  329. metadata = nil
  330. selector = nil
  331. if let splitViewController = self.splitViewController as? NCSplitViewController {
  332. if splitViewController.isCollapsed {
  333. if let navigationController = splitViewController.viewControllers.last as? UINavigationController {
  334. navigationController.popToRootViewController(animated: true)
  335. }
  336. } else {
  337. closeAllSubView()
  338. self.navigationController?.navigationBar.topItem?.title = ""
  339. }
  340. }
  341. self.splitViewController?.preferredDisplayMode = .allVisible
  342. self.navigationController?.isNavigationBarHidden = false
  343. view.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  344. backgroundView.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "logo"), multiplier: 2, color: NCBrandColor.sharedInstance.brand.withAlphaComponent(0.4))
  345. }
  346. private func closeAllSubView() {
  347. if backgroundView != nil {
  348. for view in backgroundView.subviews {
  349. view.removeFromSuperview()
  350. }
  351. }
  352. viewerImageViewController?.willMove(toParent: nil)
  353. viewerImageViewController?.view.removeFromSuperview()
  354. viewerImageViewController?.removeFromParent()
  355. }
  356. //MARK: - View File
  357. @objc func viewFile(metadata: tableMetadata, selector: String?) {
  358. self.metadata = metadata
  359. self.selector = selector
  360. self.backgroundView.image = nil
  361. closeAllSubView()
  362. if appDelegate.isMediaObserver {
  363. appDelegate.isMediaObserver = false
  364. NCViewerVideo.sharedInstance.removeObserver()
  365. }
  366. // IMAGE VIDEO AUDIO
  367. if metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_audio || metadata.typeFile == k_metadataTypeFile_video {
  368. viewImage()
  369. return
  370. }
  371. // DOCUMENT
  372. if metadata.typeFile == k_metadataTypeFile_document {
  373. // PDF
  374. if metadata.contentType == "application/pdf" {
  375. let frame = CGRect(x: 0, y: 0, width: self.backgroundView.frame.width, height: self.backgroundView.frame.height)
  376. let viewerPDF = NCViewerPDF.init(frame: frame)
  377. let filePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  378. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) == false {
  379. return
  380. }
  381. viewerPDF.setupPdfView(filePath: URL(fileURLWithPath: filePath), view: backgroundView)
  382. return
  383. }
  384. // DirectEditinf: Nextcloud Text - OnlyOffice
  385. if NCUtility.sharedInstance.isDirectEditing(metadata) != nil && appDelegate.reachability.isReachable() {
  386. let editor = NCUtility.sharedInstance.isDirectEditing(metadata)!
  387. if editor == k_editor_text || editor == k_editor_onlyoffice {
  388. NCUtility.sharedInstance.startActivityIndicator(view: backgroundView, bottom: 0)
  389. if metadata.url == "" {
  390. var customUserAgent: String?
  391. let fileNamePath = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, activeUrl: appDelegate.activeUrl)!
  392. if editor == k_editor_onlyoffice {
  393. customUserAgent = NCUtility.sharedInstance.getCustomUserAgentOnlyOffice()
  394. self.navigationController?.navigationBar.topItem?.title = ""
  395. }
  396. NCCommunication.sharedInstance.NCTextOpenFile(serverUrl: appDelegate.activeUrl, fileNamePath: fileNamePath, editor: editor, customUserAgent: customUserAgent, addCustomHeaders: nil, account: appDelegate.activeAccount) { (account, url, errorCode, errorMessage) in
  397. if errorCode == 0 && account == self.appDelegate.activeAccount && url != nil {
  398. let frame = CGRect(x: 0, y: 0, width: self.backgroundView.frame.width, height: self.backgroundView.frame.height)
  399. let nextcloudText = NCViewerNextcloudText.init(frame: frame, configuration: WKWebViewConfiguration())
  400. nextcloudText.viewerAt(url!, metadata: metadata, editor: editor, view: self.backgroundView, viewController: self)
  401. } else if errorCode != 0 {
  402. NCContentPresenter.shared.messageNotification("_error_", description: errorMessage, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  403. self.navigationController?.popViewController(animated: true)
  404. } else {
  405. self.navigationController?.popViewController(animated: true)
  406. }
  407. }
  408. } else {
  409. if editor == k_editor_onlyoffice {
  410. self.navigationController?.navigationBar.topItem?.title = ""
  411. }
  412. let frame = CGRect(x: 0, y: 0, width: self.backgroundView.frame.width, height: self.backgroundView.frame.height)
  413. let nextcloudText = NCViewerNextcloudText.init(frame: frame, configuration: WKWebViewConfiguration())
  414. nextcloudText.viewerAt(metadata.url, metadata: metadata, editor: editor, view: backgroundView, viewController: self)
  415. }
  416. }
  417. return
  418. }
  419. // RichDocument: Collabora
  420. if NCUtility.sharedInstance.isRichDocument(metadata) && appDelegate.reachability.isReachable() {
  421. NCUtility.sharedInstance.startActivityIndicator(view: backgroundView, bottom: 0)
  422. if metadata.url == "" {
  423. OCNetworking.sharedManager()?.createLinkRichdocuments(withAccount: appDelegate.activeAccount, fileId: metadata.fileId, completion: { (account, url, errorMessage, errorCode) in
  424. if errorCode == 0 && account == self.appDelegate.activeAccount && url != nil {
  425. let frame = CGRect(x: 0, y: 0, width: self.backgroundView.frame.width, height: self.backgroundView.frame.height)
  426. let richDocument = NCViewerRichdocument.init(frame: frame, configuration: WKWebViewConfiguration())
  427. richDocument.viewRichDocumentAt(url!, metadata: metadata, view: self.backgroundView, viewController: self)
  428. } else if errorCode != 0 {
  429. NCContentPresenter.shared.messageNotification("_error_", description: errorMessage, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  430. self.navigationController?.popViewController(animated: true)
  431. } else {
  432. self.navigationController?.popViewController(animated: true)
  433. }
  434. })
  435. } else {
  436. let richDocument = NCViewerRichdocument.init(frame: backgroundView.frame, configuration: WKWebViewConfiguration())
  437. richDocument.viewRichDocumentAt(metadata.url, metadata: metadata, view: backgroundView, viewController: self)
  438. }
  439. return
  440. }
  441. }
  442. // OTHER
  443. let fileNamePath = NSTemporaryDirectory() + metadata.fileNameView
  444. CCUtility.copyFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView), toPath: fileNamePath)
  445. viewerQuickLook = NCViewerQuickLook.init()
  446. viewerQuickLook?.quickLook(url: URL(fileURLWithPath: fileNamePath), viewController: self)
  447. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  448. self.unload(checkWindow: false)
  449. }
  450. }
  451. }
  452. //MARK: - viewerImageViewController - Delegate/DataSource
  453. extension NCDetailViewController: NCViewerImageViewControllerDelegate, NCViewerImageViewControllerDataSource {
  454. func viewImage() {
  455. closeAllSubView()
  456. if let metadatas = NCViewerImageCommon.shared.getMetadatasDatasource(metadata: self.metadata, metadatas: self.metadatas, favoriteDatasorce: favoriteFilterImage, mediaDatasorce: mediaFilterImage, offLineDatasource: offlineFilterImage) {
  457. var index = 0
  458. if let indexFound = metadatas.firstIndex(where: { $0.ocId == self.metadata?.ocId }) { index = indexFound }
  459. // Video -> is a Live Photo ?
  460. if metadata?.typeFile == k_metadataTypeFile_video && metadata != nil {
  461. let filename = (metadata!.fileNameView as NSString).deletingPathExtension.lowercased()
  462. if let indexFound = metadatas.firstIndex(where: { (($0.fileNameView as NSString).deletingPathExtension.lowercased() as String) == filename && $0.typeFile == k_metadataTypeFile_image }) { index = indexFound }
  463. }
  464. self.metadatas = metadatas
  465. viewerImageViewController = NCViewerImageViewController(index: index, dataSource: self, delegate: self)
  466. if viewerImageViewController != nil {
  467. self.backgroundView.image = nil
  468. viewerImageViewController!.view.isHidden = true
  469. viewerImageViewController!.enableInteractiveDismissal = true
  470. addChild(viewerImageViewController!)
  471. view.addSubview(viewerImageViewController!.view)
  472. viewerImageViewController!.view.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height)
  473. viewerImageViewController!.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  474. viewerImageViewController!.didMove(toParent: self)
  475. DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) {
  476. self.viewerImageViewController!.changeInViewSize(to: self.backgroundView.frame.size)
  477. self.viewerImageViewController!.view.isHidden = false
  478. }
  479. }
  480. }
  481. }
  482. func numberOfItems(in viewerImageViewController: NCViewerImageViewController) -> Int {
  483. return metadatas.count
  484. }
  485. func viewerImageViewController(_ viewerImageViewController: NCViewerImageViewController, imageAt index: Int, completion: @escaping (_ index: Int, _ image: UIImage?, _ metadata: tableMetadata, _ zoomScale: ZoomScale?, _ error: Error?) -> Void) {
  486. if index >= metadatas.count { return }
  487. let metadata = metadatas[index]
  488. let isPreview = CCUtility.fileProviderStorageIconExists(metadata.ocId, fileNameView: metadata.fileNameView)
  489. let isImage = CCUtility.fileProviderStorageSize(metadata.ocId, fileNameView: metadata.fileNameView) > 0
  490. let ext = CCUtility.getExtension(metadata.fileNameView)
  491. let isFolderEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account)
  492. // Refresh self metadata && title
  493. if viewerImageViewController.index < metadatas.count {
  494. self.metadata = metadatas[viewerImageViewController.index]
  495. self.navigationController?.navigationBar.topItem?.title = self.metadata!.fileNameView
  496. }
  497. // Status Current
  498. if index == viewerImageViewController.currentItemIndex {
  499. statusViewImage(metadata: metadata, viewerImageViewController: viewerImageViewController)
  500. }
  501. // Preview for Video
  502. if metadata.typeFile == k_metadataTypeFile_video && !isPreview && isImage {
  503. CCGraphics.createNewImage(from: metadata.fileNameView, ocId: metadata.ocId, filterGrayScale: false, typeFile: metadata.typeFile, writeImage: true)
  504. }
  505. // Original only for actual
  506. if metadata.typeFile == k_metadataTypeFile_image && isImage && index == viewerImageViewController.index {
  507. if let image = NCViewerImageCommon.shared.getImage(metadata: metadata) {
  508. completion(index, image, metadata, ZoomScale.default, nil)
  509. } else {
  510. completion(index, NCViewerImageCommon.shared.getImageOffOutline(frame: self.view.frame, type: metadata.typeFile), metadata, ZoomScale.default, nil)
  511. }
  512. // Automatic download for: Encripted
  513. } else if metadata.session == "" && CCUtility.fileProviderStorageSize(metadata.ocId, fileNameView: metadata.fileNameView) == 0 && isFolderEncrypted{
  514. if NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@ AND session != ''", metadata.ocId)) == nil {
  515. let metadata = NCManageDatabase.sharedInstance.initNewMetadata(metadata)
  516. metadata.session = k_download_session
  517. metadata.sessionError = ""
  518. metadata.sessionSelector = ""
  519. metadata.status = Int(k_metadataStatusWaitDownload)
  520. NCManageDatabase.sharedInstance.addMetadata(metadata)
  521. appDelegate.startLoadAutoDownloadUpload()
  522. }
  523. completion(index, NCViewerImageCommon.shared.getImageOffOutline(frame: self.view.frame, type: metadata.typeFile), metadata, ZoomScale.default, nil)
  524. // Automatic download for: HEIC - GIF - SVG
  525. } else if metadata.session == "" && CCUtility.fileProviderStorageSize(metadata.ocId, fileNameView: metadata.fileNameView) == 0 && ((metadata.contentType == "image/heic" && metadata.hasPreview == false) || ext == "GIF" || ext == "SVG") {
  526. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName
  527. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileName)!
  528. metadata.session = k_download_session_foreground
  529. _ = NCCommunication.sharedInstance.download(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, customUserAgent: nil, addCustomHeaders: nil, account: metadata.account, progressHandler: { (progress) in
  530. self.progress(Float(progress.fractionCompleted))
  531. }) { (account, etag, date, length, errorCode, errorDescription) in
  532. if errorCode == 0 && account == metadata.account {
  533. _ = NCManageDatabase.sharedInstance.addLocalFile(metadata: metadata)
  534. if let image = NCViewerImageCommon.shared.getImage(metadata: metadata) {
  535. completion(index, image, metadata, ZoomScale.default, nil)
  536. } else {
  537. completion(index, NCViewerImageCommon.shared.getImageOffOutline(frame: self.view.frame, type: metadata.typeFile), metadata, ZoomScale.default, nil)
  538. }
  539. } else if errorCode != 0 {
  540. completion(index, NCViewerImageCommon.shared.getImageOffOutline(frame: self.view.frame, type: metadata.typeFile), metadata, ZoomScale.default, nil)
  541. }
  542. metadata.session = ""
  543. self.progress(0)
  544. }
  545. // Preview
  546. } else if isPreview {
  547. if let image = NCViewerImageCommon.shared.getThumbnailImage(metadata: metadata) {
  548. completion(index, image, metadata, ZoomScale.default, nil)
  549. } else {
  550. completion(index, NCViewerImageCommon.shared.getImageOffOutline(frame: self.view.frame, type: metadata.typeFile), metadata, ZoomScale.default, nil)
  551. }
  552. } else if metadata.hasPreview {
  553. let fileNamePath = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, activeUrl: appDelegate.activeUrl)!
  554. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  555. NCCommunication.sharedInstance.downloadPreview(serverUrl: appDelegate.activeUrl, fileNamePath: fileNamePath, fileNameLocalPath: fileNameLocalPath, width: Int(k_sizePreview), height: Int(k_sizePreview), customUserAgent: nil, addCustomHeaders: nil, account: metadata.account) { (account, data, errorCode, errorMessage) in
  556. if errorCode == 0 && data != nil {
  557. completion(index, UIImage.init(data: data!), metadata, ZoomScale.default, nil)
  558. } else {
  559. completion(index, NCViewerImageCommon.shared.getImageOffOutline(frame: self.view.frame, type: metadata.typeFile), metadata, ZoomScale.default, nil)
  560. }
  561. }
  562. } else {
  563. completion(index, NCViewerImageCommon.shared.getImageOffOutline(frame: self.view.frame, type: metadata.typeFile), metadata, ZoomScale.default, nil)
  564. }
  565. }
  566. func viewerImageViewController(_ viewerImageViewController: NCViewerImageViewController, willChangeFocusTo index: Int, view: NCViewerImageContentView, metadata: tableMetadata) {
  567. statusViewImage(metadata: metadata, viewerImageViewController: viewerImageViewController)
  568. }
  569. func viewerImageViewController(_ viewerImageViewController: NCViewerImageViewController, didChangeFocusTo index: Int, view: NCViewerImageContentView, metadata: tableMetadata) {
  570. if metadata.typeFile == k_metadataTypeFile_image && !view.isLoading {
  571. DispatchQueue.global().async {
  572. if let image = NCViewerImageCommon.shared.getImage(metadata: metadata) {
  573. DispatchQueue.main.async {
  574. view.image = image
  575. }
  576. }
  577. }
  578. }
  579. }
  580. func viewerImageViewControllerTap(_ viewerImageViewController: NCViewerImageViewController, metadata: tableMetadata) {
  581. guard let navigationController = self.navigationController else { return }
  582. if metadata.typeFile == k_metadataTypeFile_image {
  583. if navigationController.isNavigationBarHidden {
  584. navigateControllerBarHidden(false)
  585. viewerImageViewController.statusView.isHidden = false
  586. } else {
  587. navigateControllerBarHidden(true)
  588. viewerImageViewController.statusView.isHidden = true
  589. }
  590. NCViewerImageCommon.shared.imageChangeSizeView(viewerImageViewController: viewerImageViewController, size: self.backgroundView.frame.size, metadata: metadata)
  591. } else {
  592. if let viewerImageVideo = UIStoryboard(name: "NCViewerImageVideo", bundle: nil).instantiateInitialViewController() as? NCViewerImageVideo {
  593. viewerImageVideo.metadata = metadata
  594. present(viewerImageVideo, animated: false) { }
  595. }
  596. }
  597. statusViewImage(metadata: metadata, viewerImageViewController: viewerImageViewController)
  598. }
  599. func viewerImageViewControllerLongPressBegan(_ viewerImageViewController: NCViewerImageViewController, metadata: tableMetadata) {
  600. viewerImageViewControllerLongPressInProgress = true
  601. let fileName = (metadata.fileNameView as NSString).deletingPathExtension + ".mov"
  602. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView LIKE[c] %@", metadata.account, metadata.serverUrl, fileName)) {
  603. if CCUtility.fileProviderStorageSize(metadata.ocId, fileNameView: metadata.fileNameView) > 0 {
  604. viewMOV(viewerImageViewController: viewerImageViewController, metadata: metadata)
  605. } else {
  606. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileNameView
  607. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  608. _ = NCCommunication.sharedInstance.download(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, customUserAgent: nil, addCustomHeaders: nil, account: metadata.account, progressHandler: { (progress) in
  609. self.progress(Float(progress.fractionCompleted))
  610. }) { (account, etag, date, length, errorCode, errorDescription) in
  611. self.progress(0)
  612. if errorCode == 0 && account == metadata.account {
  613. _ = NCManageDatabase.sharedInstance.addLocalFile(metadata: metadata)
  614. self.viewMOV(viewerImageViewController: viewerImageViewController, metadata: metadata)
  615. }
  616. }
  617. }
  618. }
  619. }
  620. func viewerImageViewControllerLongPressEnded(_ viewerImageViewController: NCViewerImageViewController, metadata: tableMetadata) {
  621. viewerImageViewControllerLongPressInProgress = false
  622. appDelegate.player?.pause()
  623. videoLayer?.removeFromSuperlayer()
  624. }
  625. func viewerImageViewControllerDismiss() {
  626. viewUnload()
  627. }
  628. func statusViewImage(metadata: tableMetadata, viewerImageViewController: NCViewerImageViewController) {
  629. var colorStatus: UIColor = UIColor.white.withAlphaComponent(0.8)
  630. if view.backgroundColor?.isLight() ?? true { colorStatus = UIColor.black.withAlphaComponent(0.8) }
  631. if NCUtility.sharedInstance.isLivePhoto(metadata: metadata) != nil {
  632. viewerImageViewController.statusView.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "livePhoto"), width: 100, height: 100, color: colorStatus)
  633. } else if metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio {
  634. viewerImageViewController.statusView.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "play"), width: 100, height: 100, color: colorStatus)
  635. } else {
  636. viewerImageViewController.statusView.image = nil
  637. }
  638. }
  639. func viewMOV(viewerImageViewController: NCViewerImageViewController, metadata: tableMetadata) {
  640. if !viewerImageViewControllerLongPressInProgress { return }
  641. appDelegate.player = AVPlayer(url: URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!))
  642. videoLayer = AVPlayerLayer(player: appDelegate.player)
  643. if videoLayer != nil {
  644. videoLayer!.frame = viewerImageViewController.view.frame
  645. videoLayer!.videoGravity = AVLayerVideoGravity.resizeAspect
  646. viewerImageViewController.view.layer.addSublayer(videoLayer!)
  647. appDelegate.player?.play()
  648. }
  649. }
  650. }
  651. //MARK: -
  652. extension NCDetailViewController: NCSelectDelegate {
  653. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, buttonType: String, overwrite: Bool) {
  654. if let metadata = self.metadata, let serverUrl = serverUrl {
  655. if buttonType == "done" {
  656. NCNetworking.sharedInstance.moveMetadata(metadata, serverUrlTo: serverUrl, overwrite: overwrite) { (errorCode, errorDescription) in }
  657. } else {
  658. NCNetworking.sharedInstance.copyMetadata(metadata, serverUrlTo: serverUrl, overwrite: overwrite) { (errorCode, errorDescription) in }
  659. }
  660. }
  661. }
  662. }