NCDetailViewController.swift 39 KB

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