NCViewerMediaPage.swift 33 KB

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