NCDetailViewController.swift 42 KB

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