NCMediaCache.swift 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. //
  2. // NCMediaCache.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 18/10/23.
  6. // Copyright © 2021 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 LRUCache
  25. import NextcloudKit
  26. @objc class NCMediaCache: NSObject {
  27. @objc public static let shared: NCMediaCache = {
  28. let instance = NCMediaCache()
  29. return instance
  30. }()
  31. private let limit: Int = 1500
  32. private typealias ThumbnailLRUCache = LRUCache<String, UIImage>
  33. private lazy var cache: ThumbnailLRUCache = {
  34. return ThumbnailLRUCache(countLimit: limit)
  35. }()
  36. public var metadatas: [tableMetadata] = []
  37. public var predicateDefault: NSPredicate?
  38. public var predicate: NSPredicate?
  39. func createCache(account: String) {
  40. let resultsMedia = NCManageDatabase.shared.getMediaOcIdEtag(account: account)
  41. guard !resultsMedia.isEmpty,
  42. let directory = CCUtility.getDirectoryProviderStorage() else { return }
  43. metadatas.removeAll()
  44. getMetadatasMedia()
  45. let ext = ".preview.ico"
  46. let manager = FileManager.default
  47. let resourceKeys = Set<URLResourceKey>([.nameKey, .pathKey, .fileSizeKey, .creationDateKey])
  48. struct FileInfo {
  49. var path: URL
  50. var ocId: String
  51. var date: Date
  52. }
  53. var files: [FileInfo] = []
  54. let startDate = Date()
  55. if let enumerator = manager.enumerator(at: URL(fileURLWithPath: directory), includingPropertiesForKeys: [.isRegularFileKey], options: [.skipsHiddenFiles]) {
  56. for case let fileURL as URL in enumerator where fileURL.lastPathComponent.hasSuffix(ext) {
  57. let fileName = fileURL.lastPathComponent
  58. let ocId = fileURL.deletingLastPathComponent().lastPathComponent
  59. guard let resourceValues = try? fileURL.resourceValues(forKeys: resourceKeys),
  60. let size = resourceValues.fileSize,
  61. size > 0,
  62. let date = resourceValues.creationDate,
  63. let etag = resultsMedia[ocId],
  64. fileName == etag + ext else { continue }
  65. files.append(FileInfo(path: fileURL, ocId: ocId, date: date))
  66. }
  67. }
  68. files.sort(by: { $0.date > $1.date })
  69. if let firstDate = files.first?.date, let lastDate = files.last?.date {
  70. print("First date: \(firstDate)")
  71. print("Last date: \(lastDate)")
  72. }
  73. cache.removeAllValues()
  74. var counter: Int = 0
  75. for file in files {
  76. counter += 1
  77. if counter > limit { break }
  78. autoreleasepool {
  79. if let image = UIImage(contentsOfFile: file.path.path) {
  80. cache.setValue(image, forKey: file.ocId)
  81. }
  82. }
  83. }
  84. let endDate = Date()
  85. let diffDate = endDate.timeIntervalSinceReferenceDate - startDate.timeIntervalSinceReferenceDate
  86. NextcloudKit.shared.nkCommonInstance.writeLog("--------- ThumbnailLRUCache image process ---------")
  87. NextcloudKit.shared.nkCommonInstance.writeLog("Counter process: \(cache.count)")
  88. NextcloudKit.shared.nkCommonInstance.writeLog("Time process: \(diffDate)")
  89. NextcloudKit.shared.nkCommonInstance.writeLog("--------- ThumbnailLRUCache image process ---------")
  90. }
  91. func getImage(ocId: String) -> UIImage? {
  92. return cache.value(forKey: ocId)
  93. }
  94. func setImage(ocId: String, image: UIImage) {
  95. cache.setValue(image, forKey: ocId)
  96. }
  97. @objc func clearCache() {
  98. cache.removeAllValues()
  99. }
  100. func getMetadatasMedia(filterClassTypeImage: Bool = false, filterClassTypeVideo: Bool = false) {
  101. let livePhoto = CCUtility.getLivePhoto()
  102. guard let appDelegate = (UIApplication.shared.delegate as? AppDelegate),
  103. let activeAccount = NCManageDatabase.shared.getActiveAccount() else { return }
  104. let startServerUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId) + activeAccount.mediaPath
  105. predicateDefault = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND (classFile == %@ OR classFile == %@) AND NOT (session CONTAINS[c] 'upload')", appDelegate.account, startServerUrl, NKCommon.TypeClassFile.image.rawValue, NKCommon.TypeClassFile.video.rawValue)
  106. if filterClassTypeImage {
  107. predicate = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND classFile == %@ AND NOT (session CONTAINS[c] 'upload')", appDelegate.account, startServerUrl, NKCommon.TypeClassFile.video.rawValue)
  108. } else if filterClassTypeVideo {
  109. predicate = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND classFile == %@ AND NOT (session CONTAINS[c] 'upload')", appDelegate.account, startServerUrl, NKCommon.TypeClassFile.image.rawValue)
  110. } else {
  111. predicate = predicateDefault
  112. }
  113. guard let predicate = predicate else { return }
  114. metadatas = NCManageDatabase.shared.getMetadatasMedia(predicate: predicate, livePhoto: livePhoto)
  115. switch CCUtility.getMediaSortDate() {
  116. case "date":
  117. metadatas = self.metadatas.sorted(by: {($0.date as Date) > ($1.date as Date)})
  118. case "creationDate":
  119. metadatas = self.metadatas.sorted(by: {($0.creationDate as Date) > ($1.creationDate as Date)})
  120. case "uploadDate":
  121. metadatas = self.metadatas.sorted(by: {($0.uploadDate as Date) > ($1.uploadDate as Date)})
  122. default:
  123. break
  124. }
  125. }
  126. }