NCViewerImage.swift 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  1. //
  2. // NCViewerImage.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. class NCViewerImage: UIViewController {
  27. @IBOutlet weak var progressView: UIProgressView!
  28. @IBOutlet weak var toolBar: UIToolbar!
  29. enum ScreenMode {
  30. case full, normal
  31. }
  32. var currentMode: ScreenMode = .normal
  33. var pageViewController: UIPageViewController {
  34. return self.children[0] as! UIPageViewController
  35. }
  36. var currentViewController: NCViewerImageZoom {
  37. return self.pageViewController.viewControllers![0] as! NCViewerImageZoom
  38. }
  39. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  40. var metadatas: [tableMetadata] = []
  41. var currentMetadata: tableMetadata = tableMetadata()
  42. var currentIndex = 0
  43. var nextIndex: Int?
  44. var currentViewerImageZoom: NCViewerImageZoom?
  45. var panGestureRecognizer: UIPanGestureRecognizer!
  46. var singleTapGestureRecognizer: UITapGestureRecognizer!
  47. var longtapGestureRecognizer: UILongPressGestureRecognizer!
  48. private var player: AVPlayer?
  49. private var videoLayer: AVPlayerLayer?
  50. private var timeObserverToken: Any?
  51. private var rateObserverToken: Any?
  52. var seekTime: CMTime?
  53. var pictureInPictureOcId: String = ""
  54. var textColor: UIColor = NCBrandColor.sharedInstance.textView
  55. override func viewDidLoad() {
  56. super.viewDidLoad()
  57. singleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didSingleTapWith(gestureRecognizer:)))
  58. panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(didPanWith(gestureRecognizer:)))
  59. longtapGestureRecognizer = UILongPressGestureRecognizer()
  60. longtapGestureRecognizer.delaysTouchesBegan = true
  61. longtapGestureRecognizer.minimumPressDuration = 0.3
  62. longtapGestureRecognizer.delegate = self
  63. longtapGestureRecognizer.addTarget(self, action: #selector(didLongpressGestureEvent(gestureRecognizer:)))
  64. pageViewController.delegate = self
  65. pageViewController.dataSource = self
  66. pageViewController.view.addGestureRecognizer(panGestureRecognizer)
  67. pageViewController.view.addGestureRecognizer(singleTapGestureRecognizer)
  68. pageViewController.view.addGestureRecognizer(longtapGestureRecognizer)
  69. let viewerImageZoom = UIStoryboard(name: "NCViewerImage", bundle: nil).instantiateViewController(withIdentifier: "NCViewerImageZoom") as! NCViewerImageZoom
  70. viewerImageZoom.index = currentIndex
  71. viewerImageZoom.image = getImageMetadata(metadatas[currentIndex])
  72. viewerImageZoom.metadata = metadatas[currentIndex]
  73. viewerImageZoom.delegate = self
  74. viewerImageZoom.viewerImage = self
  75. singleTapGestureRecognizer.require(toFail: viewerImageZoom.doubleTapGestureRecognizer)
  76. pageViewController.setViewControllers([viewerImageZoom], direction: .forward, animated: true, completion: nil)
  77. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: k_notificationCenter_changeTheming), object: nil)
  78. NotificationCenter.default.addObserver(self, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadedFile), object: nil)
  79. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_progressTask), object:nil)
  80. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_deleteFile), object: nil)
  81. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_renameFile), object: nil)
  82. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_moveFile), object: nil)
  83. NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_favoriteFile), object: nil)
  84. NotificationCenter.default.addObserver(self, selector: #selector(saveLivePhoto(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_menuSaveLivePhoto), object: nil)
  85. NotificationCenter.default.addObserver(self, selector: #selector(viewUnload), name: NSNotification.Name(rawValue: k_notificationCenter_menuDetailClose), object: nil)
  86. progressView.tintColor = NCBrandColor.sharedInstance.brandElement
  87. progressView.trackTintColor = .clear
  88. progressView.progress = 0
  89. setToolBar()
  90. }
  91. override func viewWillAppear(_ animated: Bool) {
  92. super.viewWillAppear(animated)
  93. navigationItem.rightBarButtonItem = UIBarButtonItem.init(image: CCGraphics.changeThemingColorImage(UIImage(named: "more"), width: 50, height: 50, color: NCBrandColor.sharedInstance.textView), style: .plain, target: self, action: #selector(self.openMenuMore))
  94. navigationController?.setNavigationBarHidden(false, animated: true)
  95. navigationController?.navigationBar.prefersLargeTitles = false
  96. }
  97. override func viewWillDisappear(_ animated: Bool) {
  98. super.viewWillDisappear(animated)
  99. if let navigationController = self.navigationController {
  100. if !navigationController.viewControllers.contains(self) {
  101. videoStop()
  102. }
  103. }
  104. }
  105. @objc func viewUnload() {
  106. navigationController?.popViewController(animated: true)
  107. }
  108. @objc func openMenuMore() {
  109. NCViewer.shared.toggleMoreMenu(viewController: self, metadata: currentMetadata, webView: false)
  110. }
  111. //MARK: - NotificationCenter
  112. @objc func downloadedFile(_ notification: NSNotification) {
  113. if self.view?.window == nil { return }
  114. if let userInfo = notification.userInfo as NSDictionary? {
  115. if let metadata = userInfo["metadata"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int {
  116. if errorCode == 0 {
  117. self.reloadCurrentPage()
  118. }
  119. if self.metadatas.first(where: { $0.ocId == metadata.ocId }) != nil {
  120. progressView.progress = 0
  121. }
  122. }
  123. }
  124. }
  125. @objc func triggerProgressTask(_ notification: NSNotification) {
  126. if self.view?.window == nil { return }
  127. if let userInfo = notification.userInfo as NSDictionary? {
  128. if let ocId = userInfo["ocId"] as? String {
  129. if self.metadatas.first(where: { $0.ocId == ocId }) != nil {
  130. let progressNumber = userInfo["progress"] as? NSNumber ?? 0
  131. let progress = progressNumber.floatValue
  132. if progress == 1 {
  133. self.progressView.progress = 0
  134. } else {
  135. self.progressView.progress = progress
  136. }
  137. }
  138. }
  139. }
  140. }
  141. @objc func deleteFile(_ notification: NSNotification) {
  142. if self.view?.window == nil { return }
  143. if let userInfo = notification.userInfo as NSDictionary? {
  144. if let metadata = userInfo["metadata"] as? tableMetadata {
  145. let metadatas = self.metadatas.filter { $0.ocId != metadata.ocId }
  146. if self.metadatas.count == metadatas.count { return }
  147. self.metadatas = metadatas
  148. if metadata.ocId == currentViewerImageZoom?.metadata.ocId {
  149. if !shiftCurrentPage() {
  150. self.viewUnload()
  151. }
  152. }
  153. }
  154. }
  155. }
  156. @objc func renameFile(_ notification: NSNotification) {
  157. if self.view?.window == nil { return }
  158. if let userInfo = notification.userInfo as NSDictionary? {
  159. if let metadata = userInfo["metadata"] as? tableMetadata {
  160. if let index = metadatas.firstIndex(where: {$0.ocId == metadata.ocId}) {
  161. metadatas[index] = metadata
  162. if index == currentIndex {
  163. navigationItem.title = metadata.fileNameView
  164. currentViewerImageZoom?.metadata = metadata
  165. self.currentMetadata = metadata
  166. }
  167. }
  168. }
  169. }
  170. }
  171. @objc func moveFile(_ notification: NSNotification) {
  172. if self.view?.window == nil { return }
  173. if let userInfo = notification.userInfo as NSDictionary? {
  174. if let metadata = userInfo["metadata"] as? tableMetadata {
  175. if metadatas.firstIndex(where: {$0.ocId == metadata.ocId}) != nil {
  176. deleteFile(notification)
  177. }
  178. }
  179. }
  180. }
  181. @objc func favoriteFile(_ notification: NSNotification) {
  182. if self.view?.window == nil { return }
  183. if let userInfo = notification.userInfo as NSDictionary? {
  184. if let metadata = userInfo["metadata"] as? tableMetadata {
  185. if let index = metadatas.firstIndex(where: {$0.ocId == metadata.ocId}) {
  186. metadatas[index] = metadata
  187. if index == currentIndex {
  188. currentViewerImageZoom?.metadata = metadata
  189. self.currentMetadata = metadata
  190. self.setToolBar()
  191. }
  192. }
  193. }
  194. }
  195. }
  196. @objc func saveLivePhoto(_ notification: NSNotification) {
  197. if self.view?.window == nil { return }
  198. if let userInfo = notification.userInfo as NSDictionary? {
  199. if let metadata = userInfo["metadata"] as? tableMetadata, let metadataMov = userInfo["metadataMov"] as? tableMetadata {
  200. let fileNameImage = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!)
  201. let fileNameMov = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadataMov.ocId, fileNameView: metadataMov.fileNameView)!)
  202. NCLivePhoto.generate(from: fileNameImage, videoURL: fileNameMov, progress: { progress in
  203. DispatchQueue.main.async {
  204. self.progressView.progress = Float(progress)
  205. }
  206. }, completion: { livePhoto, resources in
  207. self.progressView.progress = 0
  208. if resources != nil {
  209. NCLivePhoto.saveToLibrary(resources!) { (result) in
  210. if !result {
  211. NCContentPresenter.shared.messageNotification("_error_", description: "_livephoto_save_error_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorInternalError))
  212. }
  213. }
  214. } else {
  215. NCContentPresenter.shared.messageNotification("_error_", description: "_livephoto_save_error_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorInternalError))
  216. }
  217. })
  218. }
  219. }
  220. }
  221. @objc func changeTheming() {
  222. if currentMode == .normal {
  223. view.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  224. textColor = NCBrandColor.sharedInstance.textView
  225. }
  226. toolBar.tintColor = NCBrandColor.sharedInstance.brandElement
  227. }
  228. //
  229. // Detect for LIVE
  230. //
  231. @objc func didLongpressGestureEvent(gestureRecognizer: UITapGestureRecognizer) {
  232. if gestureRecognizer.state == .began {
  233. currentViewerImageZoom?.statusViewImage.isHidden = true
  234. currentViewerImageZoom?.statusLabel.isHidden = true
  235. let fileName = (currentMetadata.fileNameView as NSString).deletingPathExtension + ".mov"
  236. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView LIKE[c] %@", currentMetadata.account, currentMetadata.serverUrl, fileName)) {
  237. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  238. AudioServicesPlaySystemSound(1519) // peek feedback
  239. self.videoPlay(metadata: metadata)
  240. } else {
  241. let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileNameView
  242. let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  243. NCCommunication.shared.download(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, requestHandler: { (_) in
  244. }, progressHandler: { (progress) in
  245. self.progressView.progress = Float(progress.fractionCompleted)
  246. }) { (account, etag, date, length, allHeaderFields, error, errorCode, errorDescription) in
  247. self.progressView.progress = 0
  248. if errorCode == 0 && account == metadata.account {
  249. NCManageDatabase.sharedInstance.addLocalFile(metadata: metadata)
  250. if gestureRecognizer.state == .changed || gestureRecognizer.state == .began {
  251. AudioServicesPlaySystemSound(1519) // peek feedback
  252. self.videoPlay(metadata: metadata)
  253. }
  254. }
  255. }
  256. }
  257. }
  258. } else if gestureRecognizer.state == .ended {
  259. currentViewerImageZoom?.statusViewImage.isHidden = false
  260. currentViewerImageZoom?.statusLabel.isHidden = false
  261. videoStop()
  262. }
  263. }
  264. //MARK: - Image
  265. func getImageMetadata(_ metadata: tableMetadata) -> UIImage? {
  266. if let image = getImage(metadata: metadata) {
  267. return image
  268. }
  269. if metadata.typeFile == k_metadataTypeFile_video && !metadata.hasPreview {
  270. CCGraphics.createNewImage(from: metadata.fileNameView, ocId: metadata.ocId, etag: metadata.etag, typeFile: metadata.typeFile)
  271. }
  272. if CCUtility.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag) {
  273. if let imagePreviewPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag) {
  274. return UIImage.init(contentsOfFile: imagePreviewPath)
  275. }
  276. }
  277. return nil
  278. }
  279. private func getImage(metadata: tableMetadata) -> UIImage? {
  280. let ext = CCUtility.getExtension(metadata.fileNameView)
  281. var image: UIImage?
  282. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) && metadata.typeFile == k_metadataTypeFile_image {
  283. let previewPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)!
  284. let imagePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  285. if ext == "GIF" {
  286. if !FileManager().fileExists(atPath: previewPath) {
  287. CCGraphics.createNewImage(from: metadata.fileNameView, ocId: metadata.ocId, etag: metadata.etag, typeFile: metadata.typeFile)
  288. }
  289. image = UIImage.animatedImage(withAnimatedGIFURL: URL(fileURLWithPath: imagePath))
  290. } else if ext == "SVG" {
  291. if let svgImage = SVGKImage(contentsOfFile: imagePath) {
  292. let scale = svgImage.size.height / svgImage.size.width
  293. svgImage.size = CGSize(width: CGFloat(k_sizePreview), height: (CGFloat(k_sizePreview) * scale))
  294. if let image = svgImage.uiImage {
  295. if !FileManager().fileExists(atPath: previewPath) {
  296. do {
  297. try image.pngData()?.write(to: URL(fileURLWithPath: previewPath), options: .atomic)
  298. } catch { }
  299. }
  300. return image
  301. } else {
  302. return nil
  303. }
  304. } else {
  305. return nil
  306. }
  307. } else {
  308. if !FileManager().fileExists(atPath: previewPath) {
  309. CCGraphics.createNewImage(from: metadata.fileNameView, ocId: metadata.ocId, etag: metadata.etag, typeFile: metadata.typeFile)
  310. }
  311. image = UIImage.init(contentsOfFile: imagePath)
  312. }
  313. }
  314. return image
  315. }
  316. //MARK: - Video
  317. func videoPlay(metadata: tableMetadata) {
  318. NCKTVHTTPCache.shared.startProxy(user: appDelegate.user, password: appDelegate.password, metadata: metadata)
  319. if let url = NCKTVHTTPCache.shared.getVideoURL(metadata: metadata) {
  320. player = AVPlayer(url: url)
  321. player?.isMuted = CCUtility.getAudioMute()
  322. videoLayer = AVPlayerLayer(player: player)
  323. if videoLayer != nil && currentViewerImageZoom != nil {
  324. videoLayer!.frame = currentViewerImageZoom!.imageView.bounds
  325. videoLayer!.videoGravity = AVLayerVideoGravity.resizeAspectFill
  326. currentViewerImageZoom!.imageView.layer.addSublayer(videoLayer!)
  327. /*
  328. if let duration = playerVideo?.currentItem?.asset.duration {
  329. durationVideo = Float(CMTimeGetSeconds(duration))
  330. }
  331. let timeScale = CMTimeScale(NSEC_PER_SEC)
  332. let time = CMTime(seconds: 0.5, preferredTimescale: timeScale)
  333. timeObserverToken = playerVideo?.addPeriodicTimeObserver(forInterval: time, queue: .main) { [weak self] time in
  334. print(time)
  335. }
  336. */
  337. // At end go back to start
  338. NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: nil, queue: .main) { (notification) in
  339. self.player?.seek(to: CMTime.zero)
  340. }
  341. rateObserverToken = player?.addObserver(self, forKeyPath: "rate", options: [], context: nil)
  342. if pictureInPictureOcId != metadata.ocId {
  343. player?.play()
  344. if seekTime != nil {
  345. player?.seek(to: seekTime!)
  346. seekTime = nil
  347. }
  348. }
  349. }
  350. }
  351. }
  352. func videoStop() {
  353. player?.pause()
  354. player?.seek(to: CMTime.zero)
  355. if rateObserverToken != nil {
  356. player?.removeObserver(self, forKeyPath: "rate")
  357. NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
  358. NCKTVHTTPCache.shared.stopProxy()
  359. self.rateObserverToken = nil
  360. }
  361. if let timeObserverToken = timeObserverToken {
  362. player?.removeTimeObserver(timeObserverToken)
  363. self.timeObserverToken = nil
  364. }
  365. videoLayer?.removeFromSuperlayer()
  366. }
  367. override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
  368. if keyPath != nil && keyPath == "rate" {
  369. setToolBar()
  370. }
  371. }
  372. //MARK: - Tool Bar
  373. func setToolBar() {
  374. let mute = CCUtility.getAudioMute()
  375. var itemPlay = toolBar.items![0]
  376. let itemFlexibleSpace = toolBar.items![1]
  377. var itemFavorite = toolBar.items![2]
  378. var itemMute = toolBar.items![3]
  379. if player?.rate == 1 {
  380. itemPlay = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.pause, target: self, action: #selector(playerPause))
  381. } else {
  382. itemPlay = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.play, target: self, action: #selector(playerPlay))
  383. }
  384. if currentMetadata.favorite {
  385. itemFavorite = UIBarButtonItem(image: UIImage(named: "videoFavoriteOn"), style: UIBarButtonItem.Style.plain, target: self, action: #selector(SetFavorite))
  386. } else {
  387. itemFavorite = UIBarButtonItem(image: UIImage(named: "videoFavoriteOff"), style: UIBarButtonItem.Style.plain, target: self, action: #selector(SetFavorite))
  388. }
  389. if mute {
  390. itemMute = UIBarButtonItem(image: UIImage(named: "audioOff"), style: UIBarButtonItem.Style.plain, target: self, action: #selector(SetMute))
  391. } else {
  392. itemMute = UIBarButtonItem(image: UIImage(named: "audioOn"), style: UIBarButtonItem.Style.plain, target: self, action: #selector(SetMute))
  393. }
  394. toolBar.setItems([itemPlay, itemFlexibleSpace, itemFavorite, itemMute], animated: true)
  395. toolBar.tintColor = NCBrandColor.sharedInstance.brandElement
  396. }
  397. @objc func playerPause() { player?.pause() }
  398. @objc func playerPlay() { player?.play() }
  399. @objc func SetMute() {
  400. let mute = CCUtility.getAudioMute()
  401. CCUtility.setAudioMute(!mute)
  402. player?.isMuted = !mute
  403. setToolBar()
  404. }
  405. @objc func SetFavorite() {
  406. NCNetworking.shared.favoriteMetadata(currentMetadata, urlBase: self.appDelegate.urlBase) { (errorCode, errorDescription) in }
  407. }
  408. }
  409. //MARK: - UIPageViewController Delegate Datasource
  410. extension NCViewerImage: UIPageViewControllerDelegate, UIPageViewControllerDataSource {
  411. func shiftCurrentPage() -> Bool {
  412. if metadatas.count == 0 { return false }
  413. var direction: UIPageViewController.NavigationDirection = .forward
  414. if currentIndex == metadatas.count {
  415. currentIndex -= 1
  416. direction = .reverse
  417. }
  418. let viewerImageZoom = UIStoryboard(name: "NCViewerImage", bundle: nil).instantiateViewController(withIdentifier: "NCViewerImageZoom") as! NCViewerImageZoom
  419. viewerImageZoom.index = currentIndex
  420. viewerImageZoom.image = getImageMetadata(metadatas[currentIndex])
  421. viewerImageZoom.metadata = metadatas[currentIndex]
  422. viewerImageZoom.delegate = self
  423. viewerImageZoom.viewerImage = self
  424. singleTapGestureRecognizer.require(toFail: viewerImageZoom.doubleTapGestureRecognizer)
  425. pageViewController.setViewControllers([viewerImageZoom], direction: direction, animated: true, completion: nil)
  426. return true
  427. }
  428. func reloadCurrentPage() {
  429. if currentViewerImageZoom?.metadata.ocId == currentMetadata.ocId {
  430. let viewerImageZoom = UIStoryboard(name: "NCViewerImage", bundle: nil).instantiateViewController(withIdentifier: "NCViewerImageZoom") as! NCViewerImageZoom
  431. viewerImageZoom.index = currentIndex
  432. viewerImageZoom.image = getImageMetadata(metadatas[currentIndex])
  433. viewerImageZoom.metadata = metadatas[currentIndex]
  434. viewerImageZoom.delegate = self
  435. viewerImageZoom.viewerImage = self
  436. singleTapGestureRecognizer.require(toFail: viewerImageZoom.doubleTapGestureRecognizer)
  437. pageViewController.setViewControllers([viewerImageZoom], direction: .forward, animated: false, completion: nil)
  438. }
  439. }
  440. func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
  441. if currentIndex == 0 { return nil }
  442. let viewerImageZoom = UIStoryboard(name: "NCViewerImage", bundle: nil).instantiateViewController(withIdentifier: "NCViewerImageZoom") as! NCViewerImageZoom
  443. viewerImageZoom.index = currentIndex - 1
  444. viewerImageZoom.image = getImageMetadata(metadatas[currentIndex - 1])
  445. viewerImageZoom.metadata = metadatas[currentIndex - 1]
  446. viewerImageZoom.delegate = self
  447. viewerImageZoom.viewerImage = self
  448. self.singleTapGestureRecognizer.require(toFail: viewerImageZoom.doubleTapGestureRecognizer)
  449. return viewerImageZoom
  450. }
  451. func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
  452. if currentIndex == metadatas.count - 1 { return nil }
  453. let viewerImageZoom = UIStoryboard(name: "NCViewerImage", bundle: nil).instantiateViewController(withIdentifier: "NCViewerImageZoom") as! NCViewerImageZoom
  454. viewerImageZoom.index = currentIndex + 1
  455. viewerImageZoom.image = getImageMetadata(metadatas[currentIndex + 1])
  456. viewerImageZoom.metadata = metadatas[currentIndex + 1]
  457. viewerImageZoom.delegate = self
  458. viewerImageZoom.viewerImage = self
  459. singleTapGestureRecognizer.require(toFail: viewerImageZoom.doubleTapGestureRecognizer)
  460. return viewerImageZoom
  461. }
  462. func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
  463. guard let nextViewController = pendingViewControllers.first as? NCViewerImageZoom else { return }
  464. nextIndex = nextViewController.index
  465. }
  466. func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
  467. if (completed && nextIndex != nil) {
  468. previousViewControllers.forEach { viewController in
  469. let viewerImageZoom = viewController as! NCViewerImageZoom
  470. viewerImageZoom.scrollView.zoomScale = viewerImageZoom.scrollView.minimumZoomScale
  471. }
  472. currentIndex = nextIndex!
  473. }
  474. self.nextIndex = nil
  475. }
  476. }
  477. //MARK: - UIGestureRecognizerDelegate
  478. extension NCViewerImage: UIGestureRecognizerDelegate {
  479. func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
  480. if let gestureRecognizer = gestureRecognizer as? UIPanGestureRecognizer {
  481. let velocity = gestureRecognizer.velocity(in: self.view)
  482. var velocityCheck : Bool = false
  483. if UIDevice.current.orientation.isLandscape {
  484. velocityCheck = velocity.x < 0
  485. }
  486. else {
  487. velocityCheck = velocity.y < 0
  488. }
  489. if velocityCheck {
  490. return false
  491. }
  492. }
  493. return true
  494. }
  495. func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
  496. if otherGestureRecognizer == currentViewController.scrollView.panGestureRecognizer {
  497. if self.currentViewController.scrollView.contentOffset.y == 0 {
  498. return true
  499. }
  500. }
  501. return false
  502. }
  503. @objc func didPanWith(gestureRecognizer: UIPanGestureRecognizer) {
  504. currentViewerImageZoom?.didPanWith(gestureRecognizer: gestureRecognizer)
  505. }
  506. @objc func didSingleTapWith(gestureRecognizer: UITapGestureRecognizer) {
  507. if currentViewerImageZoom?.detailView.isShow() ?? false {
  508. currentViewerImageZoom?.centreConstraints()
  509. return
  510. }
  511. if currentMetadata.typeFile == k_metadataTypeFile_video || currentMetadata.typeFile == k_metadataTypeFile_audio {
  512. if pictureInPictureOcId != currentMetadata.ocId {
  513. // Kill PIP
  514. appDelegate.activeViewerVideo?.player?.replaceCurrentItem(with: nil)
  515. //
  516. appDelegate.activeViewerVideo = NCViewerVideo()
  517. appDelegate.activeViewerVideo?.metadata = currentMetadata
  518. appDelegate.activeViewerVideo?.seekTime = player?.currentTime()
  519. appDelegate.activeViewerVideo?.delegateViewerVideo = self
  520. if let currentViewerVideo = appDelegate.activeViewerVideo {
  521. present(currentViewerVideo, animated: false) { }
  522. }
  523. }
  524. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  525. self.videoStop()
  526. }
  527. } else {
  528. if currentMode == .full {
  529. navigationController?.setNavigationBarHidden(false, animated: false)
  530. view.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  531. textColor = NCBrandColor.sharedInstance.textView
  532. progressView.isHidden = false
  533. currentMode = .normal
  534. } else {
  535. navigationController?.setNavigationBarHidden(true, animated: false)
  536. view.backgroundColor = .black
  537. textColor = .white
  538. progressView.isHidden = true
  539. currentMode = .full
  540. }
  541. }
  542. }
  543. }
  544. //MARK: - NCViewerImageZoomDelegate
  545. extension NCViewerImage: NCViewerImageZoomDelegate {
  546. func dismissImageZoom() {
  547. self.navigationController?.popViewController(animated: true)
  548. }
  549. func willAppearImageZoom(viewerImageZoom: NCViewerImageZoom, metadata: tableMetadata) {
  550. videoStop()
  551. }
  552. func didAppearImageZoom(viewerImageZoom: NCViewerImageZoom, metadata: tableMetadata) {
  553. navigationItem.title = metadata.fileNameView
  554. currentMetadata = metadata
  555. currentViewerImageZoom = viewerImageZoom
  556. toolBar.isHidden = true
  557. if (currentMetadata.typeFile == k_metadataTypeFile_video || currentMetadata.typeFile == k_metadataTypeFile_audio) {
  558. videoPlay(metadata: metadata)
  559. toolBar.isHidden = false
  560. }
  561. if !NCOperationQueue.shared.downloadExists(metadata: metadata) {
  562. self.progressView.progress = 0
  563. }
  564. let isFolderEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: metadata.urlBase)
  565. let ext = CCUtility.getExtension(metadata.fileNameView)
  566. // DOWNLOAD FILE
  567. if ((metadata.typeFile == k_metadataTypeFile_image && CCUtility.getAutomaticDownloadImage()) || (metadata.contentType == "image/heic" && metadata.hasPreview == false) || ext == "GIF" || ext == "SVG" || isFolderEncrypted) && metadata.session == "" && !CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  568. NCOperationQueue.shared.download(metadata: metadata, selector: "", setFavorite: false)
  569. }
  570. // DOWNLOAD preview
  571. if !CCUtility.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag) && metadata.hasPreview {
  572. let fileNamePath = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, account: metadata.account)!
  573. let fileNamePreviewLocalPath = CCUtility.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)!
  574. let fileNameIconLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)!
  575. NCCommunication.shared.downloadPreview(fileNamePathOrFileId: fileNamePath, fileNamePreviewLocalPath: fileNamePreviewLocalPath, widthPreview: CGFloat(k_sizePreview), heightPreview: CGFloat(k_sizePreview), fileNameIconLocalPath: fileNameIconLocalPath, sizeIcon: CGFloat(k_sizeIcon)) { (account, imagePreview, imageIcon, errorCode, errorMessage) in
  576. if errorCode == 0 {
  577. self.reloadCurrentPage()
  578. }
  579. }
  580. }
  581. }
  582. }
  583. //MARK: - NCViewerVideoDelegate
  584. extension NCViewerImage: NCViewerVideoDelegate {
  585. func startPictureInPicture(metadata: tableMetadata) {
  586. pictureInPictureOcId = metadata.ocId
  587. }
  588. func stopPictureInPicture(metadata: tableMetadata) {
  589. pictureInPictureOcId = ""
  590. }
  591. func playerCurrentTime(_ time: CMTime?) {
  592. seekTime = time
  593. }
  594. }