NCImageCache.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. //
  2. // NCImageCache.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 NCImageCache: NSObject {
  27. @objc public static let shared: NCImageCache = {
  28. let instance = NCImageCache()
  29. return instance
  30. }()
  31. // MARK: -
  32. private let limit: Int = 1000
  33. enum ImageType {
  34. case placeholder
  35. case actual(_ image: UIImage)
  36. }
  37. private typealias ThumbnailLRUCache = LRUCache<String, ImageType>
  38. private lazy var cache: ThumbnailLRUCache = {
  39. return ThumbnailLRUCache(countLimit: limit)
  40. }()
  41. private var ocIdEtag: [String: String] = [:]
  42. public var metadatas: [tableMetadata] = []
  43. public var livePhoto: Bool = false
  44. override private init() {}
  45. func createMediaCache(account: String) {
  46. ocIdEtag.removeAll()
  47. metadatas.removeAll()
  48. getMediaMetadatas(account: account)
  49. guard !metadatas.isEmpty else { return }
  50. let ext = ".preview.ico"
  51. let manager = FileManager.default
  52. let resourceKeys = Set<URLResourceKey>([.nameKey, .pathKey, .fileSizeKey, .creationDateKey])
  53. struct FileInfo {
  54. var path: URL
  55. var ocId: String
  56. var date: Date
  57. }
  58. var files: [FileInfo] = []
  59. let startDate = Date()
  60. for metadata in metadatas {
  61. ocIdEtag[metadata.ocId] = metadata.etag
  62. }
  63. if let enumerator = manager.enumerator(at: URL(fileURLWithPath: NCUtilityFileSystem().directoryProviderStorage), includingPropertiesForKeys: [.isRegularFileKey], options: [.skipsHiddenFiles]) {
  64. for case let fileURL as URL in enumerator where fileURL.lastPathComponent.hasSuffix(ext) {
  65. let fileName = fileURL.lastPathComponent
  66. let ocId = fileURL.deletingLastPathComponent().lastPathComponent
  67. guard let resourceValues = try? fileURL.resourceValues(forKeys: resourceKeys),
  68. let size = resourceValues.fileSize,
  69. size > 0,
  70. let date = resourceValues.creationDate,
  71. let etag = ocIdEtag[ocId],
  72. fileName == etag + ext else { continue }
  73. files.append(FileInfo(path: fileURL, ocId: ocId, date: date))
  74. }
  75. }
  76. files.sort(by: { $0.date > $1.date })
  77. if let firstDate = files.first?.date, let lastDate = files.last?.date {
  78. print("First date: \(firstDate)")
  79. print("Last date: \(lastDate)")
  80. }
  81. cache.removeAllValues()
  82. var counter: Int = 0
  83. for file in files {
  84. counter += 1
  85. if counter > limit { break }
  86. autoreleasepool {
  87. if let image = UIImage(contentsOfFile: file.path.path) {
  88. cache.setValue(.actual(image), forKey: file.ocId)
  89. }
  90. }
  91. }
  92. let endDate = Date()
  93. let diffDate = endDate.timeIntervalSinceReferenceDate - startDate.timeIntervalSinceReferenceDate
  94. NextcloudKit.shared.nkCommonInstance.writeLog("--------- ThumbnailLRUCache image process ---------")
  95. NextcloudKit.shared.nkCommonInstance.writeLog("Counter process: \(cache.count)")
  96. NextcloudKit.shared.nkCommonInstance.writeLog("Time process: \(diffDate)")
  97. NextcloudKit.shared.nkCommonInstance.writeLog("--------- ThumbnailLRUCache image process ---------")
  98. }
  99. func getMediaImage(ocId: String) -> ImageType? {
  100. return cache.value(forKey: ocId)
  101. }
  102. func setMediaImage(ocId: String, image: ImageType) {
  103. cache.setValue(image, forKey: ocId)
  104. }
  105. @objc func clearMediaCache() {
  106. ocIdEtag.removeAll()
  107. metadatas.removeAll()
  108. cache.removeAllValues()
  109. }
  110. func getMediaMetadatas(account: String, predicate: NSPredicate? = nil) {
  111. guard let account = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", account)) else { return }
  112. let startServerUrl = NCUtilityFileSystem().getHomeServer(urlBase: account.urlBase, userId: account.userId) + account.mediaPath
  113. let predicateDefault = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND (classFile == %@ OR classFile == %@) AND NOT (session CONTAINS[c] 'upload')", account.account, startServerUrl, NKCommon.TypeClassFile.image.rawValue, NKCommon.TypeClassFile.video.rawValue)
  114. livePhoto = NCKeychain().livePhoto
  115. let newMetadatas = NCManageDatabase.shared.getMetadatasMedia(predicate: predicate ?? predicateDefault, livePhoto: livePhoto)
  116. if metadatas != newMetadatas {
  117. metadatas = newMetadatas
  118. }
  119. switch NCKeychain().mediaSortDate {
  120. case "date":
  121. metadatas = self.metadatas.sorted(by: {($0.date as Date) > ($1.date as Date)})
  122. case "creationDate":
  123. metadatas = self.metadatas.sorted(by: {($0.creationDate as Date) > ($1.creationDate as Date)})
  124. case "uploadDate":
  125. metadatas = self.metadatas.sorted(by: {($0.uploadDate as Date) > ($1.uploadDate as Date)})
  126. default:
  127. break
  128. }
  129. }
  130. // MARK: -
  131. struct images {
  132. static var file = UIImage()
  133. static var shared = UIImage()
  134. static var canShare = UIImage()
  135. static var shareByLink = UIImage()
  136. static var favorite = UIImage()
  137. static var comment = UIImage()
  138. static var livePhoto = UIImage()
  139. static var offlineFlag = UIImage()
  140. static var local = UIImage()
  141. static var folderEncrypted = UIImage()
  142. static var folderSharedWithMe = UIImage()
  143. static var folderPublic = UIImage()
  144. static var folderGroup = UIImage()
  145. static var folderExternal = UIImage()
  146. static var folderAutomaticUpload = UIImage()
  147. static var folder = UIImage()
  148. static var checkedYes = UIImage()
  149. static var checkedNo = UIImage()
  150. static var buttonMore = UIImage()
  151. static var buttonStop = UIImage()
  152. static var buttonMoreLock = UIImage()
  153. static var buttonRestore = UIImage()
  154. static var buttonTrash = UIImage()
  155. static var iconContacts = UIImage()
  156. static var iconTalk = UIImage()
  157. static var iconCalendar = UIImage()
  158. static var iconDeck = UIImage()
  159. static var iconMail = UIImage()
  160. static var iconConfirm = UIImage()
  161. static var iconPages = UIImage()
  162. }
  163. func createImagesCache() {
  164. let brandElement = NCBrandColor.shared.brandElement
  165. let yellowFavorite = NCBrandColor.shared.yellowFavorite
  166. let utility = NCUtility()
  167. images.file = UIImage(named: "file")!
  168. images.shared = UIImage(named: "share")!.image(color: .systemGray, size: 50)
  169. images.canShare = UIImage(named: "share")!.image(color: .systemGray, size: 50)
  170. images.shareByLink = UIImage(named: "sharebylink")!.image(color: .systemGray, size: 50)
  171. images.favorite = utility.loadImage(named: "star.fill", color: yellowFavorite)
  172. images.comment = UIImage(named: "comment")!.image(color: .systemGray, size: 50)
  173. images.livePhoto = utility.loadImage(named: "livephoto", color: .label)
  174. images.offlineFlag = UIImage(named: "offlineFlag")!
  175. images.local = UIImage(named: "local")!
  176. let folderWidth: CGFloat = UIScreen.main.bounds.width / 3
  177. images.folderEncrypted = UIImage(named: "folderEncrypted")!.image(color: brandElement, size: folderWidth)
  178. images.folderSharedWithMe = UIImage(named: "folder_shared_with_me")!.image(color: brandElement, size: folderWidth)
  179. images.folderPublic = UIImage(named: "folder_public")!.image(color: brandElement, size: folderWidth)
  180. images.folderGroup = UIImage(named: "folder_group")!.image(color: brandElement, size: folderWidth)
  181. images.folderExternal = UIImage(named: "folder_external")!.image(color: brandElement, size: folderWidth)
  182. images.folderAutomaticUpload = UIImage(named: "folderAutomaticUpload")!.image(color: brandElement, size: folderWidth)
  183. images.folder = UIImage(named: "folder")!.image(color: brandElement, size: folderWidth)
  184. images.checkedYes = utility.loadImage(named: "checkmark.circle.fill", color: .systemBlue)
  185. images.checkedNo = utility.loadImage(named: "circle", color: .systemGray)
  186. images.buttonMore = UIImage(named: "more")!.image(color: .systemGray, size: 50)
  187. images.buttonStop = UIImage(named: "stop")!.image(color: .systemGray, size: 50)
  188. images.buttonMoreLock = UIImage(named: "moreLock")!.image(color: .systemGray, size: 50)
  189. images.buttonRestore = UIImage(named: "restore")!.image(color: .systemGray, size: 50)
  190. images.buttonTrash = UIImage(named: "trash")!.image(color: .systemGray, size: 50)
  191. images.iconContacts = UIImage(named: "icon-contacts")!.image(color: brandElement, size: folderWidth)
  192. images.iconTalk = UIImage(named: "icon-talk")!.image(color: brandElement, size: folderWidth)
  193. images.iconCalendar = UIImage(named: "icon-calendar")!.image(color: brandElement, size: folderWidth)
  194. images.iconDeck = UIImage(named: "icon-deck")!.image(color: brandElement, size: folderWidth)
  195. images.iconMail = UIImage(named: "icon-mail")!.image(color: brandElement, size: folderWidth)
  196. images.iconConfirm = UIImage(named: "icon-confirm")!.image(color: brandElement, size: folderWidth)
  197. images.iconPages = UIImage(named: "icon-pages")!.image(color: brandElement, size: folderWidth)
  198. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterChangeTheming)
  199. }
  200. }