NCMedia.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. //
  2. // NCMedia.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 12/02/2019.
  6. // Copyright © 2019 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 RealmSwift
  26. class NCMedia: UIViewController {
  27. @IBOutlet weak var collectionView: UICollectionView!
  28. @IBOutlet weak var titleDate: UILabel!
  29. @IBOutlet weak var activityIndicator: UIActivityIndicatorView!
  30. @IBOutlet weak var activityIndicatorTrailing: NSLayoutConstraint!
  31. @IBOutlet weak var selectOrCancelButton: UIButton!
  32. @IBOutlet weak var selectOrCancelButtonTrailing: NSLayoutConstraint!
  33. @IBOutlet weak var menuButton: UIButton!
  34. @IBOutlet weak var gradientView: UIView!
  35. let layout = NCMediaLayout()
  36. var layoutType = NCGlobal.shared.mediaLayoutRatio
  37. var activeAccount = tableAccount()
  38. var documentPickerViewController: NCDocumentPickerViewController?
  39. var tabBarSelect: NCMediaSelectTabBar!
  40. let appDelegate = (UIApplication.shared.delegate as? AppDelegate)!
  41. let utilityFileSystem = NCUtilityFileSystem()
  42. let utility = NCUtility()
  43. let imageCache = NCImageCache.shared
  44. var metadatas: ThreadSafeArray<tableMetadata>?
  45. var serverUrl = ""
  46. let refreshControl = UIRefreshControl()
  47. var loadingTask: Task<Void, any Error>?
  48. let taskDescriptionRetrievesProperties = "retrievesProperties"
  49. var isTop: Bool = true
  50. var isEditMode = false
  51. var selectOcId: [String] = []
  52. var attributesZoomIn: UIMenuElement.Attributes = []
  53. var attributesZoomOut: UIMenuElement.Attributes = []
  54. let gradient: CAGradientLayer = CAGradientLayer()
  55. var showOnlyImages = false
  56. var showOnlyVideos = false
  57. var lastContentOffsetY: CGFloat = 0
  58. var timeIntervalSearchNewMedia: TimeInterval = 2.0
  59. var timerSearchNewMedia: Timer?
  60. let insetsTop: CGFloat = 75
  61. let maxImageGrid: CGFloat = 7
  62. var livePhotoImage = UIImage()
  63. var playImage = UIImage()
  64. var photoImage = UIImage()
  65. var videoImage = UIImage()
  66. // MARK: - View Life Cycle
  67. override func viewDidLoad() {
  68. super.viewDidLoad()
  69. view.backgroundColor = .systemBackground
  70. activeAccount = NCManageDatabase.shared.getActiveAccount() ?? tableAccount()
  71. collectionView.register(UINib(nibName: "NCSectionFirstHeaderEmptyData", bundle: nil), forSupplementaryViewOfKind: mediaSectionHeader, withReuseIdentifier: "sectionFirstHeaderEmptyData")
  72. collectionView.register(UINib(nibName: "NCGridMediaCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  73. collectionView.alwaysBounceVertical = true
  74. collectionView.contentInset = UIEdgeInsets(top: insetsTop, left: 0, bottom: 50, right: 0)
  75. collectionView.backgroundColor = .systemBackground
  76. collectionView.prefetchDataSource = self
  77. collectionView.dragInteractionEnabled = true
  78. collectionView.dragDelegate = self
  79. collectionView.dropDelegate = self
  80. layout.sectionInset = UIEdgeInsets(top: 0, left: 2, bottom: 0, right: 2)
  81. collectionView.collectionViewLayout = layout
  82. layoutType = NCManageDatabase.shared.getLayoutForView(account: activeAccount.account, key: NCGlobal.shared.layoutViewMedia, serverUrl: "")?.layout ?? NCGlobal.shared.mediaLayoutRatio
  83. tabBarSelect = NCMediaSelectTabBar(tabBarController: self.tabBarController, delegate: self)
  84. livePhotoImage = utility.loadImage(named: "livephoto", colors: [.white])
  85. playImage = utility.loadImage(named: "play.fill", colors: [.white])
  86. titleDate.text = ""
  87. selectOrCancelButton.backgroundColor = .clear
  88. selectOrCancelButton.layer.cornerRadius = 15
  89. selectOrCancelButton.layer.masksToBounds = true
  90. selectOrCancelButton.setTitle( NSLocalizedString("_select_", comment: ""), for: .normal)
  91. selectOrCancelButton.addBlur(style: .systemUltraThinMaterial)
  92. menuButton.backgroundColor = .clear
  93. menuButton.layer.cornerRadius = 15
  94. menuButton.layer.masksToBounds = true
  95. menuButton.showsMenuAsPrimaryAction = true
  96. menuButton.configuration = UIButton.Configuration.plain()
  97. menuButton.setImage(NCUtility().loadImage(named: "ellipsis"), for: .normal)
  98. menuButton.changesSelectionAsPrimaryAction = false
  99. menuButton.addBlur(style: .systemUltraThinMaterial)
  100. gradient.startPoint = CGPoint(x: 0, y: 0.1)
  101. gradient.endPoint = CGPoint(x: 0, y: 1)
  102. gradient.colors = [UIColor.black.withAlphaComponent(UIAccessibility.isReduceTransparencyEnabled ? 0.8 : 0.4).cgColor, UIColor.clear.cgColor]
  103. gradientView.layer.insertSublayer(gradient, at: 0)
  104. collectionView.refreshControl = refreshControl
  105. refreshControl.action(for: .valueChanged) { _ in
  106. DispatchQueue.global(qos: .userInteractive).async {
  107. self.reloadDataSource()
  108. }
  109. self.refreshControl.endRefreshing()
  110. }
  111. NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeUser), object: nil, queue: nil) { _ in
  112. self.activeAccount = NCManageDatabase.shared.getActiveAccount() ?? tableAccount()
  113. self.layoutType = NCManageDatabase.shared.getLayoutForView(account: self.activeAccount.account, key: NCGlobal.shared.layoutViewMedia, serverUrl: "")?.layout ?? NCGlobal.shared.mediaLayoutRatio
  114. if let metadatas = self.metadatas,
  115. let metadata = metadatas.first {
  116. if metadata.account != self.activeAccount.account {
  117. self.metadatas = nil
  118. self.collectionViewReloadData()
  119. }
  120. }
  121. }
  122. NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCreateMediaCacheEnded), object: nil, queue: nil) { _ in
  123. if let metadatas = self.imageCache.initialMetadatas() {
  124. self.metadatas = metadatas
  125. }
  126. self.collectionViewReloadData()
  127. }
  128. }
  129. override func viewWillAppear(_ animated: Bool) {
  130. super.viewWillAppear(animated)
  131. navigationController?.setMediaAppreance()
  132. }
  133. override func viewDidAppear(_ animated: Bool) {
  134. super.viewDidAppear(animated)
  135. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  136. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  137. NotificationCenter.default.addObserver(self, selector: #selector(copyFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCopyFile), object: nil)
  138. NotificationCenter.default.addObserver(self, selector: #selector(enterForeground(_:)), name: UIApplication.willEnterForegroundNotification, object: nil)
  139. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  140. startTimer()
  141. createMenu()
  142. if imageCache.createMediaCacheInProgress {
  143. self.metadatas = nil
  144. self.collectionViewReloadData()
  145. } else if let metadatas = imageCache.initialMetadatas() {
  146. self.metadatas = metadatas
  147. self.collectionViewReloadData()
  148. } else {
  149. DispatchQueue.global(qos: .userInteractive).async {
  150. self.reloadDataSource()
  151. }
  152. }
  153. }
  154. override func viewDidDisappear(_ animated: Bool) {
  155. super.viewDidDisappear(animated)
  156. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  157. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCopyFile), object: nil)
  158. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  159. NotificationCenter.default.removeObserver(self, name: UIApplication.willEnterForegroundNotification, object: nil)
  160. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  161. // Cancel Queue & Retrieves Properties
  162. NCNetworking.shared.downloadThumbnailQueue.cancelAll()
  163. NextcloudKit.shared.sessionManager.session.getTasksWithCompletionHandler { dataTasks, _, _ in
  164. dataTasks.forEach {
  165. if $0.taskDescription == self.taskDescriptionRetrievesProperties {
  166. $0.cancel()
  167. }
  168. }
  169. }
  170. }
  171. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  172. super.viewWillTransition(to: size, with: coordinator)
  173. coordinator.animate(alongsideTransition: nil) { _ in
  174. self.setTitleDate()
  175. }
  176. }
  177. override var preferredStatusBarStyle: UIStatusBarStyle {
  178. if self.traitCollection.userInterfaceStyle == .dark {
  179. return .lightContent
  180. } else if isTop {
  181. return .darkContent
  182. } else {
  183. return .lightContent
  184. }
  185. }
  186. override func viewWillLayoutSubviews() {
  187. super.viewWillLayoutSubviews()
  188. if let frame = tabBarController?.tabBar.frame {
  189. tabBarSelect.hostingController.view.frame = frame
  190. }
  191. gradient.frame = gradientView.bounds
  192. }
  193. func startTimer() {
  194. // don't start if media chage is in progress
  195. if imageCache.createMediaCacheInProgress {
  196. return
  197. }
  198. timerSearchNewMedia?.invalidate()
  199. timerSearchNewMedia = Timer.scheduledTimer(timeInterval: timeIntervalSearchNewMedia, target: self, selector: #selector(searchMediaUI), userInfo: nil, repeats: false)
  200. }
  201. // MARK: - NotificationCenter
  202. @objc func deleteFile(_ notification: NSNotification) {
  203. guard let userInfo = notification.userInfo as NSDictionary?,
  204. let error = userInfo["error"] as? NKError else { return }
  205. self.reloadDataSource()
  206. if error != .success {
  207. NCContentPresenter().showError(error: error)
  208. }
  209. }
  210. @objc func enterForeground(_ notification: NSNotification) {
  211. startTimer()
  212. }
  213. @objc func uploadedFile(_ notification: NSNotification) {
  214. guard let userInfo = notification.userInfo as NSDictionary?,
  215. let ocId = userInfo["ocId"] as? String else { return }
  216. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId),
  217. (metadata.isVideo || metadata.isImage) {
  218. self.reloadDataSource()
  219. }
  220. }
  221. @objc func moveFile(_ notification: NSNotification) {
  222. guard let userInfo = notification.userInfo as NSDictionary?,
  223. let dragDrop = userInfo["dragdrop"] as? Bool, dragDrop else { return }
  224. setEditMode(false)
  225. DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
  226. self.reloadDataSource()
  227. self.searchMediaUI()
  228. }
  229. }
  230. @objc func copyFile(_ notification: NSNotification) {
  231. guard let userInfo = notification.userInfo as NSDictionary?,
  232. let dragDrop = userInfo["dragdrop"] as? Bool, dragDrop else { return }
  233. setEditMode(false)
  234. DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
  235. self.reloadDataSource()
  236. self.searchMediaUI()
  237. }
  238. }
  239. // MARK: - Image
  240. func getImage(metadata: tableMetadata) -> UIImage? {
  241. let fileNamePathPreview = utilityFileSystem.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)
  242. if let image = imageCache.getPreviewImageCache(ocId: metadata.ocId, etag: metadata.etag) {
  243. return image
  244. } else if FileManager().fileExists(atPath: fileNamePathPreview), let image = UIImage(contentsOfFile: fileNamePathPreview) {
  245. imageCache.addPreviewImageCache(metadata: metadata, image: image)
  246. return image
  247. } else if metadata.hasPreview && metadata.status == NCGlobal.shared.metadataStatusNormal,
  248. (!utilityFileSystem.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag)),
  249. NCNetworking.shared.downloadThumbnailQueue.operations.filter({ ($0 as? NCMediaDownloadThumbnaill)?.metadata.ocId == metadata.ocId }).isEmpty {
  250. NCNetworking.shared.downloadThumbnailQueue.addOperation(NCMediaDownloadThumbnaill(metadata: metadata, media: self))
  251. }
  252. return nil
  253. }
  254. func buildMediaPhotoVideo(columnCount: Int) {
  255. var pointSize: CGFloat = 0
  256. switch columnCount {
  257. case 0...1: pointSize = 60
  258. case 2...3: pointSize = 30
  259. case 4...5: pointSize = 25
  260. case 6...Int(maxImageGrid): pointSize = 20
  261. default: pointSize = 20
  262. }
  263. if let image = UIImage(systemName: "photo.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: pointSize))?.withTintColor(.systemGray4, renderingMode: .alwaysOriginal) {
  264. photoImage = image
  265. }
  266. if let image = UIImage(systemName: "video.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: pointSize))?.withTintColor(.systemGray4, renderingMode: .alwaysOriginal) {
  267. videoImage = image
  268. }
  269. }
  270. }
  271. extension NCMedia: UICollectionViewDataSourcePrefetching {
  272. func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
  273. // print("[INFO] n. " + String(indexPaths.count))
  274. }
  275. }
  276. // MARK: -
  277. extension NCMedia: UIScrollViewDelegate {
  278. func scrollViewDidScroll(_ scrollView: UIScrollView) {
  279. if let metadatas, !metadatas.isEmpty {
  280. isTop = scrollView.contentOffset.y <= -(insetsTop + view.safeAreaInsets.top - 25)
  281. setColor()
  282. setNeedsStatusBarAppearanceUpdate()
  283. if lastContentOffsetY == 0 || lastContentOffsetY / 2 <= scrollView.contentOffset.y || lastContentOffsetY / 2 >= scrollView.contentOffset.y {
  284. setTitleDate()
  285. lastContentOffsetY = scrollView.contentOffset.y
  286. }
  287. } else {
  288. setColor()
  289. }
  290. }
  291. func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
  292. }
  293. func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  294. if !decelerate {
  295. if !decelerate {
  296. startTimer()
  297. }
  298. }
  299. }
  300. func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  301. startTimer()
  302. }
  303. func scrollViewDidScrollToTop(_ scrollView: UIScrollView) {
  304. let y = view.safeAreaInsets.top
  305. scrollView.contentOffset.y = -(insetsTop + y)
  306. }
  307. }
  308. // MARK: -
  309. extension NCMedia: NCSelectDelegate {
  310. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool) {
  311. guard let serverUrl = serverUrl else { return }
  312. let home = utilityFileSystem.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId)
  313. let mediaPath = serverUrl.replacingOccurrences(of: home, with: "")
  314. NCManageDatabase.shared.setAccountMediaPath(mediaPath, account: activeAccount.account)
  315. activeAccount = NCManageDatabase.shared.getActiveAccount() ?? tableAccount()
  316. reloadDataSource()
  317. startTimer()
  318. }
  319. }