NCViewerMediaPage.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. //
  2. // NCViewerMediaPage.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 NCCommunication
  26. import MediaPlayer
  27. class NCViewerMediaPage: UIViewController {
  28. @IBOutlet weak var progressView: UIProgressView!
  29. enum ScreenMode {
  30. case full, normal
  31. }
  32. var currentScreenMode: ScreenMode = .normal
  33. var saveScreenModeImage: ScreenMode = .normal
  34. var pageViewController: UIPageViewController {
  35. return self.children[0] as! UIPageViewController
  36. }
  37. var currentViewController: NCViewerMedia {
  38. return self.pageViewController.viewControllers![0] as! NCViewerMedia
  39. }
  40. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  41. var metadatas: [tableMetadata] = []
  42. var currentIndex = 0
  43. var nextIndex: Int?
  44. var IndexInPlay: Int = -1
  45. var ncplayerLivePhoto: NCPlayer?
  46. var panGestureRecognizer: UIPanGestureRecognizer!
  47. var singleTapGestureRecognizer: UITapGestureRecognizer!
  48. var longtapGestureRecognizer: UILongPressGestureRecognizer!
  49. var textColor: UIColor = NCBrandColor.shared.label
  50. var playCommand: Any?
  51. var pauseCommand: Any?
  52. var skipForwardCommand: Any?
  53. var skipBackwardCommand: Any?
  54. var nextTrackCommand: Any?
  55. var previousTrackCommand: Any?
  56. // MARK: - View Life Cycle
  57. override func viewDidLoad() {
  58. super.viewDidLoad()
  59. navigationItem.rightBarButtonItem = UIBarButtonItem.init(image: UIImage(named: "more")!.image(color: NCBrandColor.shared.label, size: 25), style: .plain, target: self, action: #selector(self.openMenuMore))
  60. singleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didSingleTapWith(gestureRecognizer:)))
  61. panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(didPanWith(gestureRecognizer:)))
  62. longtapGestureRecognizer = UILongPressGestureRecognizer()
  63. longtapGestureRecognizer.delaysTouchesBegan = true
  64. longtapGestureRecognizer.minimumPressDuration = 0.3
  65. longtapGestureRecognizer.delegate = self
  66. longtapGestureRecognizer.addTarget(self, action: #selector(didLongpressGestureEvent(gestureRecognizer:)))
  67. pageViewController.delegate = self
  68. pageViewController.dataSource = self
  69. pageViewController.view.addGestureRecognizer(panGestureRecognizer)
  70. pageViewController.view.addGestureRecognizer(singleTapGestureRecognizer)
  71. pageViewController.view.addGestureRecognizer(longtapGestureRecognizer)
  72. let viewerMedia = getViewerMedia(index: currentIndex, image: getImageMetadata(metadatas[currentIndex]), metadata: metadatas[currentIndex], direction: .forward)
  73. pageViewController.setViewControllers([viewerMedia], direction: .forward, animated: true, completion: nil)
  74. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeTheming), object: nil)
  75. NotificationCenter.default.addObserver(self, selector: #selector(viewUnload), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMenuDetailClose), object: nil)
  76. progressView.tintColor = NCBrandColor.shared.brandElement
  77. progressView.trackTintColor = .clear
  78. progressView.progress = 0
  79. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  80. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  81. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  82. NotificationCenter.default.addObserver(self, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadedFile), object: nil)
  83. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterProgressTask), object:nil)
  84. NotificationCenter.default.addObserver(self, selector: #selector(hidePlayerToolBar(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterHidePlayerToolBar), object: nil)
  85. NotificationCenter.default.addObserver(self, selector: #selector(showPlayerToolBar(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterShowPlayerToolBar), object: nil)
  86. NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidBecomeActive), object: nil)
  87. }
  88. override func viewDidDisappear(_ animated: Bool) {
  89. super.viewDidDisappear(animated)
  90. // Clear
  91. if let ncplayer = currentViewController.ncplayer, ncplayer.isPlay() {
  92. ncplayer.playerPause()
  93. ncplayer.saveCurrentTime()
  94. }
  95. currentViewController.playerToolBar.stopTimerAutoHide()
  96. clearCommandCenter()
  97. metadatas.removeAll()
  98. ncplayerLivePhoto = nil
  99. // Remove Observer
  100. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  101. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  102. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  103. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadedFile), object: nil)
  104. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterProgressTask), object: nil)
  105. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterHidePlayerToolBar), object: nil)
  106. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterShowPlayerToolBar), object: nil)
  107. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidBecomeActive), object: nil)
  108. }
  109. override var preferredStatusBarStyle: UIStatusBarStyle {
  110. if currentScreenMode == .normal {
  111. return .default
  112. } else {
  113. return .lightContent
  114. }
  115. }
  116. // MARK: -
  117. func getViewerMedia(index: Int, image: UIImage?, metadata: tableMetadata, direction: UIPageViewController.NavigationDirection) -> NCViewerMedia {
  118. let viewerMedia = UIStoryboard(name: "NCViewerMediaPage", bundle: nil).instantiateViewController(withIdentifier: "NCViewerMedia") as! NCViewerMedia
  119. viewerMedia.index = index
  120. viewerMedia.image = image
  121. viewerMedia.metadata = metadata
  122. viewerMedia.viewerMediaPage = self
  123. singleTapGestureRecognizer.require(toFail: viewerMedia.doubleTapGestureRecognizer)
  124. return viewerMedia
  125. }
  126. @objc func viewUnload() {
  127. navigationController?.popViewController(animated: true)
  128. }
  129. @objc func openMenuMore() {
  130. let imageIcon = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(currentViewController.metadata.ocId, etag: currentViewController.metadata.etag))
  131. NCViewer.shared.toggleMenu(viewController: self, metadata: currentViewController.metadata, webView: false, imageIcon: imageIcon)
  132. }
  133. func changeScreenMode(mode: ScreenMode, enableTimerAutoHide: Bool = false) {
  134. if mode == .normal {
  135. navigationController?.setNavigationBarHidden(false, animated: true)
  136. progressView.isHidden = false
  137. if !currentViewController.detailView.isShow() {
  138. currentViewController.playerToolBar.show(enableTimerAutoHide: enableTimerAutoHide)
  139. }
  140. NCUtility.shared.colorNavigationController(navigationController, backgroundColor: NCBrandColor.shared.systemBackground, titleColor: NCBrandColor.shared.label, tintColor: nil, withoutShadow: false)
  141. view.backgroundColor = NCBrandColor.shared.systemBackground
  142. textColor = NCBrandColor.shared.label
  143. } else {
  144. navigationController?.setNavigationBarHidden(true, animated: true)
  145. progressView.isHidden = true
  146. currentViewController.playerToolBar.hide()
  147. view.backgroundColor = .black
  148. textColor = .white
  149. }
  150. currentScreenMode = mode
  151. if currentViewController.metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue {
  152. saveScreenModeImage = mode
  153. }
  154. setNeedsStatusBarAppearanceUpdate()
  155. currentViewController.reloadDetail()
  156. }
  157. //MARK: - NotificationCenter
  158. @objc func downloadedFile(_ notification: NSNotification) {
  159. progressView.progress = 0
  160. }
  161. @objc func triggerProgressTask(_ notification: NSNotification) {
  162. if let userInfo = notification.userInfo as NSDictionary? {
  163. if let serverUrl = userInfo["serverUrl"] as? String, let fileName = userInfo["fileName"] as? String, let progressNumber = userInfo["progress"] as? NSNumber {
  164. if self.metadatas.first(where: { $0.serverUrl == serverUrl && $0.fileName == fileName}) != nil {
  165. let progress = progressNumber.floatValue
  166. if progress == 1 {
  167. self.progressView.progress = 0
  168. } else {
  169. self.progressView.progress = progress
  170. }
  171. }
  172. }
  173. }
  174. }
  175. @objc func deleteFile(_ notification: NSNotification) {
  176. if let userInfo = notification.userInfo as NSDictionary? {
  177. if let ocId = userInfo["ocId"] as? String {
  178. let metadatas = self.metadatas.filter { $0.ocId != ocId }
  179. if self.metadatas.count == metadatas.count { return }
  180. self.metadatas = metadatas
  181. if ocId == currentViewController.metadata.ocId {
  182. if !shiftCurrentPage() {
  183. self.viewUnload()
  184. }
  185. }
  186. }
  187. }
  188. }
  189. @objc func renameFile(_ notification: NSNotification) {
  190. if let userInfo = notification.userInfo as NSDictionary? {
  191. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  192. if let index = metadatas.firstIndex(where: {$0.ocId == metadata.ocId}) {
  193. metadatas[index] = metadata
  194. if index == currentIndex {
  195. navigationItem.title = metadata.fileNameView
  196. currentViewController.metadata = metadata
  197. self.currentViewController.metadata = metadata
  198. }
  199. }
  200. }
  201. }
  202. }
  203. @objc func moveFile(_ notification: NSNotification) {
  204. if let userInfo = notification.userInfo as NSDictionary? {
  205. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  206. if metadatas.firstIndex(where: {$0.ocId == metadata.ocId}) != nil {
  207. deleteFile(notification)
  208. }
  209. }
  210. }
  211. }
  212. @objc func changeTheming() {
  213. }
  214. @objc func hidePlayerToolBar(_ notification: NSNotification) {
  215. if let userInfo = notification.userInfo as NSDictionary?, let ocId = userInfo["ocId"] as? String {
  216. if currentViewController.metadata.ocId == ocId {
  217. changeScreenMode(mode: .full)
  218. }
  219. }
  220. }
  221. @objc func showPlayerToolBar(_ notification: NSNotification) {
  222. if let userInfo = notification.userInfo as NSDictionary?, let ocId = userInfo["ocId"] as? String, let enableTimerAutoHide = userInfo["enableTimerAutoHide"] as? Bool{
  223. if currentViewController.metadata.ocId == ocId, let playerToolBar = currentViewController.playerToolBar, !playerToolBar.isPictureInPictureActive() {
  224. changeScreenMode(mode: .normal, enableTimerAutoHide: enableTimerAutoHide)
  225. }
  226. }
  227. }
  228. @objc func applicationDidBecomeActive(_ notification: NSNotification) {
  229. progressView.progress = 0
  230. }
  231. //MARK: - Image
  232. func getImageMetadata(_ metadata: tableMetadata) -> UIImage? {
  233. if let image = getImage(metadata: metadata) {
  234. return image
  235. }
  236. if metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue && !metadata.hasPreview {
  237. NCUtility.shared.createImageFrom(fileName: metadata.fileNameView, ocId: metadata.ocId, etag: metadata.etag, classFile: metadata.classFile)
  238. }
  239. if CCUtility.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag) {
  240. if let imagePreviewPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag) {
  241. return UIImage.init(contentsOfFile: imagePreviewPath)
  242. }
  243. }
  244. return nil
  245. }
  246. private func getImage(metadata: tableMetadata) -> UIImage? {
  247. let ext = CCUtility.getExtension(metadata.fileNameView)
  248. var image: UIImage?
  249. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) && metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue {
  250. let previewPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)!
  251. let imagePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  252. if ext == "GIF" {
  253. if !FileManager().fileExists(atPath: previewPath) {
  254. NCUtility.shared.createImageFrom(fileName: metadata.fileNameView, ocId: metadata.ocId, etag: metadata.etag, classFile: metadata.classFile)
  255. }
  256. image = UIImage.animatedImage(withAnimatedGIFURL: URL(fileURLWithPath: imagePath))
  257. } else if ext == "SVG" {
  258. if let svgImage = SVGKImage(contentsOfFile: imagePath) {
  259. svgImage.size = CGSize(width: NCGlobal.shared.sizePreview, height: NCGlobal.shared.sizePreview)
  260. if let image = svgImage.uiImage {
  261. if !FileManager().fileExists(atPath: previewPath) {
  262. do {
  263. try image.pngData()?.write(to: URL(fileURLWithPath: previewPath), options: .atomic)
  264. } catch { }
  265. }
  266. return image
  267. } else {
  268. return nil
  269. }
  270. } else {
  271. return nil
  272. }
  273. } else {
  274. NCUtility.shared.createImageFrom(fileName: metadata.fileNameView, ocId: metadata.ocId, etag: metadata.etag, classFile: metadata.classFile)
  275. image = UIImage.init(contentsOfFile: imagePath)
  276. }
  277. }
  278. return image
  279. }
  280. // MARK: - Command Center
  281. func updateCommandCenter(ncplayer: NCPlayer, metadata: tableMetadata) {
  282. var nowPlayingInfo = [String : Any]()
  283. // Clear
  284. clearCommandCenter()
  285. UIApplication.shared.beginReceivingRemoteControlEvents()
  286. // Add handler for Play Command
  287. MPRemoteCommandCenter.shared().playCommand.isEnabled = true
  288. playCommand = MPRemoteCommandCenter.shared().playCommand.addTarget { event in
  289. if !ncplayer.isPlay() {
  290. ncplayer.playerPlay()
  291. return .success
  292. }
  293. return .commandFailed
  294. }
  295. // Add handler for Pause Command
  296. MPRemoteCommandCenter.shared().pauseCommand.isEnabled = true
  297. pauseCommand = MPRemoteCommandCenter.shared().pauseCommand.addTarget { event in
  298. if ncplayer.isPlay() {
  299. ncplayer.playerPause()
  300. return .success
  301. }
  302. return .commandFailed
  303. }
  304. // VIDEO / AUDIO () ()
  305. if metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue {
  306. MPRemoteCommandCenter.shared().skipForwardCommand.isEnabled = true
  307. skipForwardCommand = MPRemoteCommandCenter.shared().skipForwardCommand.addTarget { event in
  308. let seconds = Float64((event as! MPSkipIntervalCommandEvent).interval)
  309. self.currentViewController.playerToolBar.skip(seconds: seconds)
  310. return.success
  311. }
  312. MPRemoteCommandCenter.shared().skipBackwardCommand.isEnabled = true
  313. skipBackwardCommand = MPRemoteCommandCenter.shared().skipBackwardCommand.addTarget { event in
  314. let seconds = Float64((event as! MPSkipIntervalCommandEvent).interval)
  315. self.currentViewController.playerToolBar.skip(seconds: -seconds)
  316. return.success
  317. }
  318. }
  319. // AUDIO < >
  320. /*
  321. if metadata?.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue {
  322. MPRemoteCommandCenter.shared().nextTrackCommand.isEnabled = true
  323. appDelegate.nextTrackCommand = MPRemoteCommandCenter.shared().nextTrackCommand.addTarget { event in
  324. self.forward()
  325. return .success
  326. }
  327. MPRemoteCommandCenter.shared().previousTrackCommand.isEnabled = true
  328. appDelegate.previousTrackCommand = MPRemoteCommandCenter.shared().previousTrackCommand.addTarget { event in
  329. self.backward()
  330. return .success
  331. }
  332. }
  333. */
  334. nowPlayingInfo[MPMediaItemPropertyTitle] = metadata.fileNameView
  335. nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = ncplayer.durationTime.seconds
  336. if let image = currentViewController.image {
  337. nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { size in
  338. return image
  339. }
  340. }
  341. MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
  342. }
  343. func clearCommandCenter() {
  344. UIApplication.shared.endReceivingRemoteControlEvents()
  345. MPNowPlayingInfoCenter.default().nowPlayingInfo = [:]
  346. MPRemoteCommandCenter.shared().playCommand.isEnabled = false
  347. MPRemoteCommandCenter.shared().pauseCommand.isEnabled = false
  348. MPRemoteCommandCenter.shared().skipForwardCommand.isEnabled = false
  349. MPRemoteCommandCenter.shared().skipBackwardCommand.isEnabled = false
  350. MPRemoteCommandCenter.shared().nextTrackCommand.isEnabled = false
  351. MPRemoteCommandCenter.shared().previousTrackCommand.isEnabled = false
  352. if let playCommand = playCommand {
  353. MPRemoteCommandCenter.shared().playCommand.removeTarget(playCommand)
  354. self.playCommand = nil
  355. }
  356. if let pauseCommand = pauseCommand {
  357. MPRemoteCommandCenter.shared().pauseCommand.removeTarget(pauseCommand)
  358. self.pauseCommand = nil
  359. }
  360. if let skipForwardCommand = skipForwardCommand {
  361. MPRemoteCommandCenter.shared().skipForwardCommand.removeTarget(skipForwardCommand)
  362. self.skipForwardCommand = nil
  363. }
  364. if let skipBackwardCommand = skipBackwardCommand {
  365. MPRemoteCommandCenter.shared().skipBackwardCommand.removeTarget(skipBackwardCommand)
  366. self.skipBackwardCommand = nil
  367. }
  368. if let nextTrackCommand = nextTrackCommand {
  369. MPRemoteCommandCenter.shared().nextTrackCommand.removeTarget(nextTrackCommand)
  370. self.nextTrackCommand = nil
  371. }
  372. if let previousTrackCommand = previousTrackCommand {
  373. MPRemoteCommandCenter.shared().previousTrackCommand.removeTarget(previousTrackCommand)
  374. self.previousTrackCommand = nil
  375. }
  376. }
  377. }
  378. // MARK: - UIPageViewController Delegate Datasource
  379. extension NCViewerMediaPage: UIPageViewControllerDelegate, UIPageViewControllerDataSource {
  380. func shiftCurrentPage() -> Bool {
  381. if metadatas.count == 0 { return false }
  382. var direction: UIPageViewController.NavigationDirection = .forward
  383. if currentIndex == metadatas.count {
  384. currentIndex -= 1
  385. direction = .reverse
  386. }
  387. currentViewController.ncplayer?.deactivateObserver()
  388. let viewerMedia = getViewerMedia(index: currentIndex, image: getImageMetadata(metadatas[currentIndex]), metadata: metadatas[currentIndex], direction: direction)
  389. pageViewController.setViewControllers([viewerMedia], direction: direction, animated: true, completion: nil)
  390. return true
  391. }
  392. func goTo(index: Int, direction: UIPageViewController.NavigationDirection, autoPlay: Bool) {
  393. currentIndex = index
  394. currentViewController.ncplayer?.deactivateObserver()
  395. let viewerMedia = getViewerMedia(index: currentIndex, image: getImageMetadata(metadatas[currentIndex]), metadata: metadatas[currentIndex], direction: direction)
  396. viewerMedia.autoPlay = autoPlay
  397. pageViewController.setViewControllers([viewerMedia], direction: direction, animated: true, completion: nil)
  398. }
  399. func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
  400. if currentIndex == 0 { return nil }
  401. let viewerMedia = getViewerMedia(index: currentIndex-1, image: getImageMetadata(metadatas[currentIndex-1]), metadata: metadatas[currentIndex-1], direction: .reverse)
  402. return viewerMedia
  403. }
  404. func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
  405. if currentIndex == metadatas.count-1 { return nil }
  406. let viewerMedia = getViewerMedia(index: currentIndex+1, image: getImageMetadata(metadatas[currentIndex+1]), metadata: metadatas[currentIndex+1], direction: .forward)
  407. return viewerMedia
  408. }
  409. // START TRANSITION
  410. func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
  411. // Save time video
  412. if let ncplayer = currentViewController.ncplayer, ncplayer.isPlay() {
  413. ncplayer.saveCurrentTime()
  414. }
  415. guard let nextViewController = pendingViewControllers.first as? NCViewerMedia else { return }
  416. nextIndex = nextViewController.index
  417. }
  418. // END TRANSITION
  419. func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
  420. if (completed && nextIndex != nil) {
  421. previousViewControllers.forEach { viewController in
  422. let viewerMedia = viewController as! NCViewerMedia
  423. viewerMedia.ncplayer?.deactivateObserver()
  424. }
  425. currentIndex = nextIndex!
  426. }
  427. self.nextIndex = nil
  428. }
  429. }
  430. //MARK: - UIGestureRecognizerDelegate
  431. extension NCViewerMediaPage: UIGestureRecognizerDelegate {
  432. func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
  433. if let gestureRecognizer = gestureRecognizer as? UIPanGestureRecognizer {
  434. let velocity = gestureRecognizer.velocity(in: self.view)
  435. var velocityCheck : Bool = false
  436. if UIDevice.current.orientation.isLandscape {
  437. velocityCheck = velocity.x < 0
  438. }
  439. else {
  440. velocityCheck = velocity.y < 0
  441. }
  442. if velocityCheck {
  443. return false
  444. }
  445. }
  446. return true
  447. }
  448. func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
  449. if otherGestureRecognizer == currentViewController.scrollView.panGestureRecognizer {
  450. if self.currentViewController.scrollView.contentOffset.y == 0 {
  451. return true
  452. }
  453. }
  454. return false
  455. }
  456. @objc func didPanWith(gestureRecognizer: UIPanGestureRecognizer) {
  457. currentViewController.didPanWith(gestureRecognizer: gestureRecognizer)
  458. }
  459. @objc func didSingleTapWith(gestureRecognizer: UITapGestureRecognizer) {
  460. if let playerToolBar = currentViewController.playerToolBar, playerToolBar.isPictureInPictureActive() {
  461. playerToolBar.pictureInPictureController?.stopPictureInPicture()
  462. }
  463. if currentScreenMode == .full {
  464. changeScreenMode(mode: .normal, enableTimerAutoHide: true)
  465. } else {
  466. changeScreenMode(mode: .full)
  467. }
  468. }
  469. //
  470. // LIVE PHOTO
  471. //
  472. @objc func didLongpressGestureEvent(gestureRecognizer: UITapGestureRecognizer) {
  473. if !currentViewController.metadata.livePhoto { return }
  474. if gestureRecognizer.state == .began {
  475. currentViewController.updateViewConstraints()
  476. currentViewController.statusViewImage.isHidden = true
  477. currentViewController.statusLabel.isHidden = true
  478. let fileName = (currentViewController.metadata.fileNameView as NSString).deletingPathExtension + ".mov"
  479. if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView LIKE[c] %@", currentViewController.metadata.account, currentViewController.metadata.serverUrl, fileName)) {
  480. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  481. AudioServicesPlaySystemSound(1519) // peek feedback
  482. if let url = NCKTVHTTPCache.shared.getVideoURL(metadata: metadata) {
  483. self.ncplayerLivePhoto = NCPlayer.init(url: url, autoPlay: true, imageVideoContainer: self.currentViewController.imageVideoContainer, playerToolBar: nil, metadata: metadata, detailView: nil)
  484. }
  485. } else {
  486. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileNameView
  487. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  488. NCCommunication.shared.download(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, requestHandler: { (_) in
  489. }, taskHandler: { (_) in
  490. }, progressHandler: { (progress) in
  491. self.progressView.progress = Float(progress.fractionCompleted)
  492. }) { (account, etag, date, length, allHeaderFields, error, errorCode, errorDescription) in
  493. self.progressView.progress = 0
  494. if errorCode == 0 && account == metadata.account {
  495. NCManageDatabase.shared.addLocalFile(metadata: metadata)
  496. if gestureRecognizer.state == .changed || gestureRecognizer.state == .began {
  497. AudioServicesPlaySystemSound(1519) // peek feedback
  498. if let url = NCKTVHTTPCache.shared.getVideoURL(metadata: metadata) {
  499. self.ncplayerLivePhoto = NCPlayer.init(url: url, autoPlay: true, imageVideoContainer: self.currentViewController.imageVideoContainer, playerToolBar: nil, metadata: metadata, detailView: nil)
  500. }
  501. }
  502. }
  503. }
  504. }
  505. }
  506. } else if gestureRecognizer.state == .ended {
  507. currentViewController.statusViewImage.isHidden = false
  508. currentViewController.statusLabel.isHidden = false
  509. currentViewController.imageVideoContainer.image = currentViewController.image
  510. ncplayerLivePhoto?.videoLayer?.removeFromSuperlayer()
  511. ncplayerLivePhoto?.deactivateObserver()
  512. }
  513. }
  514. }