NCViewerMediaPage.swift 28 KB

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