NCViewerMediaPage.swift 28 KB

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