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 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. progressView.progress = 0
  251. let metadata = currentViewController.metadata
  252. if metadata.ocId == ocId,
  253. metadata.isAudioOrVideo,
  254. utilityFileSystem.fileProviderStorageExists(metadata),
  255. let ncplayer = currentViewController.ncplayer {
  256. let url = URL(fileURLWithPath: utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  257. if ncplayer.isPlay() {
  258. ncplayer.playerPause()
  259. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  260. ncplayer.openAVPlayer(url: url)
  261. ncplayer.playerPlay()
  262. }
  263. } else {
  264. ncplayer.openAVPlayer(url: url)
  265. }
  266. }
  267. }
  268. @objc func triggerProgressTask(_ notification: NSNotification) {
  269. guard let userInfo = notification.userInfo as NSDictionary?,
  270. let progressNumber = userInfo["progress"] as? NSNumber
  271. else { return }
  272. let progress = progressNumber.floatValue
  273. if progress == 1 {
  274. self.progressView.progress = 0
  275. } else {
  276. self.progressView.progress = progress
  277. }
  278. }
  279. @objc func uploadStartFile(_ notification: NSNotification) {
  280. /*
  281. guard let userInfo = notification.userInfo as NSDictionary?,
  282. let serverUrl = userInfo["serverUrl"] as? String,
  283. let fileName = userInfo["fileName"] as? String,
  284. let sessionSelector = userInfo["sessionSelector"] as? String
  285. else { return }
  286. */
  287. }
  288. @objc func uploadedFile(_ notification: NSNotification) {
  289. guard let userInfo = notification.userInfo as NSDictionary?,
  290. let ocId = userInfo["ocId"] as? String,
  291. let error = userInfo["error"] as? NKError,
  292. error == .success,
  293. let index = metadatas.firstIndex(where: {$0.ocId == ocId}),
  294. let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId)
  295. else {
  296. return
  297. }
  298. metadatas[index] = metadata
  299. if currentViewController.metadata.ocId == ocId {
  300. currentViewController.loadImage()
  301. } else {
  302. modifiedOcId.append(ocId)
  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. }