NCViewerMediaPage.swift 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  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 NextcloudKit
  25. import MediaPlayer
  26. import Alamofire
  27. import JGProgressHUD
  28. enum ScreenMode {
  29. case full, normal
  30. }
  31. var viewerMediaScreenMode: ScreenMode = .normal
  32. class NCViewerMediaPage: UIViewController {
  33. @IBOutlet weak var progressView: UIProgressView!
  34. // swiftlint:disable force_cast
  35. var pageViewController: UIPageViewController {
  36. return self.children[0] as! UIPageViewController
  37. }
  38. var currentViewController: NCViewerMedia {
  39. return self.pageViewController.viewControllers![0] as! NCViewerMedia
  40. }
  41. // swiftlint:enable force_cast
  42. private var hideStatusBar: Bool = false {
  43. didSet {
  44. setNeedsStatusBarAppearanceUpdate()
  45. }
  46. }
  47. var metadatas: [tableMetadata] = []
  48. var modifiedOcId: [String] = []
  49. var currentIndex = 0
  50. var nextIndex: Int?
  51. var panGestureRecognizer: UIPanGestureRecognizer!
  52. var singleTapGestureRecognizer: UITapGestureRecognizer!
  53. var longtapGestureRecognizer: UILongPressGestureRecognizer!
  54. var textColor: UIColor = .label
  55. var playCommand: Any?
  56. var pauseCommand: Any?
  57. var skipForwardCommand: Any?
  58. var skipBackwardCommand: Any?
  59. var nextTrackCommand: Any?
  60. var previousTrackCommand: Any?
  61. let utilityFileSystem = NCUtilityFileSystem()
  62. var timerAutoHide: Timer?
  63. private var timerAutoHideSeconds: Double = 4
  64. private lazy var moreNavigationItem = UIBarButtonItem(image: UIImage(named: "more")!.image(color: .label, size: 25), style: .plain, target: self, action: #selector(openMenuMore))
  65. private lazy var imageDetailNavigationItem = UIBarButtonItem(image: UIImage(systemName: "info.circle")!.image(color: .label, size: 22), style: .plain, target: self, action: #selector(toggleDetail))
  66. // MARK: - View Life Cycle
  67. override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
  68. super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
  69. viewerMediaScreenMode = .normal
  70. }
  71. required init?(coder: NSCoder) {
  72. super.init(coder: coder)
  73. viewerMediaScreenMode = .normal
  74. }
  75. override func viewDidLoad() {
  76. super.viewDidLoad()
  77. singleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didSingleTapWith(gestureRecognizer:)))
  78. panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(didPanWith(gestureRecognizer:)))
  79. longtapGestureRecognizer = UILongPressGestureRecognizer()
  80. longtapGestureRecognizer.delaysTouchesBegan = true
  81. longtapGestureRecognizer.minimumPressDuration = 0.3
  82. longtapGestureRecognizer.delegate = self
  83. longtapGestureRecognizer.addTarget(self, action: #selector(didLongpressGestureEvent(gestureRecognizer:)))
  84. pageViewController.delegate = self
  85. pageViewController.dataSource = self
  86. pageViewController.view.addGestureRecognizer(panGestureRecognizer)
  87. pageViewController.view.addGestureRecognizer(singleTapGestureRecognizer)
  88. pageViewController.view.addGestureRecognizer(longtapGestureRecognizer)
  89. progressView.tintColor = NCBrandColor.shared.brand
  90. progressView.trackTintColor = .clear
  91. progressView.progress = 0
  92. let viewerMedia = getViewerMedia(index: currentIndex, metadata: metadatas[currentIndex])
  93. pageViewController.setViewControllers([viewerMedia], direction: .forward, animated: true, completion: nil)
  94. changeScreenMode(mode: viewerMediaScreenMode)
  95. NotificationCenter.default.addObserver(self, selector: #selector(viewUnload), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeUser), object: nil)
  96. NotificationCenter.default.addObserver(self, selector: #selector(pageViewController.enableSwipeGesture), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterEnableSwipeGesture), object: nil)
  97. NotificationCenter.default.addObserver(self, selector: #selector(pageViewController.disableSwipeGesture), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDisableSwipeGesture), object: nil)
  98. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  99. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  100. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  101. NotificationCenter.default.addObserver(self, selector: #selector(copyFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCopyFile), object: nil)
  102. NotificationCenter.default.addObserver(self, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadedFile), object: nil)
  103. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterProgressTask), object: nil)
  104. NotificationCenter.default.addObserver(self, selector: #selector(uploadStartFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadStartFile), object: nil)
  105. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  106. NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidBecomeActive), object: nil)
  107. if currentViewController.metadata.isImage {
  108. navigationItem.rightBarButtonItems = [moreNavigationItem, imageDetailNavigationItem]
  109. } else {
  110. navigationItem.rightBarButtonItems = [moreNavigationItem]
  111. }
  112. }
  113. deinit {
  114. timerAutoHide?.invalidate()
  115. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterEnableSwipeGesture), object: nil)
  116. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDisableSwipeGesture), object: nil)
  117. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  118. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  119. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  120. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCopyFile), object: nil)
  121. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadedFile), object: nil)
  122. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterProgressTask), object: nil)
  123. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadStartFile), object: nil)
  124. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  125. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidBecomeActive), object: nil)
  126. }
  127. override func viewDidAppear(_ animated: Bool) {
  128. super.viewDidAppear(animated)
  129. startTimerAutoHide()
  130. }
  131. override func viewDidDisappear(_ animated: Bool) {
  132. super.viewDidDisappear(animated)
  133. currentViewController.ncplayer?.playerStop()
  134. timerAutoHide?.invalidate()
  135. clearCommandCenter()
  136. }
  137. override var preferredStatusBarStyle: UIStatusBarStyle {
  138. if viewerMediaScreenMode == .normal {
  139. return .default
  140. } else {
  141. return .lightContent
  142. }
  143. }
  144. override var prefersHomeIndicatorAutoHidden: Bool {
  145. return viewerMediaScreenMode == .full
  146. }
  147. override var prefersStatusBarHidden: Bool {
  148. return hideStatusBar
  149. }
  150. func getViewerMedia(index: Int, metadata: tableMetadata) -> NCViewerMedia {
  151. // swiftlint:disable force_cast
  152. let viewerMedia = UIStoryboard(name: "NCViewerMediaPage", bundle: nil).instantiateViewController(withIdentifier: "NCViewerMedia") as! NCViewerMedia
  153. // swiftlint:enable force_cast
  154. viewerMedia.index = index
  155. viewerMedia.metadata = metadata
  156. viewerMedia.viewerMediaPage = self
  157. viewerMedia.delegate = self
  158. singleTapGestureRecognizer.require(toFail: viewerMedia.doubleTapGestureRecognizer)
  159. return viewerMedia
  160. }
  161. @objc func viewUnload() {
  162. navigationController?.popViewController(animated: true)
  163. }
  164. @objc private func openMenuMore() {
  165. let imageIcon = UIImage(contentsOfFile: utilityFileSystem.getDirectoryProviderStorageIconOcId(currentViewController.metadata.ocId, etag: currentViewController.metadata.etag))
  166. NCViewer().toggleMenu(viewController: self, metadata: currentViewController.metadata, webView: false, imageIcon: imageIcon)
  167. }
  168. @objc private func toggleDetail() {
  169. currentViewController.toggleDetail()
  170. }
  171. func changeScreenMode(mode: ScreenMode) {
  172. let metadata = currentViewController.metadata
  173. let fullscreen = currentViewController.playerToolBar?.isFullscreen ?? false
  174. if mode == .normal {
  175. if fullscreen {
  176. navigationController?.setNavigationBarHidden(true, animated: true)
  177. hideStatusBar = true
  178. progressView.isHidden = true
  179. } else {
  180. navigationController?.setNavigationBarHidden(false, animated: true)
  181. hideStatusBar = false
  182. progressView.isHidden = false
  183. }
  184. if metadata.isAudioOrVideo {
  185. colorNavigationController(backgroundColor: .black, titleColor: .label, tintColor: nil, withoutShadow: false)
  186. currentViewController.playerToolBar?.show()
  187. view.backgroundColor = .black
  188. textColor = .white
  189. } else {
  190. colorNavigationController(backgroundColor: .systemBackground, titleColor: .label, tintColor: nil, withoutShadow: false)
  191. view.backgroundColor = .systemGray6
  192. textColor = .label
  193. }
  194. } else if !currentViewController.detailView.isShown {
  195. navigationController?.setNavigationBarHidden(true, animated: true)
  196. hideStatusBar = true
  197. progressView.isHidden = true
  198. if metadata.isVideo {
  199. currentViewController.playerToolBar?.hide()
  200. }
  201. view.backgroundColor = .black
  202. textColor = .white
  203. }
  204. if fullscreen {
  205. pageViewController.disableSwipeGesture()
  206. } else {
  207. pageViewController.enableSwipeGesture()
  208. }
  209. viewerMediaScreenMode = mode
  210. print("Screen mode: \(viewerMediaScreenMode)")
  211. startTimerAutoHide()
  212. setNeedsStatusBarAppearanceUpdate()
  213. setNeedsUpdateOfHomeIndicatorAutoHidden()
  214. currentViewController.reloadDetail()
  215. }
  216. @objc func startTimerAutoHide() {
  217. timerAutoHide?.invalidate()
  218. timerAutoHide = Timer.scheduledTimer(timeInterval: timerAutoHideSeconds, target: self, selector: #selector(autoHide), userInfo: nil, repeats: true)
  219. }
  220. @objc func autoHide() {
  221. let metadata = currentViewController.metadata
  222. if metadata.isVideo, viewerMediaScreenMode == .normal {
  223. changeScreenMode(mode: .full)
  224. }
  225. }
  226. func colorNavigationController(backgroundColor: UIColor, titleColor: UIColor, tintColor: UIColor?, withoutShadow: Bool) {
  227. let appearance = UINavigationBarAppearance()
  228. appearance.titleTextAttributes = [.foregroundColor: titleColor]
  229. appearance.largeTitleTextAttributes = [.foregroundColor: titleColor]
  230. if withoutShadow {
  231. appearance.shadowColor = .clear
  232. appearance.shadowImage = UIImage()
  233. }
  234. if let tintColor = tintColor {
  235. navigationController?.navigationBar.tintColor = tintColor
  236. }
  237. navigationController?.view.backgroundColor = backgroundColor
  238. navigationController?.navigationBar.barTintColor = titleColor
  239. navigationController?.navigationBar.standardAppearance = appearance
  240. navigationController?.navigationBar.compactAppearance = appearance
  241. navigationController?.navigationBar.scrollEdgeAppearance = appearance
  242. }
  243. // MARK: - NotificationCenter
  244. @objc func downloadedFile(_ notification: NSNotification) {
  245. guard let userInfo = notification.userInfo as NSDictionary?,
  246. let ocId = userInfo["ocId"] as? String
  247. else {
  248. return
  249. }
  250. DispatchQueue.main.async {
  251. self.progressView.progress = 0
  252. let metadata = self.currentViewController.metadata
  253. guard metadata.ocId == ocId, self.utilityFileSystem.fileProviderStorageExists(metadata) else { return }
  254. if metadata.isAudioOrVideo, let ncplayer = self.currentViewController.ncplayer {
  255. let url = URL(fileURLWithPath: self.utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  256. if ncplayer.isPlay() {
  257. ncplayer.playerPause()
  258. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  259. ncplayer.openAVPlayer(url: url)
  260. ncplayer.playerPlay()
  261. }
  262. } else {
  263. ncplayer.openAVPlayer(url: url)
  264. }
  265. } else if metadata.isImage {
  266. self.currentViewController.loadImage()
  267. }
  268. }
  269. }
  270. @objc func triggerProgressTask(_ notification: NSNotification) {
  271. guard let userInfo = notification.userInfo as NSDictionary?,
  272. let progressNumber = userInfo["progress"] as? NSNumber
  273. else { return }
  274. DispatchQueue.main.async {
  275. let progress = progressNumber.floatValue
  276. if progress == 1 {
  277. self.progressView.progress = 0
  278. } else {
  279. self.progressView.progress = progress
  280. }
  281. }
  282. }
  283. @objc func uploadStartFile(_ notification: NSNotification) { }
  284. @objc func uploadedFile(_ notification: NSNotification) {
  285. guard let userInfo = notification.userInfo as NSDictionary?,
  286. let ocId = userInfo["ocId"] as? String,
  287. let error = userInfo["error"] as? NKError,
  288. error == .success,
  289. let index = metadatas.firstIndex(where: {$0.ocId == ocId}),
  290. let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId)
  291. else {
  292. return
  293. }
  294. DispatchQueue.main.async {
  295. self.metadatas[index] = metadata
  296. if self.currentViewController.metadata.ocId == ocId {
  297. self.currentViewController.loadImage()
  298. } else {
  299. self.modifiedOcId.append(ocId)
  300. }
  301. }
  302. }
  303. @objc func deleteFile(_ notification: NSNotification) {
  304. guard let userInfo = notification.userInfo as NSDictionary? else { return }
  305. if let ocIds = userInfo["ocId"] as? [String],
  306. let ocId = ocIds.first {
  307. // Stop media
  308. if let ncplayer = currentViewController.ncplayer, ncplayer.isPlay() {
  309. ncplayer.playerPause()
  310. }
  311. let metadatas = self.metadatas.filter { $0.ocId != ocId }
  312. if self.metadatas.count == metadatas.count { return }
  313. self.metadatas = metadatas
  314. if ocId == currentViewController.metadata.ocId {
  315. shiftCurrentPage()
  316. }
  317. }
  318. }
  319. @objc func moveFile(_ notification: NSNotification) {
  320. deleteFile(notification)
  321. }
  322. @objc func copyFile(_ notification: NSNotification) {
  323. guard let userInfo = notification.userInfo as NSDictionary?,
  324. let error = userInfo["error"] as? NKError else { return }
  325. if error != .success {
  326. NCContentPresenter().showError(error: error)
  327. }
  328. }
  329. @objc func renameFile(_ notification: NSNotification) {
  330. guard let userInfo = notification.userInfo as NSDictionary?,
  331. let ocId = userInfo["ocId"] as? String,
  332. let index = metadatas.firstIndex(where: {$0.ocId == ocId}),
  333. let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId)
  334. else { return }
  335. // Stop media
  336. if let ncplayer = currentViewController.ncplayer, ncplayer.isPlay() {
  337. ncplayer.playerPause()
  338. }
  339. metadatas[index] = metadata
  340. if index == currentIndex {
  341. navigationItem.title = metadata.fileNameView
  342. currentViewController.metadata = metadata
  343. self.currentViewController.metadata = metadata
  344. }
  345. }
  346. @objc func applicationDidBecomeActive(_ notification: NSNotification) {
  347. progressView.progress = 0
  348. changeScreenMode(mode: .normal)
  349. }
  350. // MARK: - Command Center
  351. func updateCommandCenter(ncplayer: NCPlayer, title: String) {
  352. var nowPlayingInfo = [String: Any]()
  353. UIApplication.shared.beginReceivingRemoteControlEvents()
  354. // Add handler for Play Command
  355. MPRemoteCommandCenter.shared().playCommand.isEnabled = true
  356. playCommand = MPRemoteCommandCenter.shared().playCommand.addTarget { _ in
  357. if !ncplayer.isPlay() {
  358. ncplayer.playerPlay()
  359. return .success
  360. }
  361. return .commandFailed
  362. }
  363. // Add handler for Pause Command
  364. MPRemoteCommandCenter.shared().pauseCommand.isEnabled = true
  365. pauseCommand = MPRemoteCommandCenter.shared().pauseCommand.addTarget { _ in
  366. if ncplayer.isPlay() {
  367. ncplayer.playerPause()
  368. return .success
  369. }
  370. return .commandFailed
  371. }
  372. // >>
  373. MPRemoteCommandCenter.shared().skipForwardCommand.isEnabled = true
  374. skipForwardCommand = MPRemoteCommandCenter.shared().skipForwardCommand.addTarget { event in
  375. let seconds = Int32((event as? MPSkipIntervalCommandEvent)?.interval ?? 0)
  376. ncplayer.player.jumpForward(seconds)
  377. return.success
  378. }
  379. // <<
  380. MPRemoteCommandCenter.shared().skipBackwardCommand.isEnabled = true
  381. skipBackwardCommand = MPRemoteCommandCenter.shared().skipBackwardCommand.addTarget { event in
  382. let seconds = Int32((event as? MPSkipIntervalCommandEvent)?.interval ?? 0)
  383. ncplayer.player.jumpBackward(seconds)
  384. return.success
  385. }
  386. nowPlayingInfo[MPMediaItemPropertyTitle] = title
  387. if let image = currentViewController.image {
  388. nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { _ in
  389. return image
  390. }
  391. }
  392. MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
  393. }
  394. func clearCommandCenter() {
  395. UIApplication.shared.endReceivingRemoteControlEvents()
  396. MPNowPlayingInfoCenter.default().nowPlayingInfo = [:]
  397. MPRemoteCommandCenter.shared().playCommand.isEnabled = false
  398. MPRemoteCommandCenter.shared().pauseCommand.isEnabled = false
  399. MPRemoteCommandCenter.shared().skipForwardCommand.isEnabled = false
  400. MPRemoteCommandCenter.shared().skipBackwardCommand.isEnabled = false
  401. MPRemoteCommandCenter.shared().nextTrackCommand.isEnabled = false
  402. MPRemoteCommandCenter.shared().previousTrackCommand.isEnabled = false
  403. if let playCommand = playCommand {
  404. MPRemoteCommandCenter.shared().playCommand.removeTarget(playCommand)
  405. self.playCommand = nil
  406. }
  407. if let pauseCommand = pauseCommand {
  408. MPRemoteCommandCenter.shared().pauseCommand.removeTarget(pauseCommand)
  409. self.pauseCommand = nil
  410. }
  411. if let skipForwardCommand = skipForwardCommand {
  412. MPRemoteCommandCenter.shared().skipForwardCommand.removeTarget(skipForwardCommand)
  413. self.skipForwardCommand = nil
  414. }
  415. if let skipBackwardCommand = skipBackwardCommand {
  416. MPRemoteCommandCenter.shared().skipBackwardCommand.removeTarget(skipBackwardCommand)
  417. self.skipBackwardCommand = nil
  418. }
  419. if let nextTrackCommand = nextTrackCommand {
  420. MPRemoteCommandCenter.shared().nextTrackCommand.removeTarget(nextTrackCommand)
  421. self.nextTrackCommand = nil
  422. }
  423. if let previousTrackCommand = previousTrackCommand {
  424. MPRemoteCommandCenter.shared().previousTrackCommand.removeTarget(previousTrackCommand)
  425. self.previousTrackCommand = nil
  426. }
  427. }
  428. }
  429. // MARK: - UIPageViewController Delegate Datasource
  430. extension NCViewerMediaPage: UIPageViewControllerDelegate, UIPageViewControllerDataSource {
  431. func shiftCurrentPage() {
  432. if metadatas.isEmpty {
  433. self.viewUnload()
  434. return
  435. }
  436. var direction: UIPageViewController.NavigationDirection = .forward
  437. if currentIndex == metadatas.count {
  438. currentIndex -= 1
  439. direction = .reverse
  440. }
  441. let viewerMedia = getViewerMedia(index: currentIndex, metadata: metadatas[currentIndex])
  442. pageViewController.setViewControllers([viewerMedia], direction: direction, animated: true, completion: nil)
  443. }
  444. func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
  445. if currentIndex == 0 { return nil }
  446. let viewerMedia = getViewerMedia(index: currentIndex - 1, metadata: metadatas[currentIndex - 1])
  447. return viewerMedia
  448. }
  449. func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
  450. if currentIndex == metadatas.count - 1 { return nil }
  451. let viewerMedia = getViewerMedia(index: currentIndex + 1, metadata: metadatas[currentIndex + 1])
  452. return viewerMedia
  453. }
  454. // START TRANSITION
  455. func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
  456. guard let nextViewController = pendingViewControllers.first as? NCViewerMedia else { return }
  457. nextIndex = nextViewController.index
  458. if nextViewController.metadata.isImage {
  459. navigationItem.rightBarButtonItems = [moreNavigationItem, imageDetailNavigationItem]
  460. } else {
  461. navigationItem.rightBarButtonItems = [moreNavigationItem]
  462. }
  463. if nextViewController.detailView.isShown {
  464. changeScreenMode(mode: .normal)
  465. }
  466. }
  467. // END TRANSITION
  468. func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
  469. if completed && nextIndex != nil {
  470. previousViewControllers.forEach { viewController in
  471. let viewerMedia = viewController as? NCViewerMedia
  472. viewerMedia?.ncplayer?.playerStop()
  473. viewerMedia?.closeDetail()
  474. }
  475. currentIndex = nextIndex!
  476. }
  477. changeScreenMode(mode: viewerMediaScreenMode)
  478. startTimerAutoHide()
  479. self.nextIndex = nil
  480. }
  481. }
  482. // MARK: - UIGestureRecognizerDelegate
  483. extension NCViewerMediaPage: UIGestureRecognizerDelegate {
  484. func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
  485. if let gestureRecognizer = gestureRecognizer as? UIPanGestureRecognizer {
  486. let velocity = gestureRecognizer.velocity(in: self.view)
  487. var velocityCheck: Bool = false
  488. if UIDevice.current.orientation.isLandscape {
  489. velocityCheck = velocity.x < 0
  490. } else {
  491. velocityCheck = velocity.y < 0
  492. }
  493. if velocityCheck {
  494. return false
  495. }
  496. }
  497. return true
  498. }
  499. func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
  500. if otherGestureRecognizer == currentViewController.scrollView.panGestureRecognizer {
  501. if self.currentViewController.scrollView.contentOffset.y == 0 {
  502. return true
  503. }
  504. }
  505. return false
  506. }
  507. @objc func didPanWith(gestureRecognizer: UIPanGestureRecognizer) {
  508. currentViewController.didPanWith(gestureRecognizer: gestureRecognizer)
  509. }
  510. @objc func didSingleTapWith(gestureRecognizer: UITapGestureRecognizer) {
  511. if currentViewController.detailView.isShown { return }
  512. if viewerMediaScreenMode == .full {
  513. changeScreenMode(mode: .normal)
  514. } else {
  515. changeScreenMode(mode: .full)
  516. }
  517. }
  518. // MARK: - Live Photo
  519. @objc func didLongpressGestureEvent(gestureRecognizer: UITapGestureRecognizer) {
  520. if !currentViewController.metadata.isLivePhoto || currentViewController.detailView.isShown { return }
  521. if gestureRecognizer.state == .began {
  522. if let metadataLive = NCManageDatabase.shared.getMetadataLivePhoto(metadata: currentViewController.metadata),
  523. utilityFileSystem.fileProviderStorageExists(metadataLive) {
  524. AudioServicesPlaySystemSound(1519) // peek feedback
  525. currentViewController.playLivePhoto(filePath: utilityFileSystem.getDirectoryProviderStorageOcId(metadataLive.ocId, fileNameView: metadataLive.fileName))
  526. }
  527. } else if gestureRecognizer.state == .ended {
  528. currentViewController.stopLivePhoto()
  529. }
  530. }
  531. }
  532. extension UIPageViewController {
  533. @objc func enableSwipeGesture() {
  534. for view in self.view.subviews {
  535. if let subView = view as? UIScrollView {
  536. subView.isScrollEnabled = true
  537. }
  538. }
  539. }
  540. @objc func disableSwipeGesture() {
  541. for view in self.view.subviews {
  542. if let subView = view as? UIScrollView {
  543. subView.isScrollEnabled = false
  544. }
  545. }
  546. }
  547. }
  548. extension NCViewerMediaPage: NCViewerMediaViewDelegate {
  549. func didOpenDetail() {
  550. changeScreenMode(mode: .normal)
  551. imageDetailNavigationItem.image = UIImage(systemName: "info.circle.fill")
  552. }
  553. func didCloseDetail() {
  554. imageDetailNavigationItem.image = UIImage(systemName: "info.circle")
  555. }
  556. }