|
| 1 | +// |
| 2 | +// ResourceCache.swift |
| 3 | +// PCL.Mac |
| 4 | +// |
| 5 | +// Created by AnemoFlower on 2026/6/7. |
| 6 | +// |
| 7 | + |
| 8 | +import Foundation |
| 9 | + |
| 10 | +public class ResourceCache { |
| 11 | + public static var shared: ResourceCache! |
| 12 | + |
| 13 | + private let cacheFileURL: URL |
| 14 | + private let iconCacheDirectory: URL |
| 15 | + private var cacheMap: [String: Resource] |
| 16 | + |
| 17 | + public init(cacheDirectory: URL) { |
| 18 | + self.cacheFileURL = cacheDirectory.appending(path: "resource_cache.json") |
| 19 | + self.iconCacheDirectory = cacheDirectory.appending(path: "resource_icon") |
| 20 | + |
| 21 | + if FileManager.default.fileExists(atPath: cacheFileURL.path) { |
| 22 | + do { |
| 23 | + let data = try Data(contentsOf: cacheFileURL) |
| 24 | + self.cacheMap = try JSONDecoder.shared.decode([String: Resource].self, from: data) |
| 25 | + } catch { |
| 26 | + err("缓存文件加载失败:\(error.localizedDescription)") |
| 27 | + try? FileManager.default.removeItem(at: cacheFileURL) |
| 28 | + self.cacheMap = [:] |
| 29 | + } |
| 30 | + } else { |
| 31 | + self.cacheMap = [:] |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + public func resource(forHash hash: String) -> Resource? { cacheMap[hash] } |
| 36 | + |
| 37 | + public func store(_ resource: Resource, forHash hash: String) { cacheMap[hash] = resource } |
| 38 | + |
| 39 | + public func icon(forHash globalHash: String) throws -> Data? { |
| 40 | + let url = url(of: globalHash) |
| 41 | + if FileManager.default.fileExists(atPath: url.path) { |
| 42 | + return try Data(contentsOf: url) |
| 43 | + } |
| 44 | + return nil |
| 45 | + } |
| 46 | + |
| 47 | + public func store(_ iconData: Data, relativePath: String, fileHash: String) throws -> String { |
| 48 | + let globalHash = globalHash(of: relativePath, with: fileHash) |
| 49 | + let url = url(of: globalHash) |
| 50 | + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) |
| 51 | + try iconData.write(to: url) |
| 52 | + return globalHash |
| 53 | + } |
| 54 | + |
| 55 | + public func save() throws { |
| 56 | + try FileManager.default.createDirectory(at: cacheFileURL.deletingLastPathComponent(), withIntermediateDirectories: true) |
| 57 | + let data = try JSONEncoder.shared.encode(cacheMap) |
| 58 | + try data.write(to: cacheFileURL) |
| 59 | + } |
| 60 | + |
| 61 | + |
| 62 | + private func url(of globalHash: String) -> URL { |
| 63 | + return iconCacheDirectory.appending(path: "\(globalHash.prefix(2))/\(globalHash)") |
| 64 | + } |
| 65 | + |
| 66 | + private func globalHash(of path: String, with fileHash: String) -> String { |
| 67 | + return (fileHash + path).sha1 |
| 68 | + } |
| 69 | +} |
0 commit comments