NCViewerMedia.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. //
  2. // NCViewerMedia.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 24/10/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 UIKit
  24. import SVGKit
  25. import NextcloudKit
  26. import EasyTipView
  27. import SwiftUI
  28. import MobileVLCKit
  29. class NCViewerMedia: UIViewController {
  30. @IBOutlet weak var detailViewTopConstraint: NSLayoutConstraint!
  31. @IBOutlet weak var detailViewHeighConstraint: NSLayoutConstraint!
  32. @IBOutlet weak var imageViewTopConstraint: NSLayoutConstraint!
  33. @IBOutlet weak var imageViewBottomConstraint: NSLayoutConstraint!
  34. @IBOutlet weak var scrollView: UIScrollView!
  35. @IBOutlet weak var imageVideoContainer: UIImageView!
  36. @IBOutlet weak var statusViewImage: UIImageView!
  37. @IBOutlet weak var statusLabel: UILabel!
  38. @IBOutlet weak var detailView: NCViewerMediaDetailView!
  39. private var tipView: EasyTipView?
  40. private let player = VLCMediaPlayer()
  41. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  42. weak var viewerMediaPage: NCViewerMediaPage?
  43. var playerToolBar: NCPlayerToolBar?
  44. var ncplayer: NCPlayer?
  45. var image: UIImage?
  46. var metadata: tableMetadata = tableMetadata()
  47. var index: Int = 0
  48. var doubleTapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer()
  49. var imageViewConstraint: CGFloat = 0
  50. var isDetailViewInitializze: Bool = false
  51. // MARK: - View Life Cycle
  52. required init?(coder aDecoder: NSCoder) {
  53. super.init(coder: aDecoder)
  54. doubleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didDoubleTapWith(gestureRecognizer:)))
  55. doubleTapGestureRecognizer.numberOfTapsRequired = 2
  56. }
  57. deinit {
  58. print("deinit NCViewerMedia")
  59. self.tipView?.dismiss()
  60. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterOpenMediaDetail), object: nil)
  61. }
  62. override func viewDidLoad() {
  63. super.viewDidLoad()
  64. scrollView.delegate = self
  65. scrollView.maximumZoomScale = 4
  66. scrollView.minimumZoomScale = 1
  67. view.addGestureRecognizer(doubleTapGestureRecognizer)
  68. if NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) != nil {
  69. statusViewImage.image = NCUtility.shared.loadImage(named: "livephoto", color: .gray)
  70. statusLabel.text = "LIVE"
  71. } else {
  72. statusViewImage.image = nil
  73. statusLabel.text = ""
  74. }
  75. if metadata.isMovie {
  76. playerToolBar = Bundle.main.loadNibNamed("NCPlayerToolBar", owner: self, options: nil)?.first as? NCPlayerToolBar
  77. if let playerToolBar = playerToolBar {
  78. view.addSubview(playerToolBar)
  79. playerToolBar.translatesAutoresizingMaskIntoConstraints = false
  80. playerToolBar.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
  81. playerToolBar.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
  82. playerToolBar.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
  83. playerToolBar.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
  84. }
  85. self.ncplayer = NCPlayer(imageVideoContainer: self.imageVideoContainer, playerToolBar: self.playerToolBar, metadata: self.metadata, viewerMediaPage: self.viewerMediaPage)
  86. }
  87. // TIP
  88. var preferences = EasyTipView.Preferences()
  89. preferences.drawing.foregroundColor = .white
  90. preferences.drawing.backgroundColor = NCBrandColor.shared.nextcloud
  91. preferences.drawing.textAlignment = .left
  92. preferences.drawing.arrowPosition = .top
  93. preferences.drawing.cornerRadius = 10
  94. preferences.animating.dismissTransform = CGAffineTransform(translationX: 0, y: 100)
  95. preferences.animating.showInitialTransform = CGAffineTransform(translationX: 0, y: -100)
  96. preferences.animating.showInitialAlpha = 0
  97. preferences.animating.showDuration = 0.5
  98. preferences.animating.dismissDuration = 0
  99. tipView = EasyTipView(text: NSLocalizedString("_tip_open_mediadetail_", comment: ""), preferences: preferences, delegate: self)
  100. detailViewTopConstraint.constant = 0
  101. detailView.hide()
  102. self.image = nil
  103. self.imageVideoContainer.image = nil
  104. loadImage()
  105. }
  106. override func viewWillAppear(_ animated: Bool) {
  107. super.viewWillAppear(animated)
  108. viewerMediaPage?.navigationController?.navigationBar.prefersLargeTitles = false
  109. viewerMediaPage?.navigationItem.title = metadata.fileNameView
  110. if metadata.isImage, let viewerMediaPage = self.viewerMediaPage {
  111. if viewerMediaPage.modifiedOcId.contains(metadata.ocId) {
  112. viewerMediaPage.modifiedOcId.removeAll(where: { $0 == metadata.ocId })
  113. loadImage()
  114. }
  115. }
  116. }
  117. override func viewDidAppear(_ animated: Bool) {
  118. super.viewDidAppear(animated)
  119. viewerMediaPage?.clearCommandCenter()
  120. if metadata.isMovie {
  121. if let ncplayer = self.ncplayer {
  122. if ncplayer.url == nil {
  123. NCActivityIndicator.shared.startActivity(backgroundView: self.view, style: .medium)
  124. NCNetworking.shared.getVideoUrl(metadata: metadata) { url, autoplay, error in
  125. NCActivityIndicator.shared.stop()
  126. if error == .success, let url = url {
  127. ncplayer.openAVPlayer(url: url, autoplay: autoplay)
  128. } else {
  129. NCContentPresenter.shared.showError(error: error)
  130. }
  131. }
  132. } else {
  133. var position: Float = 0
  134. if let result = NCManageDatabase.shared.getVideo(metadata: metadata), let resultPosition = result.position {
  135. position = resultPosition
  136. }
  137. ncplayer.restartAVPlayer(position: position, pauseAfterPlay: true)
  138. }
  139. }
  140. } else if metadata.isImage {
  141. showTip()
  142. }
  143. NotificationCenter.default.addObserver(self, selector: #selector(openDetail(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterOpenMediaDetail), object: nil)
  144. }
  145. override func viewWillDisappear(_ animated: Bool) {
  146. super.viewWillDisappear(animated)
  147. self.tipView?.dismiss()
  148. }
  149. override func viewDidDisappear(_ animated: Bool) {
  150. super.viewDidDisappear(animated)
  151. if let ncplayer = ncplayer, ncplayer.isPlay() {
  152. ncplayer.playerPause()
  153. }
  154. }
  155. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  156. self.tipView?.dismiss()
  157. if metadata.isVideo {
  158. self.imageVideoContainer.isHidden = true
  159. }
  160. super.viewWillTransition(to: size, with: coordinator)
  161. coordinator.animate(alongsideTransition: { context in
  162. // back to the original size
  163. self.scrollView.zoom(to: CGRect(x: 0, y: 0, width: self.scrollView.bounds.width, height: self.scrollView.bounds.height), animated: false)
  164. self.view.layoutIfNeeded()
  165. UIView.animate(withDuration: context.transitionDuration) {
  166. if self.detailView.isShow() {
  167. self.openDetail()
  168. }
  169. }
  170. }, completion: { context in
  171. self.showTip()
  172. if self.metadata.isVideo {
  173. self.imageVideoContainer.isHidden = false
  174. }
  175. })
  176. }
  177. // MARK: - Tip
  178. func showTip() {
  179. if !NCManageDatabase.shared.tipExists(NCGlobal.shared.tipNCViewerMediaDetailView), let view = self.navigationController?.navigationBar {
  180. self.tipView?.show(forView: view)
  181. }
  182. }
  183. // MARK: - Image
  184. func loadImage() {
  185. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(metadata.ocId) else { return }
  186. self.metadata = metadata
  187. // Download image
  188. if !CCUtility.fileProviderStorageExists(metadata) && metadata.isImage && metadata.session == "" {
  189. if metadata.livePhoto {
  190. let fileName = (metadata.fileNameView as NSString).deletingPathExtension + ".mov"
  191. if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView LIKE[c] %@", metadata.account, metadata.serverUrl, fileName)), !CCUtility.fileProviderStorageExists(metadata) {
  192. NCNetworking.shared.download(metadata: metadata, selector: "") { _, _ in }
  193. }
  194. }
  195. NCNetworking.shared.download(metadata: metadata, selector: "") { _, _ in
  196. let image = getImageMetadata(metadata)
  197. if self.metadata.ocId == metadata.ocId {
  198. self.image = image
  199. self.imageVideoContainer.image = image
  200. }
  201. }
  202. }
  203. // Get image
  204. let image = getImageMetadata(metadata)
  205. if self.metadata.ocId == metadata.ocId {
  206. self.image = image
  207. self.imageVideoContainer.image = image
  208. }
  209. func getImageMetadata(_ metadata: tableMetadata) -> UIImage? {
  210. if let image = getImage(metadata: metadata) {
  211. return image
  212. }
  213. if metadata.isVideo && !metadata.hasPreview {
  214. NCUtility.shared.createImageFrom(fileNameView: metadata.fileNameView, ocId: metadata.ocId, etag: metadata.etag, classFile: metadata.classFile)
  215. }
  216. if CCUtility.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag) {
  217. if let imagePreviewPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag) {
  218. return UIImage(contentsOfFile: imagePreviewPath)
  219. }
  220. }
  221. if metadata.isAudio {
  222. return UIImage(named: "noPreviewAudio")!.image(color: .gray, size: view.frame.width)
  223. } else if metadata.isImage {
  224. return UIImage(named: "noPreview")!.image(color: .gray, size: view.frame.width)
  225. } else {
  226. return nil
  227. }
  228. }
  229. func getImage(metadata: tableMetadata) -> UIImage? {
  230. let ext = CCUtility.getExtension(metadata.fileNameView)
  231. var image: UIImage?
  232. if CCUtility.fileProviderStorageExists(metadata) && metadata.isImage {
  233. let previewPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)!
  234. let imagePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  235. if ext == "GIF" {
  236. if !FileManager().fileExists(atPath: previewPath) {
  237. NCUtility.shared.createImageFrom(fileNameView: metadata.fileNameView, ocId: metadata.ocId, etag: metadata.etag, classFile: metadata.classFile)
  238. }
  239. image = UIImage.animatedImage(withAnimatedGIFURL: URL(fileURLWithPath: imagePath))
  240. } else if ext == "SVG" {
  241. if let svgImage = SVGKImage(contentsOfFile: imagePath) {
  242. svgImage.size = CGSize(width: NCGlobal.shared.sizePreview, height: NCGlobal.shared.sizePreview)
  243. if let image = svgImage.uiImage {
  244. if !FileManager().fileExists(atPath: previewPath) {
  245. do {
  246. try image.pngData()?.write(to: URL(fileURLWithPath: previewPath), options: .atomic)
  247. } catch { }
  248. }
  249. return image
  250. } else {
  251. return nil
  252. }
  253. } else {
  254. return nil
  255. }
  256. } else {
  257. NCUtility.shared.createImageFrom(fileNameView: metadata.fileNameView, ocId: metadata.ocId, etag: metadata.etag, classFile: metadata.classFile)
  258. image = UIImage(contentsOfFile: imagePath)
  259. }
  260. }
  261. return image
  262. }
  263. }
  264. // MARK: - Live Photo
  265. func playLivePhoto(filePath: String) {
  266. updateViewConstraints()
  267. statusViewImage.isHidden = true
  268. statusLabel.isHidden = true
  269. player.media = VLCMedia(url: URL(fileURLWithPath: filePath))
  270. player.drawable = imageVideoContainer
  271. player.play()
  272. }
  273. func stopLivePhoto() {
  274. player.stop()
  275. statusViewImage.isHidden = false
  276. statusLabel.isHidden = false
  277. }
  278. // MARK: - Gesture
  279. @objc func didDoubleTapWith(gestureRecognizer: UITapGestureRecognizer) {
  280. guard metadata.isImage, !detailView.isShow() else { return }
  281. let pointInView = gestureRecognizer.location(in: self.imageVideoContainer)
  282. var newZoomScale = self.scrollView.maximumZoomScale
  283. if self.scrollView.zoomScale >= newZoomScale || abs(self.scrollView.zoomScale - newZoomScale) <= 0.01 {
  284. newZoomScale = self.scrollView.minimumZoomScale
  285. }
  286. let width = self.scrollView.bounds.width / newZoomScale
  287. let height = self.scrollView.bounds.height / newZoomScale
  288. let originX = pointInView.x - (width / 2.0)
  289. let originY = pointInView.y - (height / 2.0)
  290. let rectToZoomTo = CGRect(x: originX, y: originY, width: width, height: height)
  291. self.scrollView.zoom(to: rectToZoomTo, animated: true)
  292. }
  293. @objc func didPanWith(gestureRecognizer: UIPanGestureRecognizer) {
  294. guard metadata.isImage else { return }
  295. let currentLocation = gestureRecognizer.translation(in: self.view)
  296. switch gestureRecognizer.state {
  297. case .began:
  298. // let velocity = gestureRecognizer.velocity(in: self.view)
  299. // gesture moving Up
  300. // if velocity.y < 0 {
  301. // }
  302. break
  303. case .ended:
  304. if detailView.isShow() {
  305. self.imageViewTopConstraint.constant = -imageViewConstraint
  306. self.imageViewBottomConstraint.constant = imageViewConstraint
  307. } else {
  308. self.imageViewTopConstraint.constant = 0
  309. self.imageViewBottomConstraint.constant = 0
  310. }
  311. case .changed:
  312. imageViewTopConstraint.constant = (currentLocation.y - imageViewConstraint)
  313. imageViewBottomConstraint.constant = -(currentLocation.y - imageViewConstraint)
  314. // DISMISS VIEW
  315. if detailView.isHidden && (currentLocation.y > 20) {
  316. viewerMediaPage?.navigationController?.popViewController(animated: true)
  317. gestureRecognizer.state = .ended
  318. }
  319. // CLOSE DETAIL
  320. if !detailView.isHidden && (currentLocation.y > 20) {
  321. self.closeDetail()
  322. gestureRecognizer.state = .ended
  323. }
  324. // OPEN DETAIL
  325. if detailView.isHidden && (currentLocation.y < -20) {
  326. self.openDetail()
  327. gestureRecognizer.state = .ended
  328. }
  329. default:
  330. break
  331. }
  332. }
  333. }
  334. // MARK: -
  335. extension NCViewerMedia {
  336. @objc func openDetail(_ notification: NSNotification) {
  337. if let userInfo = notification.userInfo as NSDictionary?, let ocId = userInfo["ocId"] as? String, ocId == metadata.ocId {
  338. openDetail()
  339. }
  340. }
  341. private func openDetail() {
  342. self.dismissTip()
  343. CCUtility.setExif(metadata) { latitude, longitude, location, date, lensModel in
  344. if latitude != -1 && latitude != 0 && longitude != -1 && longitude != 0 {
  345. self.detailViewHeighConstraint.constant = self.view.bounds.height / 2
  346. } else {
  347. self.detailViewHeighConstraint.constant = 170
  348. }
  349. self.view.layoutIfNeeded()
  350. self.detailView.show(
  351. metadata: self.metadata,
  352. image: self.image,
  353. textColor: self.viewerMediaPage?.textColor,
  354. mediaMetadata: (latitude: latitude, longitude: longitude, location: location, date: date, lensModel: lensModel),
  355. ncplayer: self.ncplayer,
  356. delegate: self)
  357. if let image = self.imageVideoContainer.image {
  358. let ratioW = self.imageVideoContainer.frame.width / image.size.width
  359. let ratioH = self.imageVideoContainer.frame.height / image.size.height
  360. let ratio = ratioW < ratioH ? ratioW : ratioH
  361. let imageHeight = image.size.height * ratio
  362. let VideoContainerHeight = self.imageVideoContainer.frame.height * ratio
  363. let height = max(imageHeight, VideoContainerHeight)
  364. self.imageViewConstraint = self.detailView.frame.height - ((self.view.frame.height - height) / 2) + self.view.safeAreaInsets.bottom
  365. if self.imageViewConstraint < 0 { self.imageViewConstraint = 0 }
  366. }
  367. UIView.animate(withDuration: 0.3) {
  368. self.imageViewTopConstraint.constant = -self.imageViewConstraint
  369. self.imageViewBottomConstraint.constant = self.imageViewConstraint
  370. self.detailViewTopConstraint.constant = self.detailViewHeighConstraint.constant
  371. self.view.layoutIfNeeded()
  372. } completion: { _ in
  373. }
  374. self.scrollView.pinchGestureRecognizer?.isEnabled = false
  375. }
  376. }
  377. private func closeDetail() {
  378. self.detailView.hide()
  379. imageViewConstraint = 0
  380. UIView.animate(withDuration: 0.3) {
  381. self.imageViewTopConstraint.constant = 0
  382. self.imageViewBottomConstraint.constant = 0
  383. self.detailViewTopConstraint.constant = 0
  384. self.view.layoutIfNeeded()
  385. } completion: { _ in
  386. }
  387. scrollView.pinchGestureRecognizer?.isEnabled = true
  388. }
  389. func reloadDetail() {
  390. if self.detailView.isShow() {
  391. CCUtility.setExif(metadata) { (latitude, longitude, location, date, lensModel) in
  392. self.detailView.show(
  393. metadata: self.metadata,
  394. image: self.image,
  395. textColor: self.viewerMediaPage?.textColor,
  396. mediaMetadata: (latitude: latitude, longitude: longitude, location: location, date: date, lensModel: lensModel),
  397. ncplayer: self.ncplayer,
  398. delegate: self)
  399. }
  400. }
  401. }
  402. }
  403. // MARK: -
  404. extension NCViewerMedia: UIScrollViewDelegate {
  405. func viewForZooming(in scrollView: UIScrollView) -> UIView? {
  406. return imageVideoContainer
  407. }
  408. func scrollViewDidZoom(_ scrollView: UIScrollView) {
  409. if scrollView.zoomScale > 1 {
  410. if let image = imageVideoContainer.image {
  411. let ratioW = imageVideoContainer.frame.width / image.size.width
  412. let ratioH = imageVideoContainer.frame.height / image.size.height
  413. let ratio = ratioW < ratioH ? ratioW : ratioH
  414. let newWidth = image.size.width * ratio
  415. let newHeight = image.size.height * ratio
  416. let conditionLeft = newWidth*scrollView.zoomScale > imageVideoContainer.frame.width
  417. let left = 0.5 * (conditionLeft ? newWidth - imageVideoContainer.frame.width : (scrollView.frame.width - scrollView.contentSize.width))
  418. let conditioTop = newHeight*scrollView.zoomScale > imageVideoContainer.frame.height
  419. let top = 0.5 * (conditioTop ? newHeight - imageVideoContainer.frame.height : (scrollView.frame.height - scrollView.contentSize.height))
  420. scrollView.contentInset = UIEdgeInsets(top: top, left: left, bottom: top, right: left)
  421. }
  422. } else {
  423. scrollView.contentInset = .zero
  424. }
  425. }
  426. func scrollViewDidScroll(_ scrollView: UIScrollView) {
  427. }
  428. }
  429. extension NCViewerMedia: NCViewerMediaDetailViewDelegate {
  430. func downloadFullResolution() {
  431. closeDetail()
  432. NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorOpenDetail) { _, _ in }
  433. }
  434. }
  435. extension NCViewerMedia: EasyTipViewDelegate {
  436. // TIP
  437. func easyTipViewDidTap(_ tipView: EasyTipView) {
  438. NCManageDatabase.shared.addTip(NCGlobal.shared.tipNCViewerMediaDetailView)
  439. }
  440. func easyTipViewDidDismiss(_ tipView: EasyTipView) { }
  441. func dismissTip() {
  442. NCManageDatabase.shared.addTip(NCGlobal.shared.tipNCViewerMediaDetailView)
  443. self.tipView?.dismiss()
  444. }
  445. }
  446. // MARK: -
  447. /*
  448. class imageVideoContainerView: UIImageView {
  449. var playerLayer: CALayer?
  450. var metadata: tableMetadata?
  451. override func layoutSublayers(of layer: CALayer) {
  452. super.layoutSublayers(of: layer)
  453. playerLayer?.frame = self.bounds
  454. }
  455. }
  456. */