NCViewerMedia.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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 NCCommunication
  25. class NCViewerMedia: UIViewController {
  26. @IBOutlet weak var detailViewTopConstraint: NSLayoutConstraint!
  27. @IBOutlet weak var detailViewHeighConstraint: NSLayoutConstraint!
  28. @IBOutlet weak var imageViewTopConstraint: NSLayoutConstraint!
  29. @IBOutlet weak var imageViewBottomConstraint: NSLayoutConstraint!
  30. @IBOutlet weak var scrollView: UIScrollView!
  31. @IBOutlet weak var imageVideoContainer: imageVideoContainerView!
  32. @IBOutlet weak var statusViewImage: UIImageView!
  33. @IBOutlet weak var statusLabel: UILabel!
  34. @IBOutlet weak var detailView: NCViewerMediaDetailView!
  35. @IBOutlet weak var playerToolBar: NCPlayerToolBar!
  36. private var _autoPlay: Bool = false
  37. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  38. var viewerMediaPage: NCViewerMediaPage?
  39. var ncplayer: NCPlayer?
  40. var image: UIImage?
  41. var metadata: tableMetadata = tableMetadata()
  42. var index: Int = 0
  43. var doubleTapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer()
  44. var imageViewConstraint: CGFloat = 0
  45. var isDetailViewInitializze: Bool = false
  46. var autoPlay: Bool {
  47. get {
  48. let temp = _autoPlay
  49. _autoPlay = false
  50. return temp
  51. }
  52. set(newVal) {
  53. _autoPlay = newVal
  54. }
  55. }
  56. // MARK: - View Life Cycle
  57. required init?(coder aDecoder: NSCoder) {
  58. super.init(coder: aDecoder)
  59. doubleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didDoubleTapWith(gestureRecognizer:)))
  60. doubleTapGestureRecognizer.numberOfTapsRequired = 2
  61. }
  62. deinit {
  63. print("deinit NCViewerMedia")
  64. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterOpenMediaDetail), object: nil)
  65. }
  66. override func viewDidLoad() {
  67. super.viewDidLoad()
  68. scrollView.delegate = self
  69. scrollView.maximumZoomScale = 4
  70. scrollView.minimumZoomScale = 1
  71. view.addGestureRecognizer(doubleTapGestureRecognizer)
  72. if metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue {
  73. if image == nil {
  74. image = UIImage.init(named: "noPreviewVideo")!.image(color: .gray, size: view.frame.width)
  75. }
  76. imageVideoContainer.image = image
  77. } else if metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue {
  78. if image == nil {
  79. image = UIImage.init(named: "noPreviewAudio")!.image(color: .gray, size: view.frame.width)
  80. }
  81. imageVideoContainer.image = image
  82. } else {
  83. if image == nil {
  84. image = UIImage.init(named: "noPreview")!.image(color: .gray, size: view.frame.width)
  85. }
  86. imageVideoContainer.image = image
  87. }
  88. if NCManageDatabase.shared.getMetadataLivePhoto(metadata: metadata) != nil {
  89. statusViewImage.image = NCUtility.shared.loadImage(named: "livephoto", color: .gray)
  90. statusLabel.text = "LIVE"
  91. } else {
  92. statusViewImage.image = nil
  93. statusLabel.text = ""
  94. }
  95. playerToolBar.viewerMediaPage = viewerMediaPage
  96. detailViewTopConstraint.constant = 0
  97. detailView.hide()
  98. }
  99. override func viewWillAppear(_ animated: Bool) {
  100. super.viewWillAppear(animated)
  101. viewerMediaPage?.navigationController?.navigationBar.prefersLargeTitles = false
  102. viewerMediaPage?.navigationItem.title = metadata.fileNameView
  103. if metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue, let viewerMediaPage = self.viewerMediaPage {
  104. viewerMediaPage.currentScreenMode = viewerMediaPage.saveScreenModeImage
  105. }
  106. if viewerMediaPage?.currentScreenMode == .full {
  107. viewerMediaPage?.navigationController?.setNavigationBarHidden(true, animated: true)
  108. NCUtility.shared.colorNavigationController(viewerMediaPage?.navigationController, backgroundColor: .black, titleColor: .white, tintColor: nil, withoutShadow: false)
  109. viewerMediaPage?.view.backgroundColor = .black
  110. viewerMediaPage?.textColor = .white
  111. viewerMediaPage?.progressView.isHidden = true
  112. } else {
  113. viewerMediaPage?.navigationController?.setNavigationBarHidden(false, animated: true)
  114. NCUtility.shared.colorNavigationController(viewerMediaPage?.navigationController, backgroundColor: NCBrandColor.shared.systemBackground, titleColor: NCBrandColor.shared.label, tintColor: nil, withoutShadow: false)
  115. viewerMediaPage?.view.backgroundColor = NCBrandColor.shared.systemBackground
  116. viewerMediaPage?.textColor = NCBrandColor.shared.label
  117. viewerMediaPage?.progressView.isHidden = false
  118. }
  119. downloadPreview()
  120. }
  121. override func viewDidAppear(_ animated: Bool) {
  122. super.viewDidAppear(animated)
  123. if (metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue) {
  124. if ncplayer == nil, let url = NCKTVHTTPCache.shared.getVideoURL(metadata: metadata) {
  125. self.ncplayer = NCPlayer.init(url: url, autoPlay: self.autoPlay, imageVideoContainer: self.imageVideoContainer, playerToolBar: self.playerToolBar, metadata: self.metadata, detailView: self.detailView)
  126. } else {
  127. self.ncplayer?.activateObserver(playerToolBar: self.playerToolBar)
  128. if detailView.isShow() == false && ncplayer?.isPlay() == false {
  129. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterShowPlayerToolBar, userInfo: ["ocId":metadata.ocId, "enableTimerAutoHide": false])
  130. }
  131. }
  132. if let ncplayer = self.ncplayer {
  133. self.viewerMediaPage?.updateCommandCenter(ncplayer: ncplayer, metadata: self.metadata)
  134. }
  135. } else if metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue {
  136. if let image = viewerMediaPage?.getImageMetadata(metadata) {
  137. self.image = image
  138. self.imageVideoContainer.image = image
  139. }
  140. viewerMediaPage?.clearCommandCenter()
  141. }
  142. NotificationCenter.default.addObserver(self, selector: #selector(openDetail(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterOpenMediaDetail), object: nil)
  143. }
  144. override func viewDidDisappear(_ animated: Bool) {
  145. super.viewDidDisappear(animated)
  146. }
  147. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  148. super.viewWillTransition(to: size, with: coordinator)
  149. coordinator.animate(alongsideTransition: { (context) in
  150. // back to the original size
  151. self.scrollView.zoom(to: CGRect(x: 0, y: 0, width: self.scrollView.bounds.width, height: self.scrollView.bounds.height), animated: false)
  152. self.view.layoutIfNeeded()
  153. UIView.animate(withDuration: context.transitionDuration) {
  154. if self.detailView.isShow() {
  155. self.openDetail()
  156. }
  157. }
  158. }) { (_) in }
  159. }
  160. //MARK: - Gesture
  161. @objc func didDoubleTapWith(gestureRecognizer: UITapGestureRecognizer) {
  162. if detailView.isShow() { return }
  163. // NO ZOOM for Audio
  164. if metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue { return }
  165. let pointInView = gestureRecognizer.location(in: self.imageVideoContainer)
  166. var newZoomScale = self.scrollView.maximumZoomScale
  167. if self.scrollView.zoomScale >= newZoomScale || abs(self.scrollView.zoomScale - newZoomScale) <= 0.01 {
  168. newZoomScale = self.scrollView.minimumZoomScale
  169. }
  170. let width = self.scrollView.bounds.width / newZoomScale
  171. let height = self.scrollView.bounds.height / newZoomScale
  172. let originX = pointInView.x - (width / 2.0)
  173. let originY = pointInView.y - (height / 2.0)
  174. let rectToZoomTo = CGRect(x: originX, y: originY, width: width, height: height)
  175. self.scrollView.zoom(to: rectToZoomTo, animated: true)
  176. }
  177. @objc func didPanWith(gestureRecognizer: UIPanGestureRecognizer) {
  178. let currentLocation = gestureRecognizer.translation(in: self.view)
  179. switch gestureRecognizer.state {
  180. case .began:
  181. // let velocity = gestureRecognizer.velocity(in: self.view)
  182. // gesture moving Up
  183. // if velocity.y < 0 {
  184. // }
  185. break
  186. case .ended:
  187. if detailView.isShow() {
  188. self.imageViewTopConstraint.constant = -imageViewConstraint
  189. self.imageViewBottomConstraint.constant = imageViewConstraint
  190. } else {
  191. self.imageViewTopConstraint.constant = 0
  192. self.imageViewBottomConstraint.constant = 0
  193. }
  194. case .changed:
  195. imageViewTopConstraint.constant = (currentLocation.y - imageViewConstraint)
  196. imageViewBottomConstraint.constant = -(currentLocation.y - imageViewConstraint)
  197. // DISMISS VIEW
  198. if detailView.isHidden && (currentLocation.y > 20) {
  199. viewerMediaPage?.navigationController?.popViewController(animated: true)
  200. gestureRecognizer.state = .ended
  201. }
  202. // CLOSE DETAIL
  203. if !detailView.isHidden && (currentLocation.y > 20) {
  204. self.closeDetail()
  205. gestureRecognizer.state = .ended
  206. }
  207. // OPEN DETAIL
  208. if detailView.isHidden && (currentLocation.y < -20) {
  209. self.openDetail()
  210. gestureRecognizer.state = .ended
  211. }
  212. default:
  213. break
  214. }
  215. }
  216. }
  217. //MARK: -
  218. extension NCViewerMedia {
  219. @objc func openDetail(_ notification: NSNotification) {
  220. if let userInfo = notification.userInfo as NSDictionary?, let ocId = userInfo["ocId"] as? String, ocId == metadata.ocId {
  221. openDetail()
  222. }
  223. }
  224. private func openDetail() {
  225. CCUtility.setExif(metadata) { (latitude, longitude, location, date, lensModel) in
  226. if (latitude != -1 && latitude != 0 && longitude != -1 && longitude != 0) {
  227. self.detailViewHeighConstraint.constant = self.view.bounds.height / 2
  228. } else {
  229. self.detailViewHeighConstraint.constant = 170
  230. }
  231. self.view.layoutIfNeeded()
  232. self.detailView.show(metadata:self.metadata, image: self.image, textColor: self.viewerMediaPage?.textColor, latitude: latitude, longitude: longitude, location: location, date: date, lensModel: lensModel, delegate: self)
  233. if let image = self.imageVideoContainer.image {
  234. let ratioW = self.imageVideoContainer.frame.width / image.size.width
  235. let ratioH = self.imageVideoContainer.frame.height / image.size.height
  236. let ratio = ratioW < ratioH ? ratioW : ratioH
  237. let imageHeight = image.size.height * ratio
  238. self.imageViewConstraint = self.detailView.frame.height - ((self.view.frame.height - imageHeight) / 2) + self.view.safeAreaInsets.bottom
  239. if self.imageViewConstraint < 0 { self.imageViewConstraint = 0 }
  240. }
  241. UIView.animate(withDuration: 0.3) {
  242. self.imageViewTopConstraint.constant = -self.imageViewConstraint
  243. self.imageViewBottomConstraint.constant = self.imageViewConstraint
  244. self.detailViewTopConstraint.constant = self.detailViewHeighConstraint.constant
  245. self.view.layoutIfNeeded()
  246. } completion: { (_) in
  247. }
  248. self.scrollView.pinchGestureRecognizer?.isEnabled = false
  249. self.playerToolBar.hide()
  250. }
  251. }
  252. private func closeDetail() {
  253. self.detailView.hide()
  254. imageViewConstraint = 0
  255. UIView.animate(withDuration: 0.3) {
  256. self.imageViewTopConstraint.constant = 0
  257. self.imageViewBottomConstraint.constant = 0
  258. self.detailViewTopConstraint.constant = 0
  259. self.view.layoutIfNeeded()
  260. } completion: { (_) in
  261. }
  262. scrollView.pinchGestureRecognizer?.isEnabled = true
  263. if metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue && !metadata.livePhoto && ncplayer?.player?.timeControlStatus == .paused {
  264. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterShowPlayerToolBar, userInfo: ["ocId":metadata.ocId, "enableTimerAutoHide": false])
  265. }
  266. }
  267. func reloadDetail() {
  268. if self.detailView.isShow() {
  269. CCUtility.setExif(metadata) { (latitude, longitude, location, date, lensModel) in
  270. self.detailView.show(metadata:self.metadata, image: self.image, textColor: self.viewerMediaPage?.textColor, latitude: latitude, longitude: longitude, location: location, date: date, lensModel: lensModel, delegate: self)
  271. }
  272. }
  273. }
  274. func downloadPreview() {
  275. if metadata.hasPreview == false || CCUtility.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag) {
  276. downloadFile()
  277. return
  278. }
  279. var etagResource: String?
  280. let fileNamePath = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, account: metadata.account)!
  281. let fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)!
  282. let fileNameIconLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)!
  283. if FileManager.default.fileExists(atPath: fileNameIconLocalPath) && FileManager.default.fileExists(atPath: fileNamePreviewLocalPath) {
  284. etagResource = metadata.etagResource
  285. }
  286. NCUtility.shared.startActivityIndicator(backgroundView: nil, blurEffect: true)
  287. NCCommunication.shared.downloadPreview(fileNamePathOrFileId: fileNamePath, fileNamePreviewLocalPath: fileNamePreviewLocalPath , widthPreview: NCGlobal.shared.sizePreview, heightPreview: NCGlobal.shared.sizePreview, fileNameIconLocalPath: fileNameIconLocalPath, sizeIcon: NCGlobal.shared.sizeIcon, etag: etagResource, queue: NCCommunicationCommon.shared.backgroundQueue) { (account, imagePreview, imageIcon, imageOriginal, etag, errorCode, errorDescription) in
  288. if errorCode == 0, let image = self.viewerMediaPage?.getImageMetadata(self.metadata) {
  289. DispatchQueue.main.async {
  290. self.image = image
  291. self.imageVideoContainer.image = image
  292. NCUtility.shared.stopActivityIndicator()
  293. self.downloadFile()
  294. }
  295. }
  296. }
  297. }
  298. func downloadFile() {
  299. if metadata.classFile != NCCommunicationCommon.typeClassFile.image.rawValue || CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) || metadata.session != "" { return }
  300. let isFolderEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: metadata.urlBase)
  301. let ext = CCUtility.getExtension(metadata.fileNameView)
  302. if CCUtility.getAutomaticDownloadImage() || (metadata.contentType == "image/heic" && metadata.hasPreview == false) || ext == "GIF" || ext == "SVG" || isFolderEncrypted {
  303. NCUtility.shared.startActivityIndicator(backgroundView: nil, blurEffect: true)
  304. NCNetworking.shared.download(metadata: metadata, selector: "") { (errorCode) in
  305. if errorCode == 0, let image = self.viewerMediaPage?.getImageMetadata(self.metadata) {
  306. DispatchQueue.main.async {
  307. self.image = image
  308. self.imageVideoContainer.image = image
  309. NCUtility.shared.stopActivityIndicator()
  310. }
  311. }
  312. }
  313. }
  314. }
  315. }
  316. //MARK: -
  317. extension NCViewerMedia: UIScrollViewDelegate {
  318. func viewForZooming(in scrollView: UIScrollView) -> UIView? {
  319. return imageVideoContainer
  320. }
  321. func scrollViewDidZoom(_ scrollView: UIScrollView) {
  322. if scrollView.zoomScale > 1 {
  323. if let image = imageVideoContainer.image {
  324. let ratioW = imageVideoContainer.frame.width / image.size.width
  325. let ratioH = imageVideoContainer.frame.height / image.size.height
  326. let ratio = ratioW < ratioH ? ratioW : ratioH
  327. let newWidth = image.size.width * ratio
  328. let newHeight = image.size.height * ratio
  329. let conditionLeft = newWidth*scrollView.zoomScale > imageVideoContainer.frame.width
  330. let left = 0.5 * (conditionLeft ? newWidth - imageVideoContainer.frame.width : (scrollView.frame.width - scrollView.contentSize.width))
  331. let conditioTop = newHeight*scrollView.zoomScale > imageVideoContainer.frame.height
  332. let top = 0.5 * (conditioTop ? newHeight - imageVideoContainer.frame.height : (scrollView.frame.height - scrollView.contentSize.height))
  333. scrollView.contentInset = UIEdgeInsets(top: top, left: left, bottom: top, right: left)
  334. }
  335. } else {
  336. scrollView.contentInset = .zero
  337. }
  338. }
  339. func scrollViewDidScroll(_ scrollView: UIScrollView) {
  340. }
  341. }
  342. extension NCViewerMedia: NCViewerMediaDetailViewDelegate {
  343. func downloadFullResolution() {
  344. closeDetail()
  345. NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorOpenDetail) { (_) in }
  346. }
  347. }
  348. //MARK: -
  349. class imageVideoContainerView: UIImageView {
  350. var playerLayer: CALayer?
  351. var metadata: tableMetadata?
  352. override func layoutSublayers(of layer: CALayer) {
  353. super.layoutSublayers(of: layer)
  354. playerLayer?.frame = self.bounds
  355. }
  356. }