NCViewerMedia.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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. NCNetworking.shared.getVideoUrl(metadata: metadata) { url, autoplay in
  124. if let url = url {
  125. ncplayer.openAVPlayer(url: url, autoplay: autoplay)
  126. }
  127. }
  128. } else {
  129. var position: Float = 0
  130. if let result = NCManageDatabase.shared.getVideo(metadata: metadata), let resultPosition = result.position {
  131. position = resultPosition
  132. }
  133. ncplayer.restartAVPlayer(position: position, pauseAfterPlay: true)
  134. }
  135. }
  136. } else if metadata.isImage {
  137. showTip()
  138. }
  139. NotificationCenter.default.addObserver(self, selector: #selector(openDetail(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterOpenMediaDetail), object: nil)
  140. }
  141. override func viewWillDisappear(_ animated: Bool) {
  142. super.viewWillDisappear(animated)
  143. self.tipView?.dismiss()
  144. }
  145. override func viewDidDisappear(_ animated: Bool) {
  146. super.viewDidDisappear(animated)
  147. if let ncplayer = ncplayer, ncplayer.isPlay() {
  148. ncplayer.playerPause()
  149. }
  150. }
  151. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  152. self.tipView?.dismiss()
  153. if metadata.isVideo {
  154. self.imageVideoContainer.isHidden = true
  155. }
  156. super.viewWillTransition(to: size, with: coordinator)
  157. coordinator.animate(alongsideTransition: { context in
  158. // back to the original size
  159. self.scrollView.zoom(to: CGRect(x: 0, y: 0, width: self.scrollView.bounds.width, height: self.scrollView.bounds.height), animated: false)
  160. self.view.layoutIfNeeded()
  161. UIView.animate(withDuration: context.transitionDuration) {
  162. if self.detailView.isShow() {
  163. self.openDetail()
  164. }
  165. }
  166. }, completion: { context in
  167. self.showTip()
  168. if self.metadata.isVideo {
  169. self.imageVideoContainer.isHidden = false
  170. }
  171. })
  172. }
  173. // MARK: - Tip
  174. func showTip() {
  175. if !NCManageDatabase.shared.tipExists(NCGlobal.shared.tipNCViewerMediaDetailView), let view = self.navigationController?.navigationBar {
  176. self.tipView?.show(forView: view)
  177. }
  178. }
  179. // MARK: - Image
  180. func loadImage() {
  181. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(metadata.ocId) else { return }
  182. self.metadata = metadata
  183. // Download image
  184. if !CCUtility.fileProviderStorageExists(metadata) && metadata.isImage && metadata.session == "" {
  185. if metadata.livePhoto {
  186. let fileName = (metadata.fileNameView as NSString).deletingPathExtension + ".mov"
  187. if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView LIKE[c] %@", metadata.account, metadata.serverUrl, fileName)), !CCUtility.fileProviderStorageExists(metadata) {
  188. NCNetworking.shared.download(metadata: metadata, selector: "") { _, _ in }
  189. }
  190. }
  191. NCNetworking.shared.download(metadata: metadata, selector: "") { _, _ in
  192. let image = getImageMetadata(metadata)
  193. if self.metadata.ocId == metadata.ocId {
  194. self.image = image
  195. self.imageVideoContainer.image = image
  196. }
  197. }
  198. }
  199. // Get image
  200. let image = getImageMetadata(metadata)
  201. if self.metadata.ocId == metadata.ocId {
  202. self.image = image
  203. self.imageVideoContainer.image = image
  204. }
  205. func getImageMetadata(_ metadata: tableMetadata) -> UIImage? {
  206. if let image = getImage(metadata: metadata) {
  207. return image
  208. }
  209. if metadata.isVideo && !metadata.hasPreview {
  210. NCUtility.shared.createImageFrom(fileNameView: metadata.fileNameView, ocId: metadata.ocId, etag: metadata.etag, classFile: metadata.classFile)
  211. }
  212. if CCUtility.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag) {
  213. if let imagePreviewPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag) {
  214. return UIImage(contentsOfFile: imagePreviewPath)
  215. }
  216. }
  217. if metadata.isAudio {
  218. return UIImage(named: "noPreviewAudio")!.image(color: .gray, size: view.frame.width)
  219. } else if metadata.isImage {
  220. return UIImage(named: "noPreview")!.image(color: .gray, size: view.frame.width)
  221. } else {
  222. return nil
  223. }
  224. }
  225. func getImage(metadata: tableMetadata) -> UIImage? {
  226. let ext = CCUtility.getExtension(metadata.fileNameView)
  227. var image: UIImage?
  228. if CCUtility.fileProviderStorageExists(metadata) && metadata.isImage {
  229. let previewPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)!
  230. let imagePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  231. if ext == "GIF" {
  232. if !FileManager().fileExists(atPath: previewPath) {
  233. NCUtility.shared.createImageFrom(fileNameView: metadata.fileNameView, ocId: metadata.ocId, etag: metadata.etag, classFile: metadata.classFile)
  234. }
  235. image = UIImage.animatedImage(withAnimatedGIFURL: URL(fileURLWithPath: imagePath))
  236. } else if ext == "SVG" {
  237. if let svgImage = SVGKImage(contentsOfFile: imagePath) {
  238. svgImage.size = CGSize(width: NCGlobal.shared.sizePreview, height: NCGlobal.shared.sizePreview)
  239. if let image = svgImage.uiImage {
  240. if !FileManager().fileExists(atPath: previewPath) {
  241. do {
  242. try image.pngData()?.write(to: URL(fileURLWithPath: previewPath), options: .atomic)
  243. } catch { }
  244. }
  245. return image
  246. } else {
  247. return nil
  248. }
  249. } else {
  250. return nil
  251. }
  252. } else {
  253. NCUtility.shared.createImageFrom(fileNameView: metadata.fileNameView, ocId: metadata.ocId, etag: metadata.etag, classFile: metadata.classFile)
  254. image = UIImage(contentsOfFile: imagePath)
  255. }
  256. }
  257. return image
  258. }
  259. }
  260. // MARK: - Live Photo
  261. func playLivePhoto(filePath: String) {
  262. updateViewConstraints()
  263. statusViewImage.isHidden = true
  264. statusLabel.isHidden = true
  265. player.media = VLCMedia(url: URL(fileURLWithPath: filePath))
  266. player.drawable = imageVideoContainer
  267. player.play()
  268. }
  269. func stopLivePhoto() {
  270. player.stop()
  271. statusViewImage.isHidden = false
  272. statusLabel.isHidden = false
  273. }
  274. // MARK: - Gesture
  275. @objc func didDoubleTapWith(gestureRecognizer: UITapGestureRecognizer) {
  276. guard metadata.isImage, !detailView.isShow() else { return }
  277. let pointInView = gestureRecognizer.location(in: self.imageVideoContainer)
  278. var newZoomScale = self.scrollView.maximumZoomScale
  279. if self.scrollView.zoomScale >= newZoomScale || abs(self.scrollView.zoomScale - newZoomScale) <= 0.01 {
  280. newZoomScale = self.scrollView.minimumZoomScale
  281. }
  282. let width = self.scrollView.bounds.width / newZoomScale
  283. let height = self.scrollView.bounds.height / newZoomScale
  284. let originX = pointInView.x - (width / 2.0)
  285. let originY = pointInView.y - (height / 2.0)
  286. let rectToZoomTo = CGRect(x: originX, y: originY, width: width, height: height)
  287. self.scrollView.zoom(to: rectToZoomTo, animated: true)
  288. }
  289. @objc func didPanWith(gestureRecognizer: UIPanGestureRecognizer) {
  290. guard metadata.isImage else { return }
  291. let currentLocation = gestureRecognizer.translation(in: self.view)
  292. switch gestureRecognizer.state {
  293. case .began:
  294. // let velocity = gestureRecognizer.velocity(in: self.view)
  295. // gesture moving Up
  296. // if velocity.y < 0 {
  297. // }
  298. break
  299. case .ended:
  300. if detailView.isShow() {
  301. self.imageViewTopConstraint.constant = -imageViewConstraint
  302. self.imageViewBottomConstraint.constant = imageViewConstraint
  303. } else {
  304. self.imageViewTopConstraint.constant = 0
  305. self.imageViewBottomConstraint.constant = 0
  306. }
  307. case .changed:
  308. imageViewTopConstraint.constant = (currentLocation.y - imageViewConstraint)
  309. imageViewBottomConstraint.constant = -(currentLocation.y - imageViewConstraint)
  310. // DISMISS VIEW
  311. if detailView.isHidden && (currentLocation.y > 20) {
  312. viewerMediaPage?.navigationController?.popViewController(animated: true)
  313. gestureRecognizer.state = .ended
  314. }
  315. // CLOSE DETAIL
  316. if !detailView.isHidden && (currentLocation.y > 20) {
  317. self.closeDetail()
  318. gestureRecognizer.state = .ended
  319. }
  320. // OPEN DETAIL
  321. if detailView.isHidden && (currentLocation.y < -20) {
  322. self.openDetail()
  323. gestureRecognizer.state = .ended
  324. }
  325. default:
  326. break
  327. }
  328. }
  329. }
  330. // MARK: -
  331. extension NCViewerMedia {
  332. @objc func openDetail(_ notification: NSNotification) {
  333. if let userInfo = notification.userInfo as NSDictionary?, let ocId = userInfo["ocId"] as? String, ocId == metadata.ocId {
  334. openDetail()
  335. }
  336. }
  337. private func openDetail() {
  338. self.dismissTip()
  339. CCUtility.setExif(metadata) { latitude, longitude, location, date, lensModel in
  340. if latitude != -1 && latitude != 0 && longitude != -1 && longitude != 0 {
  341. self.detailViewHeighConstraint.constant = self.view.bounds.height / 2
  342. } else {
  343. self.detailViewHeighConstraint.constant = 170
  344. }
  345. self.view.layoutIfNeeded()
  346. self.detailView.show(
  347. metadata: self.metadata,
  348. image: self.image,
  349. textColor: self.viewerMediaPage?.textColor,
  350. mediaMetadata: (latitude: latitude, longitude: longitude, location: location, date: date, lensModel: lensModel),
  351. ncplayer: self.ncplayer,
  352. delegate: self)
  353. if let image = self.imageVideoContainer.image {
  354. let ratioW = self.imageVideoContainer.frame.width / image.size.width
  355. let ratioH = self.imageVideoContainer.frame.height / image.size.height
  356. let ratio = ratioW < ratioH ? ratioW : ratioH
  357. let imageHeight = image.size.height * ratio
  358. let VideoContainerHeight = self.imageVideoContainer.frame.height * ratio
  359. let height = max(imageHeight, VideoContainerHeight)
  360. self.imageViewConstraint = self.detailView.frame.height - ((self.view.frame.height - height) / 2) + self.view.safeAreaInsets.bottom
  361. if self.imageViewConstraint < 0 { self.imageViewConstraint = 0 }
  362. }
  363. UIView.animate(withDuration: 0.3) {
  364. self.imageViewTopConstraint.constant = -self.imageViewConstraint
  365. self.imageViewBottomConstraint.constant = self.imageViewConstraint
  366. self.detailViewTopConstraint.constant = self.detailViewHeighConstraint.constant
  367. self.view.layoutIfNeeded()
  368. } completion: { _ in
  369. }
  370. self.scrollView.pinchGestureRecognizer?.isEnabled = false
  371. }
  372. }
  373. private func closeDetail() {
  374. self.detailView.hide()
  375. imageViewConstraint = 0
  376. UIView.animate(withDuration: 0.3) {
  377. self.imageViewTopConstraint.constant = 0
  378. self.imageViewBottomConstraint.constant = 0
  379. self.detailViewTopConstraint.constant = 0
  380. self.view.layoutIfNeeded()
  381. } completion: { _ in
  382. }
  383. scrollView.pinchGestureRecognizer?.isEnabled = true
  384. }
  385. func reloadDetail() {
  386. if self.detailView.isShow() {
  387. CCUtility.setExif(metadata) { (latitude, longitude, location, date, lensModel) in
  388. self.detailView.show(
  389. metadata: self.metadata,
  390. image: self.image,
  391. textColor: self.viewerMediaPage?.textColor,
  392. mediaMetadata: (latitude: latitude, longitude: longitude, location: location, date: date, lensModel: lensModel),
  393. ncplayer: self.ncplayer,
  394. delegate: self)
  395. }
  396. }
  397. }
  398. }
  399. // MARK: -
  400. extension NCViewerMedia: UIScrollViewDelegate {
  401. func viewForZooming(in scrollView: UIScrollView) -> UIView? {
  402. return imageVideoContainer
  403. }
  404. func scrollViewDidZoom(_ scrollView: UIScrollView) {
  405. if scrollView.zoomScale > 1 {
  406. if let image = imageVideoContainer.image {
  407. let ratioW = imageVideoContainer.frame.width / image.size.width
  408. let ratioH = imageVideoContainer.frame.height / image.size.height
  409. let ratio = ratioW < ratioH ? ratioW : ratioH
  410. let newWidth = image.size.width * ratio
  411. let newHeight = image.size.height * ratio
  412. let conditionLeft = newWidth*scrollView.zoomScale > imageVideoContainer.frame.width
  413. let left = 0.5 * (conditionLeft ? newWidth - imageVideoContainer.frame.width : (scrollView.frame.width - scrollView.contentSize.width))
  414. let conditioTop = newHeight*scrollView.zoomScale > imageVideoContainer.frame.height
  415. let top = 0.5 * (conditioTop ? newHeight - imageVideoContainer.frame.height : (scrollView.frame.height - scrollView.contentSize.height))
  416. scrollView.contentInset = UIEdgeInsets(top: top, left: left, bottom: top, right: left)
  417. }
  418. } else {
  419. scrollView.contentInset = .zero
  420. }
  421. }
  422. func scrollViewDidScroll(_ scrollView: UIScrollView) {
  423. }
  424. }
  425. extension NCViewerMedia: NCViewerMediaDetailViewDelegate {
  426. func downloadFullResolution() {
  427. closeDetail()
  428. NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorOpenDetail) { _, _ in }
  429. }
  430. }
  431. extension NCViewerMedia: EasyTipViewDelegate {
  432. // TIP
  433. func easyTipViewDidTap(_ tipView: EasyTipView) {
  434. NCManageDatabase.shared.addTip(NCGlobal.shared.tipNCViewerMediaDetailView)
  435. }
  436. func easyTipViewDidDismiss(_ tipView: EasyTipView) { }
  437. func dismissTip() {
  438. NCManageDatabase.shared.addTip(NCGlobal.shared.tipNCViewerMediaDetailView)
  439. self.tipView?.dismiss()
  440. }
  441. }
  442. // MARK: -
  443. /*
  444. class imageVideoContainerView: UIImageView {
  445. var playerLayer: CALayer?
  446. var metadata: tableMetadata?
  447. override func layoutSublayers(of layer: CALayer) {
  448. super.layoutSublayers(of: layer)
  449. playerLayer?.frame = self.bounds
  450. }
  451. }
  452. */